title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Chessboard Pawn-Pawn game - GeeksforGeeks
|
02 Jun, 2021
There is an 8*8 chessboard and two chess players having a single pawn each. A player has to move his pawn in each turn, either one step forward or one step diagonally only when this move kills the other pawn. The player who is unable to make any move loses. Given row and column numbers of white and black pawns. The task is to predict who would win assuming both plays optimally. Note that White plays first and a pawn cannot move outside the chessboard.
Examples:
Input: rowW = 2, colW = 2, rowB = 3, colB = 3 Output: WhiteInput: rowW = 2, colW = 2, rowB = 3, colB = 3 Output: White
Approach:
If its white pawn’s turn we have to check whether white pawn is on the 8th row then black wins because white pawn has no further move. If it’s black pawn’s turn then we have to check whether it is on the 1st row then white wins because black pawn has no further move.
If its white pawn’s turn and black pawn is adjacent diagonally then white pawn will kill black pawn and white pawn wins else white pawn will move one step forward (if not already occupied by the black pawn) else white will lose.
If it’s black pawn’s turn and white pawn is adjacent diagonally then black pawn will kill white pawn and black pawn wins else black pawn will move one step forward (if not already occupied by the white pawn) else black will lose.
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 that returns true if white winsbool whiteWins(int rowW, int colW, int rowB, int colB){ int white = 0, black = 0; while (1) { // If white can move if (rowW != 8) { // If white pawn can kill black pawn // White wins if (rowB == rowW + 1 && (colB == colW - 1 || colB == colW + 1)) return true; // Make the move forward else rowW++; } // White has no moves // White loses else return false; // If black can move if (rowB != 1) { // If black pawn can kill white pawn // White loses if (rowB == rowW + 1 && (colB == colW - 1 || colB == colW + 1)) return false; // Make the move forward else rowB--; } // Black has no moves // White wins else return true; } // If white has got more moves if (white > black) return true; return false;} // Driver codeint main(){ int rowW = 2, colW = 2, rowB = 3, colB = 3; if (whiteWins(rowW, colW, rowB, colB)) cout << "White"; else cout << "Black"; return 0;}
// Java implementation of the approachclass GFG{ // Function that returns true if white winsstatic boolean whiteWins(int rowW, int colW, int rowB, int colB){ int white = 0, black = 0; boolean flag=true; while (flag) { // If white can move if (rowW != 8) { // If white pawn can kill black pawn // White wins if (rowB == rowW + 1 && (colB == colW - 1 || colB == colW + 1)) return true; // Make the move forward else rowW++; } // White has no moves // White loses else return false; // If black can move if (rowB != 1) { // If black pawn can kill white pawn // White loses if (rowB == rowW + 1 && (colB == colW - 1 || colB == colW + 1)) return false; // Make the move forward else rowB--; } // Black has no moves // White wins else return true; } // If white has got more moves if (white > black) return true; return false;} // Driver codepublic static void main(String args[]){ int rowW = 2, colW = 2, rowB = 3, colB = 3; if (whiteWins(rowW, colW, rowB, colB)) System.out.println("White"); else System.out.println("Black");}} // This code is contributed by Arnab Kundu
# Print implementation of the approach # Function that returns true if white winsdef whiteWins(rowW, colW, rowB, colB): white = 0; black = 0; while (1): # If white can move if (rowW != 8): # If white pawn can kill black pawn # White wins if (rowB == rowW + 1 and (colB == colW - 1 or colB == colW + 1)): return True; # Make the move forward else: rowW += 1; # White has no moves # White loses else: return False; # If black can move if (rowB != 1): # If black pawn can kill white pawn # White loses if (rowB == rowW + 1 and (colB == colW - 1 or colB == colW + 1)): return False; # Make the move forward else: rowB -= 1; # Black has no moves # White wins else: return Frue; # If white has got more moves if (white > black): return True; return False; # Driver codeif __name__ == '__main__': rowW, colW = 2, 2; rowB, colB = 3, 3; if (whiteWins(rowW, colW, rowB, colB)): print("White"); else: print("Black"); # This code is contributed by Rajput-Ji
// C# implementation of the approachusing System;public class GFG{ // Function that returns true if white winsstatic bool whiteWins(int rowW, int colW, int rowB, int colB){ int white = 0, black = 0; bool flag=true; while (flag) { // If white can move if (rowW != 8) { // If white pawn can kill black pawn // White wins if (rowB == rowW + 1 && (colB == colW - 1 || colB == colW + 1)) return true; // Make the move forward else rowW++; } // White has no moves // White loses else return false; // If black can move if (rowB != 1) { // If black pawn can kill white pawn // White loses if (rowB == rowW + 1 && (colB == colW - 1 || colB == colW + 1)) return false; // Make the move forward else rowB--; } // Black has no moves // White wins else return true; } // If white has got more moves if (white > black) return true; return false;} // Driver codepublic static void Main(String []args){ int rowW = 2, colW = 2, rowB = 3, colB = 3; if (whiteWins(rowW, colW, rowB, colB)) Console.WriteLine("White"); else Console.WriteLine("Black");}}/* This code contributed by PrinciRaj1992 */
<script> // JavaScript implementation of the approach // Function that returns true if white wins function whiteWins(rowW , colW , rowB , colB) { var white = 0, black = 0; var flag = true; while (flag) { // If white can move if (rowW != 8) { // If white pawn can kill black pawn // White wins if (rowB == rowW + 1 && (colB == colW - 1 || colB == colW + 1)) return true; // Make the move forward else rowW++; } // White has no moves // White loses else return false; // If black can move if (rowB != 1) { // If black pawn can kill white pawn // White loses if (rowB == rowW + 1 && (colB == colW - 1 || colB == colW + 1)) return false; // Make the move forward else rowB--; } // Black has no moves // White wins else return true; } // If white has got more moves if (white > black) return true; return false; } // Driver code var rowW = 2, colW = 2, rowB = 3, colB = 3; if (whiteWins(rowW, colW, rowB, colB)) document.write("White"); else document.write("Black"); // This code contributed by aashish1995 </script>
White
andrew1234
princiraj1992
Rajput-Ji
aashish1995
chessboard-problems
Competitive Programming
Game Theory
Game Theory
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Modulo 10^9+7 (1000000007)
Bits manipulation (Important tactics)
Prefix Sum Array - Implementation and Applications in Competitive Programming
Formatted output in Java
Algorithm Library | C++ Magicians STL Algorithm
Minimax Algorithm in Game Theory | Set 1 (Introduction)
Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move)
Minimax Algorithm in Game Theory | Set 4 (Alpha-Beta Pruning)
Implementation of Tic-Tac-Toe game
Optimal Strategy for a Game | DP-31
|
[
{
"code": null,
"e": 25278,
"s": 25250,
"text": "\n02 Jun, 2021"
},
{
"code": null,
"e": 25735,
"s": 25278,
"text": "There is an 8*8 chessboard and two chess players having a single pawn each. A player has to move his pawn in each turn, either one step forward or one step diagonally only when this move kills the other pawn. The player who is unable to make any move loses. Given row and column numbers of white and black pawns. The task is to predict who would win assuming both plays optimally. Note that White plays first and a pawn cannot move outside the chessboard. "
},
{
"code": null,
"e": 25747,
"s": 25735,
"text": "Examples: "
},
{
"code": null,
"e": 25868,
"s": 25747,
"text": "Input: rowW = 2, colW = 2, rowB = 3, colB = 3 Output: WhiteInput: rowW = 2, colW = 2, rowB = 3, colB = 3 Output: White "
},
{
"code": null,
"e": 25882,
"s": 25870,
"text": "Approach: "
},
{
"code": null,
"e": 26150,
"s": 25882,
"text": "If its white pawn’s turn we have to check whether white pawn is on the 8th row then black wins because white pawn has no further move. If it’s black pawn’s turn then we have to check whether it is on the 1st row then white wins because black pawn has no further move."
},
{
"code": null,
"e": 26379,
"s": 26150,
"text": "If its white pawn’s turn and black pawn is adjacent diagonally then white pawn will kill black pawn and white pawn wins else white pawn will move one step forward (if not already occupied by the black pawn) else white will lose."
},
{
"code": null,
"e": 26609,
"s": 26379,
"text": "If it’s black pawn’s turn and white pawn is adjacent diagonally then black pawn will kill white pawn and black pawn wins else black pawn will move one step forward (if not already occupied by the white pawn) else black will lose."
},
{
"code": null,
"e": 26662,
"s": 26609,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26666,
"s": 26662,
"text": "C++"
},
{
"code": null,
"e": 26671,
"s": 26666,
"text": "Java"
},
{
"code": null,
"e": 26679,
"s": 26671,
"text": "Python3"
},
{
"code": null,
"e": 26682,
"s": 26679,
"text": "C#"
},
{
"code": null,
"e": 26693,
"s": 26682,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns true if white winsbool whiteWins(int rowW, int colW, int rowB, int colB){ int white = 0, black = 0; while (1) { // If white can move if (rowW != 8) { // If white pawn can kill black pawn // White wins if (rowB == rowW + 1 && (colB == colW - 1 || colB == colW + 1)) return true; // Make the move forward else rowW++; } // White has no moves // White loses else return false; // If black can move if (rowB != 1) { // If black pawn can kill white pawn // White loses if (rowB == rowW + 1 && (colB == colW - 1 || colB == colW + 1)) return false; // Make the move forward else rowB--; } // Black has no moves // White wins else return true; } // If white has got more moves if (white > black) return true; return false;} // Driver codeint main(){ int rowW = 2, colW = 2, rowB = 3, colB = 3; if (whiteWins(rowW, colW, rowB, colB)) cout << \"White\"; else cout << \"Black\"; return 0;}",
"e": 28043,
"s": 26693,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ // Function that returns true if white winsstatic boolean whiteWins(int rowW, int colW, int rowB, int colB){ int white = 0, black = 0; boolean flag=true; while (flag) { // If white can move if (rowW != 8) { // If white pawn can kill black pawn // White wins if (rowB == rowW + 1 && (colB == colW - 1 || colB == colW + 1)) return true; // Make the move forward else rowW++; } // White has no moves // White loses else return false; // If black can move if (rowB != 1) { // If black pawn can kill white pawn // White loses if (rowB == rowW + 1 && (colB == colW - 1 || colB == colW + 1)) return false; // Make the move forward else rowB--; } // Black has no moves // White wins else return true; } // If white has got more moves if (white > black) return true; return false;} // Driver codepublic static void main(String args[]){ int rowW = 2, colW = 2, rowB = 3, colB = 3; if (whiteWins(rowW, colW, rowB, colB)) System.out.println(\"White\"); else System.out.println(\"Black\");}} // This code is contributed by Arnab Kundu",
"e": 29522,
"s": 28043,
"text": null
},
{
"code": "# Print implementation of the approach # Function that returns true if white winsdef whiteWins(rowW, colW, rowB, colB): white = 0; black = 0; while (1): # If white can move if (rowW != 8): # If white pawn can kill black pawn # White wins if (rowB == rowW + 1 and (colB == colW - 1 or colB == colW + 1)): return True; # Make the move forward else: rowW += 1; # White has no moves # White loses else: return False; # If black can move if (rowB != 1): # If black pawn can kill white pawn # White loses if (rowB == rowW + 1 and (colB == colW - 1 or colB == colW + 1)): return False; # Make the move forward else: rowB -= 1; # Black has no moves # White wins else: return Frue; # If white has got more moves if (white > black): return True; return False; # Driver codeif __name__ == '__main__': rowW, colW = 2, 2; rowB, colB = 3, 3; if (whiteWins(rowW, colW, rowB, colB)): print(\"White\"); else: print(\"Black\"); # This code is contributed by Rajput-Ji",
"e": 30850,
"s": 29522,
"text": null
},
{
"code": "// C# implementation of the approachusing System;public class GFG{ // Function that returns true if white winsstatic bool whiteWins(int rowW, int colW, int rowB, int colB){ int white = 0, black = 0; bool flag=true; while (flag) { // If white can move if (rowW != 8) { // If white pawn can kill black pawn // White wins if (rowB == rowW + 1 && (colB == colW - 1 || colB == colW + 1)) return true; // Make the move forward else rowW++; } // White has no moves // White loses else return false; // If black can move if (rowB != 1) { // If black pawn can kill white pawn // White loses if (rowB == rowW + 1 && (colB == colW - 1 || colB == colW + 1)) return false; // Make the move forward else rowB--; } // Black has no moves // White wins else return true; } // If white has got more moves if (white > black) return true; return false;} // Driver codepublic static void Main(String []args){ int rowW = 2, colW = 2, rowB = 3, colB = 3; if (whiteWins(rowW, colW, rowB, colB)) Console.WriteLine(\"White\"); else Console.WriteLine(\"Black\");}}/* This code contributed by PrinciRaj1992 */",
"e": 32353,
"s": 30850,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach // Function that returns true if white wins function whiteWins(rowW , colW , rowB , colB) { var white = 0, black = 0; var flag = true; while (flag) { // If white can move if (rowW != 8) { // If white pawn can kill black pawn // White wins if (rowB == rowW + 1 && (colB == colW - 1 || colB == colW + 1)) return true; // Make the move forward else rowW++; } // White has no moves // White loses else return false; // If black can move if (rowB != 1) { // If black pawn can kill white pawn // White loses if (rowB == rowW + 1 && (colB == colW - 1 || colB == colW + 1)) return false; // Make the move forward else rowB--; } // Black has no moves // White wins else return true; } // If white has got more moves if (white > black) return true; return false; } // Driver code var rowW = 2, colW = 2, rowB = 3, colB = 3; if (whiteWins(rowW, colW, rowB, colB)) document.write(\"White\"); else document.write(\"Black\"); // This code contributed by aashish1995 </script>",
"e": 33912,
"s": 32353,
"text": null
},
{
"code": null,
"e": 33918,
"s": 33912,
"text": "White"
},
{
"code": null,
"e": 33931,
"s": 33920,
"text": "andrew1234"
},
{
"code": null,
"e": 33945,
"s": 33931,
"text": "princiraj1992"
},
{
"code": null,
"e": 33955,
"s": 33945,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 33967,
"s": 33955,
"text": "aashish1995"
},
{
"code": null,
"e": 33987,
"s": 33967,
"text": "chessboard-problems"
},
{
"code": null,
"e": 34011,
"s": 33987,
"text": "Competitive Programming"
},
{
"code": null,
"e": 34023,
"s": 34011,
"text": "Game Theory"
},
{
"code": null,
"e": 34035,
"s": 34023,
"text": "Game Theory"
},
{
"code": null,
"e": 34133,
"s": 34035,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34142,
"s": 34133,
"text": "Comments"
},
{
"code": null,
"e": 34155,
"s": 34142,
"text": "Old Comments"
},
{
"code": null,
"e": 34182,
"s": 34155,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 34220,
"s": 34182,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 34298,
"s": 34220,
"text": "Prefix Sum Array - Implementation and Applications in Competitive Programming"
},
{
"code": null,
"e": 34323,
"s": 34298,
"text": "Formatted output in Java"
},
{
"code": null,
"e": 34371,
"s": 34323,
"text": "Algorithm Library | C++ Magicians STL Algorithm"
},
{
"code": null,
"e": 34427,
"s": 34371,
"text": "Minimax Algorithm in Game Theory | Set 1 (Introduction)"
},
{
"code": null,
"e": 34508,
"s": 34427,
"text": "Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move)"
},
{
"code": null,
"e": 34570,
"s": 34508,
"text": "Minimax Algorithm in Game Theory | Set 4 (Alpha-Beta Pruning)"
},
{
"code": null,
"e": 34605,
"s": 34570,
"text": "Implementation of Tic-Tac-Toe game"
}
] |
Linear Algebra for Natural Language Processing | by Taaniya Arora | Towards Data Science
|
The field of Natural Language Processing involves building techniques to process text in natural language by people like you and me, and extract insights from it for performing a variety of tasks from interpreting user queries on search engines and returning web pages, to solving customer queries as chatbot assistant. The importance of representing every word into a form that captures the meaning of the word and the overall context becomes crucial especially when major decisions are based upon the insights extracted from text on a large scale — like forecasting stock price change with social media.
In this article, we’ll begin with the basics of linear algebra to get an intuition of sof vectors and their significance for representing specific types of information, the different ways of representing text in vector space, and how the concept has evolved to the state of the art models we have now.
We’ll step through the following areas -
Unit vectors in our coordinate system
Linear combination of vectors
Span in vector coordinate system
Collinearity & multicollinearity
Linear dependence and independence of vectors
Basis vectors
Vector Space Model for NLP
Dense Vectors
i-> Denotes a unit vector (vector of length 1 unit) pointing in the x-direction
j -> Denotes a unit vector in the y-direction
Together, they are called the basis of our coordinate vector space.
We’ll come to the term basis more in the subsequent parts below.
Suppose we have a vector 3i+ 5j
This vector has x,y coordinates : 3 & 5 respectively
These coordinates are the scalars that flip and scale the unit vectors by 3 & 5 units in the x & y directions respectively
If u & v are two vectors in a 2 dimensional space,then their linear combination resulting into a vector l is represented by -
l = x1. u + x2. v
The numbers x1, x2 are the components of a vector x
This is essentially a scaling and addition operation by x on the given vectors.
The above expression of linear combination is equivalent to the following linear system -
Bx = l
Where B denotes a matrix whose columns are u and v.
Let’s understand this by an example below with vectors u & v in a 2 dimensional space -
# Vectors u & v# The vectors are 3D, we'll only use 2 dimensionsu_vec = np.array([1, -1, 0])v_vec = np.array([0, 1, -1])# Vector xx_vec = np.array([1.5, 2])# Plotting them# fetch coords from first 2 dimensionsdata = np.vstack((u_vec, v_vec))[:,:2]origin = np.array([[0, 0, 0], [0, 0, 0]])[:,:2]plt.ylim(-2,3)plt.xlim(-2,3)QV = plt.quiver(origin[:,0],origin[:,1], data[:, 0], data[:, 1], color=['black', 'green'], angles='xy', scale_units='xy', scale=1.)plt.grid()plt.xlabel("x-axis")plt.ylabel("y-axis")plt.show()
We can also understand it from this explanation for a similar example with 3 dimensions given by a Professor in his notes here -
Taking the 3 vectors from the example in the image and plotting them in 3D space (The units of axes are different than the vectors in the plot)
u_vec = np.array([1, -1, 0])v_vec = np.array([0, 1, -1])w_vec = np.array([0, 0, 1])data = np.vstack((u_vec, v_vec, w_vec))origin = np.array([[0, 0, 0], [0, 0, 0], [0, 0, 0]])fig = plt.figure()ax = fig.add_subplot(111, projection='3d')ax.quiver(origin[:,0],origin[:,1], origin[:,2], data[:, 0], data[:, 1], data[:,2])ax.set_xlim([-1, 2])ax.set_ylim([-1, 2])ax.set_zlim([-1, 2])plt.grid()plt.show()
A span is a set of all possible combinations of vectors that we can reach with a linear combination of a given pair of vectors
The span of most pairs of 2-D vectors is all vectors in the 2-D space. Except, when they line up in the same direction (i.e if they are collinear) , in which case, their span is a line.
i.e span( a, b) = R2 (all vectors in 2D space) , provided they are not collinear.
Collinearity is the case when we have p different predictor variables but some of them are linear combinations of others, so they don’t add any other information. 2 collinear vectors / variables will have correlation close to +/- 1 and can be detected by their correlation matrix.
Multicollinearity exists when more than 2 vectors are collinear and any pair of vectors may not necessarily have high correlation.
Linear Independence
We say that v1 , v2, . . . , vn are linearly independent, if none of them is
a linear combination of the others. This is equivalent to saying
that x1.v1 + x2.v2 + . . . + xn.vn = 0 implies x1 = x2 = . . . = xn = 0
Since collinear vectors can be expressed as linear combinations of each other, they are linearly dependent.
A basis is that set of linearly independent vectors that span that space.
We call these vectors as basis vectors
A Vector space is a set V of vectors, where two operations — vector addition and scalar multiplication are defined. For E.g. If two vectors u & v are in space V, then their sum, w = u + v will also lie in the vector space V.
A 2D vector space is a set of linearly independent basis vectors with 2 axes.
Each axis represents a dimension in the vector space.
Recalling the previous plot of vector a = (3,5) = 3 i + 5 j again. This vector is represented on a 2D space with 2 linearly independent basis vectors — X & Y, who also represent the 2 axes as well as the 2 dimenions of the space.
3 & 5 here are the x,y components of this vector for representation on the X-Y 2D space.
A vector space model is a representation of text in vector space.
Here, each word in a corpus is a linearly independent basis vector and each basis vector represents an axis in the vector space.
This means, each word is orthogonal to other words/axes.
For a corpus of vocabulary |V|, R will contain |V| axes.
Combination of terms represent documents as points or vectors in this space
For 3 words, we’ll have a 3D vector model represented like this -
The table above the graph represents the TF-IDF incident matrix.
D1 = (0.91, 0, 0.0011) represents a document vector in the 3 axes — good, house, car. Similarly, we have D2 & D3 document vectors.
How does representation in vector space help us, though?
One of the common application using this representation is information retrieval for search engines, question answering systems and much more.
By representing the text into vectors, we aim to use vector algebra to extract semantics from the text and use it for different applications like searching documents containing the similar sementics as those contained in a given search query.
For eg. For a search token ‘buy’ , we would want to get all the documents containing different forms of this word — buying, bought and even synonyms of the word ‘buy’. Such documents can not be captured from other rudimentary methods representing documents as Binary incident matrix.
This is achieved through distance metrics like cosine similarity between vectors of document & query, where the documents closer to the query are ranked the highest.
The number of words / vocabulary size can be as huge as in millions eg. Google news corpus is 3 Million, which means as many independent axes/dimensions to represent the vectors. Hence, we want to use the operations in vector space to reduce the number of dimensions and bring words with similar to each other in the same axis.
The above operations are possible on document vectors which are represented by extending the above vector representation of documents to documents represented as distributed or dense vectors. These representations capture the semantics of the text and also captures the linear combinations of word vectors
The previous vector space model with each word representing a separate dimension results in sparse vectors.
Dense vectors captures the context in the vector representation. The dense vector of words are such that words appearing in similar contexts will have similar representations.
These dense vectors are also called as word embeddings or distributed representations.
word2vec is one such framework to learn dense vectors of words from large corpus. It has 2 variants — skip-gram and CBOW(continuous bag of words)
Some of the other frameworks and techniques to obtain dense vectors are Global Vectors(GloVe), fastText, ELMo(Embeddings from Language Model) and most recent state of the art Bert based approached to obtain contextualized word embeddings during inference.
This article introduced the concept of vector space based on linear algebra and highlighted the related concepts as part of their application in Natural Language Processing for representing text documents in semantics representation and extraction tasks.
The applications of word embeddings have been extended to more advanced and wide applications with much improved performance than earlier.
You can also refer to the source code and run on colab by accessing my Git repository here.
Hope you enjoyed reading it. :)
Linear Independence, Basis & Dimension, MIT
Matrices-Introduction to Vectors, MIT
Vector space models for NLP, NPTEL
An introduction to statistical learning, E-Book by Gareth James, Daniela Witten, Trevor Hastie and Robert Tibshirani
|
[
{
"code": null,
"e": 777,
"s": 171,
"text": "The field of Natural Language Processing involves building techniques to process text in natural language by people like you and me, and extract insights from it for performing a variety of tasks from interpreting user queries on search engines and returning web pages, to solving customer queries as chatbot assistant. The importance of representing every word into a form that captures the meaning of the word and the overall context becomes crucial especially when major decisions are based upon the insights extracted from text on a large scale — like forecasting stock price change with social media."
},
{
"code": null,
"e": 1079,
"s": 777,
"text": "In this article, we’ll begin with the basics of linear algebra to get an intuition of sof vectors and their significance for representing specific types of information, the different ways of representing text in vector space, and how the concept has evolved to the state of the art models we have now."
},
{
"code": null,
"e": 1120,
"s": 1079,
"text": "We’ll step through the following areas -"
},
{
"code": null,
"e": 1158,
"s": 1120,
"text": "Unit vectors in our coordinate system"
},
{
"code": null,
"e": 1188,
"s": 1158,
"text": "Linear combination of vectors"
},
{
"code": null,
"e": 1221,
"s": 1188,
"text": "Span in vector coordinate system"
},
{
"code": null,
"e": 1254,
"s": 1221,
"text": "Collinearity & multicollinearity"
},
{
"code": null,
"e": 1300,
"s": 1254,
"text": "Linear dependence and independence of vectors"
},
{
"code": null,
"e": 1314,
"s": 1300,
"text": "Basis vectors"
},
{
"code": null,
"e": 1341,
"s": 1314,
"text": "Vector Space Model for NLP"
},
{
"code": null,
"e": 1355,
"s": 1341,
"text": "Dense Vectors"
},
{
"code": null,
"e": 1435,
"s": 1355,
"text": "i-> Denotes a unit vector (vector of length 1 unit) pointing in the x-direction"
},
{
"code": null,
"e": 1481,
"s": 1435,
"text": "j -> Denotes a unit vector in the y-direction"
},
{
"code": null,
"e": 1549,
"s": 1481,
"text": "Together, they are called the basis of our coordinate vector space."
},
{
"code": null,
"e": 1614,
"s": 1549,
"text": "We’ll come to the term basis more in the subsequent parts below."
},
{
"code": null,
"e": 1646,
"s": 1614,
"text": "Suppose we have a vector 3i+ 5j"
},
{
"code": null,
"e": 1699,
"s": 1646,
"text": "This vector has x,y coordinates : 3 & 5 respectively"
},
{
"code": null,
"e": 1822,
"s": 1699,
"text": "These coordinates are the scalars that flip and scale the unit vectors by 3 & 5 units in the x & y directions respectively"
},
{
"code": null,
"e": 1948,
"s": 1822,
"text": "If u & v are two vectors in a 2 dimensional space,then their linear combination resulting into a vector l is represented by -"
},
{
"code": null,
"e": 1966,
"s": 1948,
"text": "l = x1. u + x2. v"
},
{
"code": null,
"e": 2018,
"s": 1966,
"text": "The numbers x1, x2 are the components of a vector x"
},
{
"code": null,
"e": 2098,
"s": 2018,
"text": "This is essentially a scaling and addition operation by x on the given vectors."
},
{
"code": null,
"e": 2188,
"s": 2098,
"text": "The above expression of linear combination is equivalent to the following linear system -"
},
{
"code": null,
"e": 2195,
"s": 2188,
"text": "Bx = l"
},
{
"code": null,
"e": 2247,
"s": 2195,
"text": "Where B denotes a matrix whose columns are u and v."
},
{
"code": null,
"e": 2335,
"s": 2247,
"text": "Let’s understand this by an example below with vectors u & v in a 2 dimensional space -"
},
{
"code": null,
"e": 2849,
"s": 2335,
"text": "# Vectors u & v# The vectors are 3D, we'll only use 2 dimensionsu_vec = np.array([1, -1, 0])v_vec = np.array([0, 1, -1])# Vector xx_vec = np.array([1.5, 2])# Plotting them# fetch coords from first 2 dimensionsdata = np.vstack((u_vec, v_vec))[:,:2]origin = np.array([[0, 0, 0], [0, 0, 0]])[:,:2]plt.ylim(-2,3)plt.xlim(-2,3)QV = plt.quiver(origin[:,0],origin[:,1], data[:, 0], data[:, 1], color=['black', 'green'], angles='xy', scale_units='xy', scale=1.)plt.grid()plt.xlabel(\"x-axis\")plt.ylabel(\"y-axis\")plt.show()"
},
{
"code": null,
"e": 2978,
"s": 2849,
"text": "We can also understand it from this explanation for a similar example with 3 dimensions given by a Professor in his notes here -"
},
{
"code": null,
"e": 3122,
"s": 2978,
"text": "Taking the 3 vectors from the example in the image and plotting them in 3D space (The units of axes are different than the vectors in the plot)"
},
{
"code": null,
"e": 3519,
"s": 3122,
"text": "u_vec = np.array([1, -1, 0])v_vec = np.array([0, 1, -1])w_vec = np.array([0, 0, 1])data = np.vstack((u_vec, v_vec, w_vec))origin = np.array([[0, 0, 0], [0, 0, 0], [0, 0, 0]])fig = plt.figure()ax = fig.add_subplot(111, projection='3d')ax.quiver(origin[:,0],origin[:,1], origin[:,2], data[:, 0], data[:, 1], data[:,2])ax.set_xlim([-1, 2])ax.set_ylim([-1, 2])ax.set_zlim([-1, 2])plt.grid()plt.show()"
},
{
"code": null,
"e": 3646,
"s": 3519,
"text": "A span is a set of all possible combinations of vectors that we can reach with a linear combination of a given pair of vectors"
},
{
"code": null,
"e": 3832,
"s": 3646,
"text": "The span of most pairs of 2-D vectors is all vectors in the 2-D space. Except, when they line up in the same direction (i.e if they are collinear) , in which case, their span is a line."
},
{
"code": null,
"e": 3914,
"s": 3832,
"text": "i.e span( a, b) = R2 (all vectors in 2D space) , provided they are not collinear."
},
{
"code": null,
"e": 4195,
"s": 3914,
"text": "Collinearity is the case when we have p different predictor variables but some of them are linear combinations of others, so they don’t add any other information. 2 collinear vectors / variables will have correlation close to +/- 1 and can be detected by their correlation matrix."
},
{
"code": null,
"e": 4326,
"s": 4195,
"text": "Multicollinearity exists when more than 2 vectors are collinear and any pair of vectors may not necessarily have high correlation."
},
{
"code": null,
"e": 4346,
"s": 4326,
"text": "Linear Independence"
},
{
"code": null,
"e": 4423,
"s": 4346,
"text": "We say that v1 , v2, . . . , vn are linearly independent, if none of them is"
},
{
"code": null,
"e": 4488,
"s": 4423,
"text": "a linear combination of the others. This is equivalent to saying"
},
{
"code": null,
"e": 4560,
"s": 4488,
"text": "that x1.v1 + x2.v2 + . . . + xn.vn = 0 implies x1 = x2 = . . . = xn = 0"
},
{
"code": null,
"e": 4668,
"s": 4560,
"text": "Since collinear vectors can be expressed as linear combinations of each other, they are linearly dependent."
},
{
"code": null,
"e": 4742,
"s": 4668,
"text": "A basis is that set of linearly independent vectors that span that space."
},
{
"code": null,
"e": 4781,
"s": 4742,
"text": "We call these vectors as basis vectors"
},
{
"code": null,
"e": 5006,
"s": 4781,
"text": "A Vector space is a set V of vectors, where two operations — vector addition and scalar multiplication are defined. For E.g. If two vectors u & v are in space V, then their sum, w = u + v will also lie in the vector space V."
},
{
"code": null,
"e": 5084,
"s": 5006,
"text": "A 2D vector space is a set of linearly independent basis vectors with 2 axes."
},
{
"code": null,
"e": 5138,
"s": 5084,
"text": "Each axis represents a dimension in the vector space."
},
{
"code": null,
"e": 5368,
"s": 5138,
"text": "Recalling the previous plot of vector a = (3,5) = 3 i + 5 j again. This vector is represented on a 2D space with 2 linearly independent basis vectors — X & Y, who also represent the 2 axes as well as the 2 dimenions of the space."
},
{
"code": null,
"e": 5457,
"s": 5368,
"text": "3 & 5 here are the x,y components of this vector for representation on the X-Y 2D space."
},
{
"code": null,
"e": 5523,
"s": 5457,
"text": "A vector space model is a representation of text in vector space."
},
{
"code": null,
"e": 5652,
"s": 5523,
"text": "Here, each word in a corpus is a linearly independent basis vector and each basis vector represents an axis in the vector space."
},
{
"code": null,
"e": 5709,
"s": 5652,
"text": "This means, each word is orthogonal to other words/axes."
},
{
"code": null,
"e": 5766,
"s": 5709,
"text": "For a corpus of vocabulary |V|, R will contain |V| axes."
},
{
"code": null,
"e": 5842,
"s": 5766,
"text": "Combination of terms represent documents as points or vectors in this space"
},
{
"code": null,
"e": 5908,
"s": 5842,
"text": "For 3 words, we’ll have a 3D vector model represented like this -"
},
{
"code": null,
"e": 5973,
"s": 5908,
"text": "The table above the graph represents the TF-IDF incident matrix."
},
{
"code": null,
"e": 6104,
"s": 5973,
"text": "D1 = (0.91, 0, 0.0011) represents a document vector in the 3 axes — good, house, car. Similarly, we have D2 & D3 document vectors."
},
{
"code": null,
"e": 6161,
"s": 6104,
"text": "How does representation in vector space help us, though?"
},
{
"code": null,
"e": 6304,
"s": 6161,
"text": "One of the common application using this representation is information retrieval for search engines, question answering systems and much more."
},
{
"code": null,
"e": 6547,
"s": 6304,
"text": "By representing the text into vectors, we aim to use vector algebra to extract semantics from the text and use it for different applications like searching documents containing the similar sementics as those contained in a given search query."
},
{
"code": null,
"e": 6831,
"s": 6547,
"text": "For eg. For a search token ‘buy’ , we would want to get all the documents containing different forms of this word — buying, bought and even synonyms of the word ‘buy’. Such documents can not be captured from other rudimentary methods representing documents as Binary incident matrix."
},
{
"code": null,
"e": 6997,
"s": 6831,
"text": "This is achieved through distance metrics like cosine similarity between vectors of document & query, where the documents closer to the query are ranked the highest."
},
{
"code": null,
"e": 7325,
"s": 6997,
"text": "The number of words / vocabulary size can be as huge as in millions eg. Google news corpus is 3 Million, which means as many independent axes/dimensions to represent the vectors. Hence, we want to use the operations in vector space to reduce the number of dimensions and bring words with similar to each other in the same axis."
},
{
"code": null,
"e": 7631,
"s": 7325,
"text": "The above operations are possible on document vectors which are represented by extending the above vector representation of documents to documents represented as distributed or dense vectors. These representations capture the semantics of the text and also captures the linear combinations of word vectors"
},
{
"code": null,
"e": 7739,
"s": 7631,
"text": "The previous vector space model with each word representing a separate dimension results in sparse vectors."
},
{
"code": null,
"e": 7915,
"s": 7739,
"text": "Dense vectors captures the context in the vector representation. The dense vector of words are such that words appearing in similar contexts will have similar representations."
},
{
"code": null,
"e": 8002,
"s": 7915,
"text": "These dense vectors are also called as word embeddings or distributed representations."
},
{
"code": null,
"e": 8148,
"s": 8002,
"text": "word2vec is one such framework to learn dense vectors of words from large corpus. It has 2 variants — skip-gram and CBOW(continuous bag of words)"
},
{
"code": null,
"e": 8404,
"s": 8148,
"text": "Some of the other frameworks and techniques to obtain dense vectors are Global Vectors(GloVe), fastText, ELMo(Embeddings from Language Model) and most recent state of the art Bert based approached to obtain contextualized word embeddings during inference."
},
{
"code": null,
"e": 8659,
"s": 8404,
"text": "This article introduced the concept of vector space based on linear algebra and highlighted the related concepts as part of their application in Natural Language Processing for representing text documents in semantics representation and extraction tasks."
},
{
"code": null,
"e": 8798,
"s": 8659,
"text": "The applications of word embeddings have been extended to more advanced and wide applications with much improved performance than earlier."
},
{
"code": null,
"e": 8890,
"s": 8798,
"text": "You can also refer to the source code and run on colab by accessing my Git repository here."
},
{
"code": null,
"e": 8922,
"s": 8890,
"text": "Hope you enjoyed reading it. :)"
},
{
"code": null,
"e": 8966,
"s": 8922,
"text": "Linear Independence, Basis & Dimension, MIT"
},
{
"code": null,
"e": 9004,
"s": 8966,
"text": "Matrices-Introduction to Vectors, MIT"
},
{
"code": null,
"e": 9039,
"s": 9004,
"text": "Vector space models for NLP, NPTEL"
}
] |
Create a Stack and Queue using ArrayDeque in Java
|
Create a stack using ArrayDeque.
Deque<String> s = new ArrayDeque<String>();
// stack
s.push("Bat");
s.push("Mat");
s.push("Cat");
s.push("Rat");
s.push("Hat");
s.push("Fat");
Create a queue using ArrayDeque −
Deque<String> q = new ArrayDeque<String>();
// queue
q.add("Bat");
q.add("Mat");
q.add("Cat");
q.add("Rat");
q.add("Hat");
q.add("Fat");
The following is an example.
Live Demo
import java.util.ArrayDeque;
import java.util.Deque;
public class Demo {
public static void main(String args[]) {
Deque<String> s = new ArrayDeque<String>();
Deque<String> q = new ArrayDeque<String>();
// stack
s.push("Bat");
s.push("Mat");
s.push("Cat");
s.push("Rat");
s.push("Hat");
s.push("Fat");
while (!s.isEmpty())
System.out.print(s.pop() + " ");
System.out.print("\n");
// queue
q.add("Bat");
q.add("Mat");
q.add("Cat");
q.add("Rat");
q.add("Hat");
q.add("Fat");
while (!q.isEmpty())
System.out.print(q.remove() + " ");
}
}
Fat Hat Rat Cat Mat Bat
Bat Mat Cat Rat Hat Fat
|
[
{
"code": null,
"e": 1095,
"s": 1062,
"text": "Create a stack using ArrayDeque."
},
{
"code": null,
"e": 1238,
"s": 1095,
"text": "Deque<String> s = new ArrayDeque<String>();\n// stack\ns.push(\"Bat\");\ns.push(\"Mat\");\ns.push(\"Cat\");\ns.push(\"Rat\");\ns.push(\"Hat\");\ns.push(\"Fat\");"
},
{
"code": null,
"e": 1272,
"s": 1238,
"text": "Create a queue using ArrayDeque −"
},
{
"code": null,
"e": 1409,
"s": 1272,
"text": "Deque<String> q = new ArrayDeque<String>();\n// queue\nq.add(\"Bat\");\nq.add(\"Mat\");\nq.add(\"Cat\");\nq.add(\"Rat\");\nq.add(\"Hat\");\nq.add(\"Fat\");"
},
{
"code": null,
"e": 1438,
"s": 1409,
"text": "The following is an example."
},
{
"code": null,
"e": 1449,
"s": 1438,
"text": " Live Demo"
},
{
"code": null,
"e": 2120,
"s": 1449,
"text": "import java.util.ArrayDeque;\nimport java.util.Deque;\npublic class Demo {\n public static void main(String args[]) {\n Deque<String> s = new ArrayDeque<String>();\n Deque<String> q = new ArrayDeque<String>();\n // stack\n s.push(\"Bat\");\n s.push(\"Mat\");\n s.push(\"Cat\");\n s.push(\"Rat\");\n s.push(\"Hat\");\n s.push(\"Fat\");\n while (!s.isEmpty())\n System.out.print(s.pop() + \" \");\n System.out.print(\"\\n\");\n // queue\n q.add(\"Bat\");\n q.add(\"Mat\");\n q.add(\"Cat\");\n q.add(\"Rat\");\n q.add(\"Hat\");\n q.add(\"Fat\");\n while (!q.isEmpty())\n System.out.print(q.remove() + \" \");\n }\n}"
},
{
"code": null,
"e": 2168,
"s": 2120,
"text": "Fat Hat Rat Cat Mat Bat\nBat Mat Cat Rat Hat Fat"
}
] |
How to convert a binary matrix to logical matrix in R?
|
A binary matrix contains values such as Yes or NO, 1 or 0, or any other two values that represents opposite mostly and the globally accepted logical values are FALSE and TRUE. Therefore, to convert a binary matrix to logical matrix, we can use ifelse function and convert the one category of binary variable to appropriate logical value and for the rest returns the left-out value. This is a very easy task in R, check out the below examples to understand how it can be done.
Live Demo
> M1<-matrix(sample(c("No","Yes"),40,replace=TRUE),nrow=20)
> M1
[,1] [,2]
[1,] "No" "Yes"
[2,] "No" "No"
[3,] "No" "Yes"
[4,] "Yes" "Yes"
[5,] "Yes" "Yes"
[6,] "No" "No"
[7,] "Yes" "No"
[8,] "Yes" "Yes"
[9,] "No" "No"
[10,] "No" "Yes"
[11,] "No" "No"
[12,] "Yes" "Yes"
[13,] "No" "No"
[14,] "Yes" "Yes"
[15,] "No" "Yes"
[16,] "No" "No"
[17,] "Yes" "No"
[18,] "Yes" "No"
[19,] "Yes" "No"
[20,] "Yes" "Yes"
Converting M1 to a logical matrix −
> M1[,]<-ifelse(M1 %in% c("No"),FALSE,TRUE)
> M1
[,1] [,2]
[1,] "FALSE" "TRUE"
[2,] "FALSE" "FALSE"
[3,] "FALSE" "TRUE"
[4,] "TRUE" "TRUE"
[5,] "TRUE" "TRUE"
[6,] "FALSE" "FALSE"
[7,] "TRUE" "FALSE"
[8,] "TRUE" "TRUE"
[9,] "FALSE" "FALSE"
[10,] "FALSE" "TRUE"
[11,] "FALSE" "FALSE"
[12,] "TRUE" "TRUE"
[13,] "FALSE" "FALSE"
[14,] "TRUE" "TRUE"
[15,] "FALSE" "TRUE"
[16,] "FALSE" "FALSE"
[17,] "TRUE" "FALSE"
[18,] "TRUE" "FALSE"
[19,] "TRUE" "FALSE"
[20,] "TRUE" "TRUE"
Live Demo
> M2<-matrix(sample(c("0","1"),40,replace=TRUE),nrow=20)
> M2
[,1] [,2]
[1,] "1" "1"
[2,] "0" "1"
[3,] "1" "0"
[4,] "0" "0"
[5,] "1" "0"
[6,] "1" "1"
[7,] "1" "0"
[8,] "0" "1"
[9,] "0" "0"
[10,] "0" "0"
[11,] "0" "1"
[12,] "0" "0"
[13,] "0" "1"
[14,] "0" "0"
[15,] "1" "1"
[16,] "0" "1"
[17,] "0" "1"
[18,] "1" "0"
[19,] "1" "0"
[20,] "1" "0"
Converting M2 to a logical matrix −
> M2[,]<-ifelse(M2 %in% c("0"),FALSE,TRUE)
> M2
[,1] [,2]
[1,] "TRUE" "TRUE"
[2,] "FALSE" "TRUE"
[3,] "TRUE" "FALSE"
[4,] "FALSE" "FALSE"
[5,] "TRUE" "FALSE"
[6,] "TRUE" "TRUE"
[7,] "TRUE" "FALSE"
[8,] "FALSE" "TRUE"
[9,] "FALSE" "FALSE"
[10,] "FALSE" "FALSE"
[11,] "FALSE" "TRUE"
[12,] "FALSE" "FALSE"
[13,] "FALSE" "TRUE"
[14,] "FALSE" "FALSE"
[15,] "TRUE" "TRUE"
[16,] "FALSE" "TRUE"
[17,] "FALSE" "TRUE"
[18,] "TRUE" "FALSE"
[19,] "TRUE" "FALSE"
[20,] "TRUE" "FALSE"
|
[
{
"code": null,
"e": 1538,
"s": 1062,
"text": "A binary matrix contains values such as Yes or NO, 1 or 0, or any other two values that represents opposite mostly and the globally accepted logical values are FALSE and TRUE. Therefore, to convert a binary matrix to logical matrix, we can use ifelse function and convert the one category of binary variable to appropriate logical value and for the rest returns the left-out value. This is a very easy task in R, check out the below examples to understand how it can be done."
},
{
"code": null,
"e": 1548,
"s": 1538,
"text": "Live Demo"
},
{
"code": null,
"e": 1613,
"s": 1548,
"text": "> M1<-matrix(sample(c(\"No\",\"Yes\"),40,replace=TRUE),nrow=20)\n> M1"
},
{
"code": null,
"e": 1954,
"s": 1613,
"text": "[,1] [,2]\n[1,] \"No\" \"Yes\"\n[2,] \"No\" \"No\"\n[3,] \"No\" \"Yes\"\n[4,] \"Yes\" \"Yes\"\n[5,] \"Yes\" \"Yes\"\n[6,] \"No\" \"No\"\n[7,] \"Yes\" \"No\"\n[8,] \"Yes\" \"Yes\"\n[9,] \"No\" \"No\"\n[10,] \"No\" \"Yes\"\n[11,] \"No\" \"No\"\n[12,] \"Yes\" \"Yes\"\n[13,] \"No\" \"No\"\n[14,] \"Yes\" \"Yes\"\n[15,] \"No\" \"Yes\"\n[16,] \"No\" \"No\"\n[17,] \"Yes\" \"No\"\n[18,] \"Yes\" \"No\"\n[19,] \"Yes\" \"No\"\n[20,] \"Yes\" \"Yes\""
},
{
"code": null,
"e": 1990,
"s": 1954,
"text": "Converting M1 to a logical matrix −"
},
{
"code": null,
"e": 2039,
"s": 1990,
"text": "> M1[,]<-ifelse(M1 %in% c(\"No\"),FALSE,TRUE)\n> M1"
},
{
"code": null,
"e": 2460,
"s": 2039,
"text": "[,1] [,2]\n[1,] \"FALSE\" \"TRUE\"\n[2,] \"FALSE\" \"FALSE\"\n[3,] \"FALSE\" \"TRUE\"\n[4,] \"TRUE\" \"TRUE\"\n[5,] \"TRUE\" \"TRUE\"\n[6,] \"FALSE\" \"FALSE\"\n[7,] \"TRUE\" \"FALSE\"\n[8,] \"TRUE\" \"TRUE\"\n[9,] \"FALSE\" \"FALSE\"\n[10,] \"FALSE\" \"TRUE\"\n[11,] \"FALSE\" \"FALSE\"\n[12,] \"TRUE\" \"TRUE\"\n[13,] \"FALSE\" \"FALSE\"\n[14,] \"TRUE\" \"TRUE\"\n[15,] \"FALSE\" \"TRUE\"\n[16,] \"FALSE\" \"FALSE\"\n[17,] \"TRUE\" \"FALSE\"\n[18,] \"TRUE\" \"FALSE\"\n[19,] \"TRUE\" \"FALSE\"\n[20,] \"TRUE\" \"TRUE\""
},
{
"code": null,
"e": 2470,
"s": 2460,
"text": "Live Demo"
},
{
"code": null,
"e": 2532,
"s": 2470,
"text": "> M2<-matrix(sample(c(\"0\",\"1\"),40,replace=TRUE),nrow=20)\n> M2"
},
{
"code": null,
"e": 2813,
"s": 2532,
"text": "[,1] [,2]\n[1,] \"1\" \"1\"\n[2,] \"0\" \"1\"\n[3,] \"1\" \"0\"\n[4,] \"0\" \"0\"\n[5,] \"1\" \"0\"\n[6,] \"1\" \"1\"\n[7,] \"1\" \"0\"\n[8,] \"0\" \"1\"\n[9,] \"0\" \"0\"\n[10,] \"0\" \"0\"\n[11,] \"0\" \"1\"\n[12,] \"0\" \"0\"\n[13,] \"0\" \"1\"\n[14,] \"0\" \"0\"\n[15,] \"1\" \"1\"\n[16,] \"0\" \"1\"\n[17,] \"0\" \"1\"\n[18,] \"1\" \"0\"\n[19,] \"1\" \"0\"\n[20,] \"1\" \"0\""
},
{
"code": null,
"e": 2849,
"s": 2813,
"text": "Converting M2 to a logical matrix −"
},
{
"code": null,
"e": 2897,
"s": 2849,
"text": "> M2[,]<-ifelse(M2 %in% c(\"0\"),FALSE,TRUE)\n> M2"
},
{
"code": null,
"e": 3320,
"s": 2897,
"text": "[,1] [,2]\n[1,] \"TRUE\" \"TRUE\"\n[2,] \"FALSE\" \"TRUE\"\n[3,] \"TRUE\" \"FALSE\"\n[4,] \"FALSE\" \"FALSE\"\n[5,] \"TRUE\" \"FALSE\"\n[6,] \"TRUE\" \"TRUE\"\n[7,] \"TRUE\" \"FALSE\"\n[8,] \"FALSE\" \"TRUE\"\n[9,] \"FALSE\" \"FALSE\"\n[10,] \"FALSE\" \"FALSE\"\n[11,] \"FALSE\" \"TRUE\"\n[12,] \"FALSE\" \"FALSE\"\n[13,] \"FALSE\" \"TRUE\"\n[14,] \"FALSE\" \"FALSE\"\n[15,] \"TRUE\" \"TRUE\"\n[16,] \"FALSE\" \"TRUE\"\n[17,] \"FALSE\" \"TRUE\"\n[18,] \"TRUE\" \"FALSE\"\n[19,] \"TRUE\" \"FALSE\"\n[20,] \"TRUE\" \"FALSE\""
}
] |
Maximum XOR value in matrix - GeeksforGeeks
|
30 Apr, 2021
Given a square matrix (N X N), the task is to find the maximum XOR value of a complete row or a complete column.Examples :
Input : N = 3
mat[3][3] = {{1, 0, 4},
{3, 7, 2},
{5, 9, 10} };
Output : 14
We get this maximum XOR value by doing XOR
of elements in second column 0 ^ 7 ^ 9 = 14
Input : N = 4
mat[4][4] = { {1, 2, 3, 6},
{4, 5, 6,7},
{7, 8, 9, 10},
{2, 4, 5, 11}}
Output : 12
A simple solution of this problem is we can traverse the matrix twice and calculate maximum xor value row-wise & column wise ,and at last return the maximum between (xor_row , xor_column).A efficient solution is we can traverse matrix only one time and calculate max XOR value .
Start traverse the matrix and calculate XOR at each index row and column wise. We can compute both values by using indexes in reverse way. This is possible because matrix is a square matrix.Store the maximum of both.
Start traverse the matrix and calculate XOR at each index row and column wise. We can compute both values by using indexes in reverse way. This is possible because matrix is a square matrix.
Store the maximum of both.
Below is the implementation :
C++
Java
Python3
C#
PHP
Javascript
// C++ program to Find maximum XOR value in// matrix either row / column wise#include<iostream>using namespace std; // maximum number of row and columnconst int MAX = 1000; // function return the maximum xor value that is// either row or column wiseint maxXOR(int mat[][MAX], int N){ // for row xor and column xor int r_xor, c_xor; int max_xor = 0; // traverse matrix for (int i = 0 ; i < N ; i++) { r_xor = 0, c_xor = 0; for (int j = 0 ; j < N ; j++) { // xor row element r_xor = r_xor^mat[i][j]; // for each column : j is act as row & i // act as column xor column element c_xor = c_xor^mat[j][i]; } // update maximum between r_xor , c_xor if (max_xor < max(r_xor, c_xor)) max_xor = max(r_xor, c_xor); } // return maximum xor value return max_xor;} // driver Codeint main(){ int N = 3; int mat[][MAX] = {{1 , 5, 4}, {3 , 7, 2 }, {5 , 9, 10} }; cout << "maximum XOR value : " << maxXOR(mat, N); return 0;}
// Java program to Find maximum XOR value in// matrix either row / column wiseclass GFG { // maximum number of row and column static final int MAX = 1000; // function return the maximum xor value // that is either row or column wise static int maxXOR(int mat[][], int N) { // for row xor and column xor int r_xor, c_xor; int max_xor = 0; // traverse matrix for (int i = 0 ; i < N ; i++) { r_xor = 0; c_xor = 0; for (int j = 0 ; j < N ; j++) { // xor row element r_xor = r_xor^mat[i][j]; // for each column : j is act as row & i // act as column xor column element c_xor = c_xor^mat[j][i]; } // update maximum between r_xor , c_xor if (max_xor < Math.max(r_xor, c_xor)) max_xor = Math.max(r_xor, c_xor); } // return maximum xor value return max_xor; } //driver code public static void main (String[] args) { int N = 3; int mat[][] = { {1, 5, 4}, {3, 7, 2}, {5, 9, 10}}; System.out.print("maximum XOR value : " + maxXOR(mat, N)); }} // This code is contributed by Anant Agarwal.
# Python3 program to Find maximum# XOR value in matrix either row / column wise # maximum number of row and columnMAX = 1000 # Function return the maximum# xor value that is either row# or column wisedef maxXOR(mat, N): # For row xor and column xor max_xor = 0 # Traverse matrix for i in range(N): r_xor = 0 c_xor = 0 for j in range(N): # xor row element r_xor = r_xor ^ mat[i][j] # for each column : j is act as row & i # act as column xor column element c_xor = c_xor ^ mat[j][i] # update maximum between r_xor , c_xor if (max_xor < max(r_xor, c_xor)): max_xor = max(r_xor, c_xor) # return maximum xor value return max_xor # Driver CodeN = 3 mat= [[1 , 5, 4], [3 , 7, 2 ], [5 , 9, 10]] print("maximum XOR value : ", maxXOR(mat, N)) # This code is contributed by Anant Agarwal.
// C# program to Find maximum XOR value in// matrix either row / column wiseusing System; class GFG{ // maximum number of row and column // function return the maximum xor value // that is either row or column wise static int maxXOR(int [,]mat, int N) { // for row xor and column xor int r_xor, c_xor; int max_xor = 0; // traverse matrix for (int i = 0 ; i < N ; i++) { r_xor = 0; c_xor = 0; for (int j = 0 ; j < N ; j++) { // xor row element r_xor = r_xor^mat[i, j]; // for each column : j is act as row & i // act as column xor column element c_xor = c_xor^mat[j, i]; } // update maximum between r_xor , c_xor if (max_xor < Math.Max(r_xor, c_xor)) max_xor = Math.Max(r_xor, c_xor); } // return maximum xor value return max_xor; } // Driver code public static void Main () { int N = 3; int [,]mat = { {1, 5, 4}, {3, 7, 2}, {5, 9, 10}}; Console.Write("maximum XOR value : " + maxXOR(mat, N)); }} // This code is contributed by nitin mittal.
<?php// PHP program to Find// maximum XOR value in// matrix either row or// column wise // maximum number of// row and column$MAX = 1000; // function return the maximum// xor value that is either// row or column wisefunction maxXOR($mat, $N){ // for row xor and // column xor $r_xor; $c_xor; $max_xor = 0; // traverse matrix for ($i = 0 ; $i < $N ; $i++) { $r_xor = 0; $c_xor = 0; for ($j = 0 ; $j < $N ; $j++) { // xor row element $r_xor = $r_xor^$mat[$i][$j]; // for each column : j // is act as row & i // act as column xor // column element $c_xor = $c_xor^$mat[$j][$i]; } // update maximum between // r_xor , c_xor if ($max_xor < max($r_xor, $c_xor)) $max_xor = max($r_xor, $c_xor); } // return maximum // xor value return $max_xor;} // Driver Code $N = 3; $mat = array(array(1, 5, 4), array(3, 7, 2), array(5, 9, 10)); echo "maximum XOR value : " , maxXOR($mat, $N); // This code is contributed by anuj_67.?>
<script> // Javascript program to Find// maximum XOR value in// matrix either row / column wise // maximum number of row and columnconst MAX = 1000; // function return the maximum// xor value that is// either row or column wisefunction maxXOR(mat, N){ // for row xor and column xor let r_xor, c_xor; let max_xor = 0; // traverse matrix for (let i = 0 ; i < N ; i++) { r_xor = 0, c_xor = 0; for (let j = 0 ; j < N ; j++) { // xor row element r_xor = r_xor^mat[i][j]; // for each column : j // is act as row & i // act as column xor // column element c_xor = c_xor^mat[j][i]; } // update maximum between r_xor , c_xor if (max_xor < Math.max(r_xor, c_xor)) max_xor = Math.max(r_xor, c_xor); } // return maximum xor value return max_xor;} // driver Code let N = 3; let mat = [[1 , 5, 4], [3 , 7, 2 ], [5 , 9, 10]]; document.write("maximum XOR value : " + maxXOR(mat, N)); </script>
Output :
maximum XOR value : 12
Time complexity : O(N*N) space complexity : O(1)This article is contributed by Nishant_Singh(Pintu). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
vt_m
souravmahato348
Bitwise-XOR
Matrix
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Sudoku | Backtracking-7
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
Program to multiply two matrices
Count all possible paths from top left to bottom right of a mXn matrix
Min Cost Path | DP-6
Printing all solutions in N-Queen Problem
The Celebrity Problem
Python program to multiply two matrices
Gold Mine Problem
Multiplication of two Matrices in Single line using Numpy in Python
|
[
{
"code": null,
"e": 24615,
"s": 24587,
"text": "\n30 Apr, 2021"
},
{
"code": null,
"e": 24740,
"s": 24615,
"text": "Given a square matrix (N X N), the task is to find the maximum XOR value of a complete row or a complete column.Examples : "
},
{
"code": null,
"e": 25127,
"s": 24740,
"text": "Input : N = 3 \n mat[3][3] = {{1, 0, 4},\n {3, 7, 2},\n {5, 9, 10} };\nOutput : 14\nWe get this maximum XOR value by doing XOR \nof elements in second column 0 ^ 7 ^ 9 = 14\n\nInput : N = 4 \n mat[4][4] = { {1, 2, 3, 6},\n {4, 5, 6,7},\n {7, 8, 9, 10},\n {2, 4, 5, 11}}\nOutput : 12 "
},
{
"code": null,
"e": 25410,
"s": 25129,
"text": "A simple solution of this problem is we can traverse the matrix twice and calculate maximum xor value row-wise & column wise ,and at last return the maximum between (xor_row , xor_column).A efficient solution is we can traverse matrix only one time and calculate max XOR value . "
},
{
"code": null,
"e": 25627,
"s": 25410,
"text": "Start traverse the matrix and calculate XOR at each index row and column wise. We can compute both values by using indexes in reverse way. This is possible because matrix is a square matrix.Store the maximum of both."
},
{
"code": null,
"e": 25818,
"s": 25627,
"text": "Start traverse the matrix and calculate XOR at each index row and column wise. We can compute both values by using indexes in reverse way. This is possible because matrix is a square matrix."
},
{
"code": null,
"e": 25845,
"s": 25818,
"text": "Store the maximum of both."
},
{
"code": null,
"e": 25877,
"s": 25845,
"text": "Below is the implementation : "
},
{
"code": null,
"e": 25881,
"s": 25877,
"text": "C++"
},
{
"code": null,
"e": 25886,
"s": 25881,
"text": "Java"
},
{
"code": null,
"e": 25894,
"s": 25886,
"text": "Python3"
},
{
"code": null,
"e": 25897,
"s": 25894,
"text": "C#"
},
{
"code": null,
"e": 25901,
"s": 25897,
"text": "PHP"
},
{
"code": null,
"e": 25912,
"s": 25901,
"text": "Javascript"
},
{
"code": "// C++ program to Find maximum XOR value in// matrix either row / column wise#include<iostream>using namespace std; // maximum number of row and columnconst int MAX = 1000; // function return the maximum xor value that is// either row or column wiseint maxXOR(int mat[][MAX], int N){ // for row xor and column xor int r_xor, c_xor; int max_xor = 0; // traverse matrix for (int i = 0 ; i < N ; i++) { r_xor = 0, c_xor = 0; for (int j = 0 ; j < N ; j++) { // xor row element r_xor = r_xor^mat[i][j]; // for each column : j is act as row & i // act as column xor column element c_xor = c_xor^mat[j][i]; } // update maximum between r_xor , c_xor if (max_xor < max(r_xor, c_xor)) max_xor = max(r_xor, c_xor); } // return maximum xor value return max_xor;} // driver Codeint main(){ int N = 3; int mat[][MAX] = {{1 , 5, 4}, {3 , 7, 2 }, {5 , 9, 10} }; cout << \"maximum XOR value : \" << maxXOR(mat, N); return 0;}",
"e": 27025,
"s": 25912,
"text": null
},
{
"code": "// Java program to Find maximum XOR value in// matrix either row / column wiseclass GFG { // maximum number of row and column static final int MAX = 1000; // function return the maximum xor value // that is either row or column wise static int maxXOR(int mat[][], int N) { // for row xor and column xor int r_xor, c_xor; int max_xor = 0; // traverse matrix for (int i = 0 ; i < N ; i++) { r_xor = 0; c_xor = 0; for (int j = 0 ; j < N ; j++) { // xor row element r_xor = r_xor^mat[i][j]; // for each column : j is act as row & i // act as column xor column element c_xor = c_xor^mat[j][i]; } // update maximum between r_xor , c_xor if (max_xor < Math.max(r_xor, c_xor)) max_xor = Math.max(r_xor, c_xor); } // return maximum xor value return max_xor; } //driver code public static void main (String[] args) { int N = 3; int mat[][] = { {1, 5, 4}, {3, 7, 2}, {5, 9, 10}}; System.out.print(\"maximum XOR value : \" + maxXOR(mat, N)); }} // This code is contributed by Anant Agarwal.",
"e": 28425,
"s": 27025,
"text": null
},
{
"code": "# Python3 program to Find maximum# XOR value in matrix either row / column wise # maximum number of row and columnMAX = 1000 # Function return the maximum# xor value that is either row# or column wisedef maxXOR(mat, N): # For row xor and column xor max_xor = 0 # Traverse matrix for i in range(N): r_xor = 0 c_xor = 0 for j in range(N): # xor row element r_xor = r_xor ^ mat[i][j] # for each column : j is act as row & i # act as column xor column element c_xor = c_xor ^ mat[j][i] # update maximum between r_xor , c_xor if (max_xor < max(r_xor, c_xor)): max_xor = max(r_xor, c_xor) # return maximum xor value return max_xor # Driver CodeN = 3 mat= [[1 , 5, 4], [3 , 7, 2 ], [5 , 9, 10]] print(\"maximum XOR value : \", maxXOR(mat, N)) # This code is contributed by Anant Agarwal.",
"e": 29397,
"s": 28425,
"text": null
},
{
"code": "// C# program to Find maximum XOR value in// matrix either row / column wiseusing System; class GFG{ // maximum number of row and column // function return the maximum xor value // that is either row or column wise static int maxXOR(int [,]mat, int N) { // for row xor and column xor int r_xor, c_xor; int max_xor = 0; // traverse matrix for (int i = 0 ; i < N ; i++) { r_xor = 0; c_xor = 0; for (int j = 0 ; j < N ; j++) { // xor row element r_xor = r_xor^mat[i, j]; // for each column : j is act as row & i // act as column xor column element c_xor = c_xor^mat[j, i]; } // update maximum between r_xor , c_xor if (max_xor < Math.Max(r_xor, c_xor)) max_xor = Math.Max(r_xor, c_xor); } // return maximum xor value return max_xor; } // Driver code public static void Main () { int N = 3; int [,]mat = { {1, 5, 4}, {3, 7, 2}, {5, 9, 10}}; Console.Write(\"maximum XOR value : \" + maxXOR(mat, N)); }} // This code is contributed by nitin mittal.",
"e": 30759,
"s": 29397,
"text": null
},
{
"code": "<?php// PHP program to Find// maximum XOR value in// matrix either row or// column wise // maximum number of// row and column$MAX = 1000; // function return the maximum// xor value that is either// row or column wisefunction maxXOR($mat, $N){ // for row xor and // column xor $r_xor; $c_xor; $max_xor = 0; // traverse matrix for ($i = 0 ; $i < $N ; $i++) { $r_xor = 0; $c_xor = 0; for ($j = 0 ; $j < $N ; $j++) { // xor row element $r_xor = $r_xor^$mat[$i][$j]; // for each column : j // is act as row & i // act as column xor // column element $c_xor = $c_xor^$mat[$j][$i]; } // update maximum between // r_xor , c_xor if ($max_xor < max($r_xor, $c_xor)) $max_xor = max($r_xor, $c_xor); } // return maximum // xor value return $max_xor;} // Driver Code $N = 3; $mat = array(array(1, 5, 4), array(3, 7, 2), array(5, 9, 10)); echo \"maximum XOR value : \" , maxXOR($mat, $N); // This code is contributed by anuj_67.?>",
"e": 31919,
"s": 30759,
"text": null
},
{
"code": "<script> // Javascript program to Find// maximum XOR value in// matrix either row / column wise // maximum number of row and columnconst MAX = 1000; // function return the maximum// xor value that is// either row or column wisefunction maxXOR(mat, N){ // for row xor and column xor let r_xor, c_xor; let max_xor = 0; // traverse matrix for (let i = 0 ; i < N ; i++) { r_xor = 0, c_xor = 0; for (let j = 0 ; j < N ; j++) { // xor row element r_xor = r_xor^mat[i][j]; // for each column : j // is act as row & i // act as column xor // column element c_xor = c_xor^mat[j][i]; } // update maximum between r_xor , c_xor if (max_xor < Math.max(r_xor, c_xor)) max_xor = Math.max(r_xor, c_xor); } // return maximum xor value return max_xor;} // driver Code let N = 3; let mat = [[1 , 5, 4], [3 , 7, 2 ], [5 , 9, 10]]; document.write(\"maximum XOR value : \" + maxXOR(mat, N)); </script>",
"e": 33019,
"s": 31919,
"text": null
},
{
"code": null,
"e": 33030,
"s": 33019,
"text": "Output : "
},
{
"code": null,
"e": 33054,
"s": 33030,
"text": "maximum XOR value : 12"
},
{
"code": null,
"e": 33530,
"s": 33054,
"text": "Time complexity : O(N*N) space complexity : O(1)This article is contributed by Nishant_Singh(Pintu). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 33543,
"s": 33530,
"text": "nitin mittal"
},
{
"code": null,
"e": 33548,
"s": 33543,
"text": "vt_m"
},
{
"code": null,
"e": 33564,
"s": 33548,
"text": "souravmahato348"
},
{
"code": null,
"e": 33576,
"s": 33564,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 33583,
"s": 33576,
"text": "Matrix"
},
{
"code": null,
"e": 33590,
"s": 33583,
"text": "Matrix"
},
{
"code": null,
"e": 33688,
"s": 33590,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33697,
"s": 33688,
"text": "Comments"
},
{
"code": null,
"e": 33710,
"s": 33697,
"text": "Old Comments"
},
{
"code": null,
"e": 33734,
"s": 33710,
"text": "Sudoku | Backtracking-7"
},
{
"code": null,
"e": 33796,
"s": 33734,
"text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)"
},
{
"code": null,
"e": 33829,
"s": 33796,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 33900,
"s": 33829,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 33921,
"s": 33900,
"text": "Min Cost Path | DP-6"
},
{
"code": null,
"e": 33963,
"s": 33921,
"text": "Printing all solutions in N-Queen Problem"
},
{
"code": null,
"e": 33985,
"s": 33963,
"text": "The Celebrity Problem"
},
{
"code": null,
"e": 34025,
"s": 33985,
"text": "Python program to multiply two matrices"
},
{
"code": null,
"e": 34043,
"s": 34025,
"text": "Gold Mine Problem"
}
] |
MongoDB query to display all the values excluding the id?
|
For this, use the project.Theproject takes a document that can specify the inclusion of fields, the suppression of the _id field, the addition of new fields, and the resetting of the values of existing fields
Let us first create a collection with documents −
> db.demo226.insertOne({"Name":"Chris","Age":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3f9be803d395bdc2134738")
}
> db.demo226.insertOne({"Name":"Bob","Age":20});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3f9bf003d395bdc2134739")
}
> db.demo226.insertOne({"Name":"David","Age":22});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3f9bf803d395bdc213473a")
}
Display all documents from a collection with the help of find() method −
> db.demo226.find();
This will produce the following output −
{ "_id" : ObjectId("5e3f9be803d395bdc2134738"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5e3f9bf003d395bdc2134739"), "Name" : "Bob", "Age" : 20 }
{ "_id" : ObjectId("5e3f9bf803d395bdc213473a"), "Name" : "David", "Age" : 22 }
Following is the query to display all the values excluding id −
> db.demo226.aggregate(
... {$project:
... {
... _id: false,
..." StudentFirstName":"$Name",
... "StudentAge":"$Age"
... }
... }
...);
This will produce the following output −
{ "StudentFirstName" : "Chris", "StudentAge" : 21 }
{ "StudentFirstName" : "Bob", "StudentAge" : 20 }
{ "StudentFirstName" : "David", "StudentAge" : 22 }
|
[
{
"code": null,
"e": 1271,
"s": 1062,
"text": "For this, use the project.Theproject takes a document that can specify the inclusion of fields, the suppression of the _id field, the addition of new fields, and the resetting of the values of existing fields"
},
{
"code": null,
"e": 1321,
"s": 1271,
"text": "Let us first create a collection with documents −"
},
{
"code": null,
"e": 1727,
"s": 1321,
"text": "> db.demo226.insertOne({\"Name\":\"Chris\",\"Age\":21});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e3f9be803d395bdc2134738\")\n}\n> db.demo226.insertOne({\"Name\":\"Bob\",\"Age\":20});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e3f9bf003d395bdc2134739\")\n}\n> db.demo226.insertOne({\"Name\":\"David\",\"Age\":22});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e3f9bf803d395bdc213473a\")\n}"
},
{
"code": null,
"e": 1800,
"s": 1727,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1821,
"s": 1800,
"text": "> db.demo226.find();"
},
{
"code": null,
"e": 1862,
"s": 1821,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2097,
"s": 1862,
"text": "{ \"_id\" : ObjectId(\"5e3f9be803d395bdc2134738\"), \"Name\" : \"Chris\", \"Age\" : 21 }\n{ \"_id\" : ObjectId(\"5e3f9bf003d395bdc2134739\"), \"Name\" : \"Bob\", \"Age\" : 20 }\n{ \"_id\" : ObjectId(\"5e3f9bf803d395bdc213473a\"), \"Name\" : \"David\", \"Age\" : 22 }"
},
{
"code": null,
"e": 2161,
"s": 2097,
"text": "Following is the query to display all the values excluding id −"
},
{
"code": null,
"e": 2334,
"s": 2161,
"text": "> db.demo226.aggregate(\n... {$project:\n... {\n... _id: false,\n...\" StudentFirstName\":\"$Name\",\n... \"StudentAge\":\"$Age\"\n... }\n... }\n...);"
},
{
"code": null,
"e": 2375,
"s": 2334,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2529,
"s": 2375,
"text": "{ \"StudentFirstName\" : \"Chris\", \"StudentAge\" : 21 }\n{ \"StudentFirstName\" : \"Bob\", \"StudentAge\" : 20 }\n{ \"StudentFirstName\" : \"David\", \"StudentAge\" : 22 }"
}
] |
JavaScript - RegExp test Method
|
The test method searches string for text that matches regexp. If it finds a match, it returns true; otherwise, it returns false.
Its syntax is as follows −
RegExpObject.test( string );
string − The string to be searched
Returns the matched text if a match is found, and null if not.
Try the following example program.
<html>
<head>
<title>JavaScript RegExp test Method</title>
</head>
<body>
<script type = "text/javascript">
var str = "Javascript is an interesting scripting language";
var re = new RegExp( "script", "g" );
var result = re.test(str);
document.write("Test 1 - returned value : " + result);
re = new RegExp( "pushing", "g" );
var result = re.test(str);
document.write("<br />Test 2 - returned value : " + result);
</script>
</body>
</html>
Test 1 - returned value : true
Test 2 - returned value : false
25 Lectures
2.5 hours
Anadi Sharma
74 Lectures
10 hours
Lets Kode It
72 Lectures
4.5 hours
Frahaan Hussain
70 Lectures
4.5 hours
Frahaan Hussain
46 Lectures
6 hours
Eduonix Learning Solutions
88 Lectures
14 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2595,
"s": 2466,
"text": "The test method searches string for text that matches regexp. If it finds a match, it returns true; otherwise, it returns false."
},
{
"code": null,
"e": 2622,
"s": 2595,
"text": "Its syntax is as follows −"
},
{
"code": null,
"e": 2652,
"s": 2622,
"text": "RegExpObject.test( string );\n"
},
{
"code": null,
"e": 2688,
"s": 2652,
"text": "string − The string to be searched"
},
{
"code": null,
"e": 2751,
"s": 2688,
"text": "Returns the matched text if a match is found, and null if not."
},
{
"code": null,
"e": 2786,
"s": 2751,
"text": "Try the following example program."
},
{
"code": null,
"e": 3355,
"s": 2786,
"text": "<html>\n <head>\n <title>JavaScript RegExp test Method</title>\n </head>\n \n <body>\n <script type = \"text/javascript\">\n var str = \"Javascript is an interesting scripting language\";\n var re = new RegExp( \"script\", \"g\" );\n \n var result = re.test(str);\n document.write(\"Test 1 - returned value : \" + result); \n \n re = new RegExp( \"pushing\", \"g\" );\n \n var result = re.test(str);\n document.write(\"<br />Test 2 - returned value : \" + result); \n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 3420,
"s": 3355,
"text": "Test 1 - returned value : true\nTest 2 - returned value : false \n"
},
{
"code": null,
"e": 3455,
"s": 3420,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3469,
"s": 3455,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3503,
"s": 3469,
"text": "\n 74 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3517,
"s": 3503,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3552,
"s": 3517,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3569,
"s": 3552,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3604,
"s": 3569,
"text": "\n 70 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3621,
"s": 3604,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3654,
"s": 3621,
"text": "\n 46 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3682,
"s": 3654,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3716,
"s": 3682,
"text": "\n 88 Lectures \n 14 hours \n"
},
{
"code": null,
"e": 3744,
"s": 3716,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3751,
"s": 3744,
"text": " Print"
},
{
"code": null,
"e": 3762,
"s": 3751,
"text": " Add Notes"
}
] |
How to Create a Representative Test Set | by Dimitris Poulopoulos | Towards Data Science
|
Splitting a data set into train and test sets is usually one of the first processing steps in a machine learning pipeline. After this point, there is just one inviolable rule: set aside the test data split and refer to it again only when your model is ready for its final evaluation. But is there a way to be confident that the split we made is the right one? How can we be sure that the test set is representative of our population?
We must be sure that the test set resembles closely the intricacies of our population. The same goes for our validation sets as well.
In this story, we discuss two methods of splitting: random and stratified sampling. We consider their advantages and debate over which one to use under specific circumstances. This story is actually my published notes on the excellent Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems by Aurélien Géron.
Learning Rate is my weekly newsletter for those who are curious about the world of AI and MLOps. You’ll hear from me every Friday with updates and thoughts on the latest AI news, research, repos and books. Subscribe here!
For this example, we use the California Housing Prices data set. This data set is excellent for introductory tutorials due to its familiar nature, few missing values, modest size and clear goal.
This dataset is based on data from the 1990 California census. The task is to predict the median value of the houses in a specific district, given a set of features (e.g., housing age, total rooms, etc.). The target or dependent variable (i.e., the median housing value) is a numeric value. Hence, we have a regression task to deal with.
The features of the data set are pretty much self-explanatory, but let us load the CSV file using pandas and look at the first five rows.
We can execute more methods to get a feel for about the data, like df.info() or df.describe(), while a simple histogram of each numerical instance — using the df.hist() method — would give us a better picture of the information in our hands. But, since this is not the scope of this article, let us move onto the next step, which is splitting the data set into train and test sets.
Creating a test set is really easy in theory; just select a few rows at random — typically the 10% or 20% of the full data set — and keep them in a new, separate dataframe. Moreover, for reproducibility, we could set a random_state number so every time we run an experiment we get back the same test set. That would also help compare different approaches directly because every algorithm we choose is evaluated on the same test set.
Moving forward, we use a convenient method provided by Scikit-Learn named train_test_split(). The method accepts lists, numpy arrays, scipy sparse matrices or pandas dataframes. We should also provide the split percentage as it is None by default and a random_state number.
We can see that the method returns a tuple, which we can unpack directly into a train and a test set. Since we pass a dataframe to the method, the resulting train and test sets are also dataframes. Keep in mind that by default the method first shuffles the data set and then splits it. To avoid this behaviour we could set the shuffle attribute to False.
Usually, if the data set is large enough (especially relative to the number of attributes) randomly splitting it would suffice. But if that’s not the case, random splitting could introduce significant sampling bias.
train_set, test_set = train_test_split(df, test_size=.2, random_state=42, shuffle=False)
We now have a randomly generated test set to evaluate our model on. But is it any good? Is it representative of the population? Well, it depends. Usually, if the data set is large enough (especially relative to the number of attributes) randomly splitting it would suffice. But if that’s not the case, random splitting could introduce significant sampling bias. So, let us see how to fix this problem.
Imagine we are running a survey in the US that records the education level and median income of a specific state. If we only question people that live in expensive districts we would surely introduce significant bias in our sample. Thus, we need a way to select people of any economic status roughly approximating the corresponding distribution of the population.
In our case, let us first check if there is a variable that correlates highly with our target variable. This is done easily using the pandas.corr() method.
We sort the results for the dependent variable in descending order and we get that median_income has a fairly strong positive correlation with median_house_value. This is surely something to expect.
It seems that splitting the data set in a stratified fashion, using median_income as the class labels would be a good idea. First, let us create a new variable that creates the class labels for this attribute.
pd.cut will create five classes, according to the bins we specify and keep them in a new variable we name income_cat for income category. We are now ready to split our data set in a stratified fashion.
The only change is that we now set the stratify argument of the train_test_split() method with an array-like object that sets the label classes. There is also another, more involved way to do this, specified in the code sample below for legacy purposes.
In any case, let us see how we did. We will examine the ratio for each income category in the full data set, as well as in the test sample.
Let us compare the two results side by side.
We can see that we are very close. The small differences are really insignificant. We now have a test set that follows the distribution of the income category in our population!
Creating a test set is not always that straight-forward. We must be sure that the test set resembles closely the intricacies of our population. The same goes for our validation sets as well. For instance, check the StratifiedKFold() method provided by Scikit-Learn.
In this story, we saw how we can split a data set into train and test sets both randomly and in a stratified fashion. We implemented the corresponding solutions in Python, using the Scikit-Learn library. Finally, we provided the details and advantages for each method and a simple practical rule on when to use each one.
Learning Rate is my weekly newsletter for those who are curious about the world of AI and MLOps. You’ll hear from me every Friday with updates and thoughts on the latest AI news, research, repos and books. Subscribe here!
My name is Dimitris Poulopoulos and I’m a machine learning researcher at BigDataStack and PhD(c) at the University of Piraeus, Greece. I have worked on designing and implementing AI and software solutions for major clients such as the European Commission, Eurostat, IMF, the European Central Bank, OECD, and IKEA. If you are interested in reading more posts about Machine Learning, Deep Learning and Data Science, follow me on Medium, LinkedIn or @james2pl on twitter.
|
[
{
"code": null,
"e": 605,
"s": 171,
"text": "Splitting a data set into train and test sets is usually one of the first processing steps in a machine learning pipeline. After this point, there is just one inviolable rule: set aside the test data split and refer to it again only when your model is ready for its final evaluation. But is there a way to be confident that the split we made is the right one? How can we be sure that the test set is representative of our population?"
},
{
"code": null,
"e": 739,
"s": 605,
"text": "We must be sure that the test set resembles closely the intricacies of our population. The same goes for our validation sets as well."
},
{
"code": null,
"e": 1124,
"s": 739,
"text": "In this story, we discuss two methods of splitting: random and stratified sampling. We consider their advantages and debate over which one to use under specific circumstances. This story is actually my published notes on the excellent Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems by Aurélien Géron."
},
{
"code": null,
"e": 1346,
"s": 1124,
"text": "Learning Rate is my weekly newsletter for those who are curious about the world of AI and MLOps. You’ll hear from me every Friday with updates and thoughts on the latest AI news, research, repos and books. Subscribe here!"
},
{
"code": null,
"e": 1541,
"s": 1346,
"text": "For this example, we use the California Housing Prices data set. This data set is excellent for introductory tutorials due to its familiar nature, few missing values, modest size and clear goal."
},
{
"code": null,
"e": 1879,
"s": 1541,
"text": "This dataset is based on data from the 1990 California census. The task is to predict the median value of the houses in a specific district, given a set of features (e.g., housing age, total rooms, etc.). The target or dependent variable (i.e., the median housing value) is a numeric value. Hence, we have a regression task to deal with."
},
{
"code": null,
"e": 2017,
"s": 1879,
"text": "The features of the data set are pretty much self-explanatory, but let us load the CSV file using pandas and look at the first five rows."
},
{
"code": null,
"e": 2399,
"s": 2017,
"text": "We can execute more methods to get a feel for about the data, like df.info() or df.describe(), while a simple histogram of each numerical instance — using the df.hist() method — would give us a better picture of the information in our hands. But, since this is not the scope of this article, let us move onto the next step, which is splitting the data set into train and test sets."
},
{
"code": null,
"e": 2832,
"s": 2399,
"text": "Creating a test set is really easy in theory; just select a few rows at random — typically the 10% or 20% of the full data set — and keep them in a new, separate dataframe. Moreover, for reproducibility, we could set a random_state number so every time we run an experiment we get back the same test set. That would also help compare different approaches directly because every algorithm we choose is evaluated on the same test set."
},
{
"code": null,
"e": 3106,
"s": 2832,
"text": "Moving forward, we use a convenient method provided by Scikit-Learn named train_test_split(). The method accepts lists, numpy arrays, scipy sparse matrices or pandas dataframes. We should also provide the split percentage as it is None by default and a random_state number."
},
{
"code": null,
"e": 3461,
"s": 3106,
"text": "We can see that the method returns a tuple, which we can unpack directly into a train and a test set. Since we pass a dataframe to the method, the resulting train and test sets are also dataframes. Keep in mind that by default the method first shuffles the data set and then splits it. To avoid this behaviour we could set the shuffle attribute to False."
},
{
"code": null,
"e": 3677,
"s": 3461,
"text": "Usually, if the data set is large enough (especially relative to the number of attributes) randomly splitting it would suffice. But if that’s not the case, random splitting could introduce significant sampling bias."
},
{
"code": null,
"e": 3766,
"s": 3677,
"text": "train_set, test_set = train_test_split(df, test_size=.2, random_state=42, shuffle=False)"
},
{
"code": null,
"e": 4168,
"s": 3766,
"text": "We now have a randomly generated test set to evaluate our model on. But is it any good? Is it representative of the population? Well, it depends. Usually, if the data set is large enough (especially relative to the number of attributes) randomly splitting it would suffice. But if that’s not the case, random splitting could introduce significant sampling bias. So, let us see how to fix this problem."
},
{
"code": null,
"e": 4532,
"s": 4168,
"text": "Imagine we are running a survey in the US that records the education level and median income of a specific state. If we only question people that live in expensive districts we would surely introduce significant bias in our sample. Thus, we need a way to select people of any economic status roughly approximating the corresponding distribution of the population."
},
{
"code": null,
"e": 4688,
"s": 4532,
"text": "In our case, let us first check if there is a variable that correlates highly with our target variable. This is done easily using the pandas.corr() method."
},
{
"code": null,
"e": 4887,
"s": 4688,
"text": "We sort the results for the dependent variable in descending order and we get that median_income has a fairly strong positive correlation with median_house_value. This is surely something to expect."
},
{
"code": null,
"e": 5097,
"s": 4887,
"text": "It seems that splitting the data set in a stratified fashion, using median_income as the class labels would be a good idea. First, let us create a new variable that creates the class labels for this attribute."
},
{
"code": null,
"e": 5299,
"s": 5097,
"text": "pd.cut will create five classes, according to the bins we specify and keep them in a new variable we name income_cat for income category. We are now ready to split our data set in a stratified fashion."
},
{
"code": null,
"e": 5553,
"s": 5299,
"text": "The only change is that we now set the stratify argument of the train_test_split() method with an array-like object that sets the label classes. There is also another, more involved way to do this, specified in the code sample below for legacy purposes."
},
{
"code": null,
"e": 5693,
"s": 5553,
"text": "In any case, let us see how we did. We will examine the ratio for each income category in the full data set, as well as in the test sample."
},
{
"code": null,
"e": 5738,
"s": 5693,
"text": "Let us compare the two results side by side."
},
{
"code": null,
"e": 5916,
"s": 5738,
"text": "We can see that we are very close. The small differences are really insignificant. We now have a test set that follows the distribution of the income category in our population!"
},
{
"code": null,
"e": 6182,
"s": 5916,
"text": "Creating a test set is not always that straight-forward. We must be sure that the test set resembles closely the intricacies of our population. The same goes for our validation sets as well. For instance, check the StratifiedKFold() method provided by Scikit-Learn."
},
{
"code": null,
"e": 6503,
"s": 6182,
"text": "In this story, we saw how we can split a data set into train and test sets both randomly and in a stratified fashion. We implemented the corresponding solutions in Python, using the Scikit-Learn library. Finally, we provided the details and advantages for each method and a simple practical rule on when to use each one."
},
{
"code": null,
"e": 6725,
"s": 6503,
"text": "Learning Rate is my weekly newsletter for those who are curious about the world of AI and MLOps. You’ll hear from me every Friday with updates and thoughts on the latest AI news, research, repos and books. Subscribe here!"
}
] |
Python dictionary fromkeys() Method
|
Python dictionary method fromkeys() creates a new dictionary with keys from seq and values set to value.
Following is the syntax for fromkeys() method −
dict.fromkeys(seq[, value])
seq − This is the list of values which would be used for dictionary keys preparation.
seq − This is the list of values which would be used for dictionary keys preparation.
value − This is optional, if provided then value would be set to this value
value − This is optional, if provided then value would be set to this value
This method returns the list.
The following example shows the usage of fromkeys() method.
#!/usr/bin/python
seq = ('name', 'age', 'sex')
dict = dict.fromkeys(seq)
print "New Dictionary : %s" % str(dict)
dict = dict.fromkeys(seq, 10)
print "New Dictionary : %s" % str(dict)
When we run above program, it produces following result −
New Dictionary : {'age': None, 'name': None, 'sex': None}
New Dictionary : {'age': 10, 'name': 10, 'sex': 10}
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": 2350,
"s": 2244,
"text": "Python dictionary method fromkeys() creates a new dictionary with keys from seq and values set to value."
},
{
"code": null,
"e": 2398,
"s": 2350,
"text": "Following is the syntax for fromkeys() method −"
},
{
"code": null,
"e": 2427,
"s": 2398,
"text": "dict.fromkeys(seq[, value])\n"
},
{
"code": null,
"e": 2513,
"s": 2427,
"text": "seq − This is the list of values which would be used for dictionary keys preparation."
},
{
"code": null,
"e": 2599,
"s": 2513,
"text": "seq − This is the list of values which would be used for dictionary keys preparation."
},
{
"code": null,
"e": 2675,
"s": 2599,
"text": "value − This is optional, if provided then value would be set to this value"
},
{
"code": null,
"e": 2751,
"s": 2675,
"text": "value − This is optional, if provided then value would be set to this value"
},
{
"code": null,
"e": 2781,
"s": 2751,
"text": "This method returns the list."
},
{
"code": null,
"e": 2841,
"s": 2781,
"text": "The following example shows the usage of fromkeys() method."
},
{
"code": null,
"e": 3028,
"s": 2841,
"text": "#!/usr/bin/python\n\nseq = ('name', 'age', 'sex')\ndict = dict.fromkeys(seq)\nprint \"New Dictionary : %s\" % str(dict)\n\ndict = dict.fromkeys(seq, 10)\nprint \"New Dictionary : %s\" % str(dict)"
},
{
"code": null,
"e": 3086,
"s": 3028,
"text": "When we run above program, it produces following result −"
},
{
"code": null,
"e": 3197,
"s": 3086,
"text": "New Dictionary : {'age': None, 'name': None, 'sex': None}\nNew Dictionary : {'age': 10, 'name': 10, 'sex': 10}\n"
},
{
"code": null,
"e": 3234,
"s": 3197,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3250,
"s": 3234,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3283,
"s": 3250,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3302,
"s": 3283,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3337,
"s": 3302,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3359,
"s": 3337,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3393,
"s": 3359,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3421,
"s": 3393,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3456,
"s": 3421,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3470,
"s": 3456,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3503,
"s": 3470,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3520,
"s": 3503,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3527,
"s": 3520,
"text": " Print"
},
{
"code": null,
"e": 3538,
"s": 3527,
"text": " Add Notes"
}
] |
rsync - Unix, Linux Command
|
rsync [OPTION]... SRC [SRC]... DEST
rsync [OPTION]... SRC [SRC]... [USER@]HOST:DEST
rsync [OPTION]... SRC [SRC]... [USER@]HOST::DEST
rsync [OPTION]... SRC [SRC]... rsync://[USER@]HOST[:PORT]/DEST
rsync [OPTION]... SRC
rsync [OPTION]... [USER@]HOST:SRC [DEST]
rsync [OPTION]... [USER@]HOST::SRC [DEST]
rsync [OPTION]... rsync://[USER@]HOST[:PORT]/SRC [DEST]
rsync is a program that behaves in much the same way that rcp does,
but has many more options and uses the rsync remote-update protocol to
greatly speed up file transfers when the destination file is being
updated.
The rsync remote-update protocol allows rsync to transfer just the
differences between two sets of files across the network connection, using
an efficient checksum-search algorithm described in the technical
report that accompanies this package.
Some of the additional features of rsync are:
Rsync copies files either to or from a remote host, or locally on the
current host (it does not support copying files between two remote hosts).
There are two different ways for rsync to contact a remote system: using a
remote-shell program as the transport (such as ssh or rsh) or contacting an
rsync daemon directly via TCP. The remote-shell transport is used whenever
the source or destination path contains a single colon (:) separator after
a host specification. Contacting an rsync daemon directly happens when the
source or destination path contains a double colon (::) separator after a
host specification, OR when an rsync:// URL is specified (see also the
"USING RSYNC-DAEMON FEATURES VIA A REMOTE-SHELL CONNECTION" section for
an exception to this latter rule).
As a special case, if a single source arg is specified without a
destination, the files are listed in an output format similar to "ls -l".
As expected, if neither the source or destination path specify a remote
host, the copy occurs locally (see also the --list-only option).
See the file README for installation instructions.
Once installed, you can use rsync to any machine that you can access via
a remote shell (as well as some that you can access using the rsync
daemon-mode protocol). For remote transfers, a modern rsync uses ssh
for its communications, but it may have been configured to use a
different remote shell by default, such as rsh or remsh.
You can also specify any remote shell you like, either by using the -e
command line option, or by setting the RSYNC_RSH environment variable.
Note that rsync must be installed on both the source and destination
machines.
You use rsync in the same way you use rcp. You must specify a source
and a destination, one of which may be remote.
Perhaps the best way to explain the syntax is with some examples:
rsync -t *.c foo:src/
This would transfer all files matching the pattern *.c from the
current directory to the directory src on the machine foo. If any of
the files already exist on the remote system then the rsync
remote-update protocol is used to update the file by sending only the
differences. See the tech report for details.
rsync -avz foo:src/bar /data/tmp
This would recursively transfer all files from the directory src/bar on the
machine foo into the /data/tmp/bar directory on the local machine. The
files are transferred in "archive" mode, which ensures that symbolic
links, devices, attributes, permissions, ownerships, etc. are preserved
in the transfer. Additionally, compression will be used to reduce the
size of data portions of the transfer.
rsync -avz foo:src/bar/ /data/tmp
A trailing slash on the source changes this behavior to avoid creating an
additional directory level at the destination. You can think of a trailing
/ on a source as meaning "copy the contents of this directory" as opposed
to "copy the directory by name", but in both cases the attributes of the
containing directory are transferred to the containing directory on the
destination. In other words, each of the following commands copies the
files in the same way, including their setting of the attributes of
/dest/foo:
rsync -av /src/foo /dest
rsync -av /src/foo/ /dest/foo
Note also that host and module references don’t require a trailing slash to
copy the contents of the default directory. For example, both of these
copy the remote directory’s contents into "/dest":
rsync -av host: /dest
rsync -av host::module /dest
You can also use rsync in local-only mode, where both the source and
destination don’t have a ’:’ in the name. In this case it behaves like
an improved copy command.
Finally, you can list all the (listable) modules available from a
particular rsync daemon by leaving off the module name:
rsync somehost.mydomain.com::
See the following section for more details.
The syntax for requesting multiple files from a remote host involves using
quoted spaces in the SRC. Some examples:
rsync host::’modname/dir1/file1 modname/dir2/file2’ /dest
This would copy file1 and file2 into /dest from an rsync daemon. Each
additional arg must include the same "modname/" prefix as the first one,
and must be preceded by a single space. All other spaces are assumed
to be a part of the filenames.
rsync -av host:’dir1/file1 dir2/file2’ /dest
This would copy file1 and file2 into /dest using a remote shell. This
word-splitting is done by the remote shell, so if it doesn’t work it means
that the remote shell isn’t configured to split its args based on
whitespace (a very rare setting, but not unknown). If you need to transfer
a filename that contains whitespace, you’ll need to either escape the
whitespace in a way that the remote shell will understand, or use wildcards
in place of the spaces. Two examples of this are:
rsync -av host:’file\ name\ with\ spaces’ /dest
rsync -av host:file?name?with?spaces /dest
This latter example assumes that your shell passes through unmatched
wildcards. If it complains about "no match", put the name in quotes.
It is also possible to use rsync without a remote shell as the transport.
In this case you will directly connect to a remote rsync daemon, typically
using TCP port 873. (This obviously requires the daemon to be running on
the remote system, so refer to the STARTING AN RSYNC DAEMON TO ACCEPT
CONNECTIONS section below for information on that.)
Using rsync in this way is the same as using it with a remote shell except
that:
rsync -av host::src /dest
rsync -av host::src /dest
Some modules on the remote daemon may require authentication. If so,
you will receive a password prompt when you connect. You can avoid the
password prompt by setting the environment variable RSYNC_PASSWORD to
the password you want to use or using the --password-file option. This
may be useful when scripting rsync.
WARNING: On some systems environment variables are visible to all
users. On those systems using --password-file is recommended.
You may establish the connection via a web proxy by setting the
environment variable RSYNC_PROXY to a hostname:port pair pointing to
your web proxy. Note that your web proxy’s configuration must support
proxy connections to port 873.
It is sometimes useful to use various features of an rsync daemon (such as
named modules) without actually allowing any new socket connections into a
system (other than what is already required to allow remote-shell access).
Rsync supports connecting to a host using a remote shell and then spawning
a single-use "daemon" server that expects to read its config file in the
home dir of the remote user. This can be useful if you want to encrypt a
daemon-style transfer’s data, but since the daemon is started up fresh by
the remote user, you may not be able to use features such as chroot or
change the uid used by the daemon. (For another way to encrypt a daemon
transfer, consider using ssh to tunnel a local port to a remote machine and
configure a normal rsync daemon on that remote host to only allow
connections from "localhost".)
From the user’s perspective, a daemon transfer via a remote-shell
connection uses nearly the same command-line syntax as a normal
rsync-daemon transfer, with the only exception being that you must
explicitly set the remote shell program on the command-line with the
--rsh=COMMAND option. (Setting the RSYNC_RSH in the environment
will not turn on this functionality.) For example:
rsync -av --rsh=ssh host::module /dest
rsync -av --rsh=ssh host::module /dest
If you need to specify a different remote-shell user, keep in mind that the
user@ prefix in front of the host is specifying the rsync-user value (for a
module that requires user-based authentication). This means that you must
give the ’-l user’ option to ssh when specifying the remote-shell, as in
this example that uses the short version of the --rsh option:
rsync -av -e "ssh -l ssh-user" rsync-user@host::module /dest
rsync -av -e "ssh -l ssh-user" rsync-user@host::module /dest
The "ssh-user" will be used at the ssh level; the "rsync-user" will be
used to log-in to the "module".
In order to connect to an rsync daemon, the remote system needs to have a
daemon already running (or it needs to have configured something like inetd
to spawn an rsync daemon for incoming connections on a particular port).
For full information on how to start a daemon that will handling incoming
socket connections, see the rsyncd.conf(5) man page -- that is the config
file for the daemon, and it contains the full details for how to run the
daemon (including stand-alone and inetd configurations).
If you’re using one of the remote-shell transports for the transfer, there is
no need to manually start an rsync daemon.
Here are some examples of how I use rsync.
To backup my wife’s home directory, which consists of large MS Word
files and mail folders, I use a cron job that runs
rsync -Cavz . arvidsjaur:backup
each night over a PPP connection to a duplicate directory on my machine
"arvidsjaur".
To synchronize my samba source trees I use the following Makefile
targets:
get:
rsync -avuzb --exclude ’*~’ samba:samba/ .
put:
rsync -Cavuzb . samba:samba/
sync: get put
get:
rsync -avuzb --exclude ’*~’ samba:samba/ .
put:
rsync -Cavuzb . samba:samba/
sync: get put
this allows me to sync with a CVS directory at the other end of the
connection. I then do CVS operations on the remote machine, which saves a
lot of time as the remote CVS protocol isn’t very efficient.
I mirror a directory between my "old" and "new" ftp sites with the
command:
rsync -az -e ssh --delete ~ftp/pub/samba nimbus:"~ftp/pub/tridge"
This is launched from cron every few hours.
Here is a short summary of the options available in rsync. Please refer
to the detailed description below for a complete description.
-v, --verbose increase verbosity
-q, --quiet suppress non-error messages
-c, --checksum skip based on checksum, not mod-time & size
-a, --archive archive mode; same as -rlptgoD (no -H)
--no-OPTION turn off an implied OPTION (e.g. --no-D)
-r, --recursive recurse into directories
-R, --relative use relative path names
--no-implied-dirs don’t send implied dirs with --relative
-b, --backup make backups (see --suffix & --backup-dir)
--backup-dir=DIR make backups into hierarchy based in DIR
--suffix=SUFFIX backup suffix (default ~ w/o --backup-dir)
-u, --update skip files that are newer on the receiver
--inplace update destination files in-place
--append append data onto shorter files
-d, --dirs transfer directories without recursing
-l, --links copy symlinks as symlinks
-L, --copy-links transform symlink into referent file/dir
--copy-unsafe-links only "unsafe" symlinks are transformed
--safe-links ignore symlinks that point outside the tree
-k, --copy-dirlinks transform symlink to dir into referent dir
-K, --keep-dirlinks treat symlinked dir on receiver as dir
-H, --hard-links preserve hard links
-p, --perms preserve permissions
-E, --executability preserve executability
-A, --acls preserve ACLs (implies -p) [non-standard]
-X, --xattrs preserve extended attrs (implies -p) [n.s.]
--chmod=CHMOD change destination permissions
-o, --owner preserve owner (super-user only)
-g, --group preserve group
--devices preserve device files (super-user only)
--specials preserve special files
-D same as --devices --specials
-t, --times preserve times
-O, --omit-dir-times omit directories when preserving times
--super receiver attempts super-user activities
-S, --sparse handle sparse files efficiently
-n, --dry-run show what would have been transferred
-W, --whole-file copy files whole (without rsync algorithm)
-x, --one-file-system don’t cross filesystem boundaries
-B, --block-size=SIZE force a fixed checksum block-size
-e, --rsh=COMMAND specify the remote shell to use
--rsync-path=PROGRAM specify the rsync to run on remote machine
--existing ignore non-existing files on receiving side
--ignore-existing ignore files that already exist on receiver
--remove-sent-files sent files/symlinks are removed from sender
--del an alias for --delete-during
--delete delete files that don’t exist on sender
--delete-before receiver deletes before transfer (default)
--delete-during receiver deletes during xfer, not before
--delete-after receiver deletes after transfer, not before
--delete-excluded also delete excluded files on receiver
--ignore-errors delete even if there are I/O errors
--force force deletion of dirs even if not empty
--max-delete=NUM don’t delete more than NUM files
--max-size=SIZE don’t transfer any file larger than SIZE
--min-size=SIZE don’t transfer any file smaller than SIZE
--partial keep partially transferred files
--partial-dir=DIR put a partially transferred file into DIR
--delay-updates put all updated files into place at end
-m, --prune-empty-dirs prune empty directory chains from file-list
--numeric-ids don’t map uid/gid values by user/group name
--timeout=TIME set I/O timeout in seconds
-I, --ignore-times don’t skip files that match size and time
--size-only skip files that match in size
--modify-window=NUM compare mod-times with reduced accuracy
-T, --temp-dir=DIR create temporary files in directory DIR
-y, --fuzzy find similar file for basis if no dest file
--compare-dest=DIR also compare received files relative to DIR
--copy-dest=DIR ... and include copies of unchanged files
--link-dest=DIR hardlink to files in DIR when unchanged
-z, --compress compress file data during the transfer
--compress-level=NUM explicitly set compression level
-C, --cvs-exclude auto-ignore files in the same way CVS does
-f, --filter=RULE add a file-filtering RULE
-F same as --filter=’dir-merge /.rsync-filter’
repeated: --filter=’- .rsync-filter’
--exclude=PATTERN exclude files matching PATTERN
--exclude-from=FILE read exclude patterns from FILE
--include=PATTERN don’t exclude files matching PATTERN
--include-from=FILE read include patterns from FILE
--files-from=FILE read list of source-file names from FILE
-0, --from0 all *from/filter files are delimited by 0s
--address=ADDRESS bind address for outgoing socket to daemon
--port=PORT specify double-colon alternate port number
--sockopts=OPTIONS specify custom TCP options
--blocking-io use blocking I/O for the remote shell
--stats give some file-transfer stats
-8, --8-bit-output leave high-bit chars unescaped in output
-h, --human-readable output numbers in a human-readable format
--progress show progress during transfer
-P same as --partial --progress
-i, --itemize-changes output a change-summary for all updates
--log-format=FORMAT output filenames using the specified format
--password-file=FILE read password from FILE
--list-only list the files instead of copying them
--bwlimit=KBPS limit I/O bandwidth; KBytes per second
--write-batch=FILE write a batched update to FILE
--only-write-batch=FILE like --write-batch but w/o updating dest
--read-batch=FILE read a batched update from FILE
--protocol=NUM force an older protocol version to be used
--checksum-seed=NUM set block/file checksum seed (advanced)
-4, --ipv4 prefer IPv4
-6, --ipv6 prefer IPv6
--version print version number
(-h) --help show this help (see below for -h comment)
-v, --verbose increase verbosity
-q, --quiet suppress non-error messages
-c, --checksum skip based on checksum, not mod-time & size
-a, --archive archive mode; same as -rlptgoD (no -H)
--no-OPTION turn off an implied OPTION (e.g. --no-D)
-r, --recursive recurse into directories
-R, --relative use relative path names
--no-implied-dirs don’t send implied dirs with --relative
-b, --backup make backups (see --suffix & --backup-dir)
--backup-dir=DIR make backups into hierarchy based in DIR
--suffix=SUFFIX backup suffix (default ~ w/o --backup-dir)
-u, --update skip files that are newer on the receiver
--inplace update destination files in-place
--append append data onto shorter files
-d, --dirs transfer directories without recursing
-l, --links copy symlinks as symlinks
-L, --copy-links transform symlink into referent file/dir
--copy-unsafe-links only "unsafe" symlinks are transformed
--safe-links ignore symlinks that point outside the tree
-k, --copy-dirlinks transform symlink to dir into referent dir
-K, --keep-dirlinks treat symlinked dir on receiver as dir
-H, --hard-links preserve hard links
-p, --perms preserve permissions
-E, --executability preserve executability
-A, --acls preserve ACLs (implies -p) [non-standard]
-X, --xattrs preserve extended attrs (implies -p) [n.s.]
--chmod=CHMOD change destination permissions
-o, --owner preserve owner (super-user only)
-g, --group preserve group
--devices preserve device files (super-user only)
--specials preserve special files
-D same as --devices --specials
-t, --times preserve times
-O, --omit-dir-times omit directories when preserving times
--super receiver attempts super-user activities
-S, --sparse handle sparse files efficiently
-n, --dry-run show what would have been transferred
-W, --whole-file copy files whole (without rsync algorithm)
-x, --one-file-system don’t cross filesystem boundaries
-B, --block-size=SIZE force a fixed checksum block-size
-e, --rsh=COMMAND specify the remote shell to use
--rsync-path=PROGRAM specify the rsync to run on remote machine
--existing ignore non-existing files on receiving side
--ignore-existing ignore files that already exist on receiver
--remove-sent-files sent files/symlinks are removed from sender
--del an alias for --delete-during
--delete delete files that don’t exist on sender
--delete-before receiver deletes before transfer (default)
--delete-during receiver deletes during xfer, not before
--delete-after receiver deletes after transfer, not before
--delete-excluded also delete excluded files on receiver
--ignore-errors delete even if there are I/O errors
--force force deletion of dirs even if not empty
--max-delete=NUM don’t delete more than NUM files
--max-size=SIZE don’t transfer any file larger than SIZE
--min-size=SIZE don’t transfer any file smaller than SIZE
--partial keep partially transferred files
--partial-dir=DIR put a partially transferred file into DIR
--delay-updates put all updated files into place at end
-m, --prune-empty-dirs prune empty directory chains from file-list
--numeric-ids don’t map uid/gid values by user/group name
--timeout=TIME set I/O timeout in seconds
-I, --ignore-times don’t skip files that match size and time
--size-only skip files that match in size
--modify-window=NUM compare mod-times with reduced accuracy
-T, --temp-dir=DIR create temporary files in directory DIR
-y, --fuzzy find similar file for basis if no dest file
--compare-dest=DIR also compare received files relative to DIR
--copy-dest=DIR ... and include copies of unchanged files
--link-dest=DIR hardlink to files in DIR when unchanged
-z, --compress compress file data during the transfer
--compress-level=NUM explicitly set compression level
-C, --cvs-exclude auto-ignore files in the same way CVS does
-f, --filter=RULE add a file-filtering RULE
-F same as --filter=’dir-merge /.rsync-filter’
repeated: --filter=’- .rsync-filter’
--exclude=PATTERN exclude files matching PATTERN
--exclude-from=FILE read exclude patterns from FILE
--include=PATTERN don’t exclude files matching PATTERN
--include-from=FILE read include patterns from FILE
--files-from=FILE read list of source-file names from FILE
-0, --from0 all *from/filter files are delimited by 0s
--address=ADDRESS bind address for outgoing socket to daemon
--port=PORT specify double-colon alternate port number
--sockopts=OPTIONS specify custom TCP options
--blocking-io use blocking I/O for the remote shell
--stats give some file-transfer stats
-8, --8-bit-output leave high-bit chars unescaped in output
-h, --human-readable output numbers in a human-readable format
--progress show progress during transfer
-P same as --partial --progress
-i, --itemize-changes output a change-summary for all updates
--log-format=FORMAT output filenames using the specified format
--password-file=FILE read password from FILE
--list-only list the files instead of copying them
--bwlimit=KBPS limit I/O bandwidth; KBytes per second
--write-batch=FILE write a batched update to FILE
--only-write-batch=FILE like --write-batch but w/o updating dest
--read-batch=FILE read a batched update from FILE
--protocol=NUM force an older protocol version to be used
--checksum-seed=NUM set block/file checksum seed (advanced)
-4, --ipv4 prefer IPv4
-6, --ipv6 prefer IPv6
--version print version number
(-h) --help show this help (see below for -h comment)
Rsync can also be run as a daemon, in which case the following options are
accepted:
--daemon run as an rsync daemon
--address=ADDRESS bind to the specified address
--bwlimit=KBPS limit I/O bandwidth; KBytes per second
--config=FILE specify alternate rsyncd.conf file
--no-detach do not detach from the parent
--port=PORT listen on alternate port number
--sockopts=OPTIONS specify custom TCP options
-v, --verbose increase verbosity
-4, --ipv4 prefer IPv4
-6, --ipv6 prefer IPv6
-h, --help show this help (if used after --daemon)
--daemon run as an rsync daemon
--address=ADDRESS bind to the specified address
--bwlimit=KBPS limit I/O bandwidth; KBytes per second
--config=FILE specify alternate rsyncd.conf file
--no-detach do not detach from the parent
--port=PORT listen on alternate port number
--sockopts=OPTIONS specify custom TCP options
-v, --verbose increase verbosity
-4, --ipv4 prefer IPv4
-6, --ipv6 prefer IPv6
-h, --help show this help (if used after --daemon)
rsync uses the GNU long options package. Many of the command line
options have two variants, one short and one long. These are shown
below, separated by commas. Some options only have a long variant.
The ’=’ for options that take a parameter is optional; whitespace
can be used instead.
782448 63% 110.64kB/s 0:00:04
782448 63% 110.64kB/s 0:00:04
1238099 100% 146.38kB/s 0:00:08 (5, 57.1% of 396)
1238099 100% 146.38kB/s 0:00:08 (5, 57.1% of 396)
rsync -av --list-only foo* dest/
rsync -av --list-only foo* dest/
The options allowed when starting an rsync daemon are as follows:
The filter rules allow for flexible selection of which files to transfer
(include) and which files to skip (exclude). The rules either directly
specify include/exclude patterns or they specify a way to acquire more
include/exclude patterns (e.g. to read them from a file).
As the list of files/directories to transfer is built, rsync checks each
name to be transferred against the list of include/exclude patterns in
turn, and the first matching pattern is acted on: if it is an exclude
pattern, then that file is skipped; if it is an include pattern then that
filename is not skipped; if no matching pattern is found, then the
filename is not skipped.
Rsync builds an ordered list of filter rules as specified on the
command-line. Filter rules have the following syntax:
RULE [PATTERN_OR_FILENAME]
RULE,MODIFIERS [PATTERN_OR_FILENAME]
You have your choice of using either short or long RULE names, as described
below. If you use a short-named rule, the ’,’ separating the RULE from the
MODIFIERS is optional. The PATTERN or FILENAME that follows (when present)
must come after either a single space or an underscore (_).
Here are the available rule prefixes:
exclude, - specifies an exclude pattern.
include, + specifies an include pattern.
merge, . specifies a merge-file to read for more rules.
dir-merge, : specifies a per-directory merge-file.
hide, H specifies a pattern for hiding files from the transfer.
show, S files that match the pattern are not hidden.
protect, P specifies a pattern for protecting files from deletion.
risk, R files that match the pattern are not protected.
clear, ! clears the current include/exclude list (takes no arg)
When rules are being read from a file, empty lines are ignored, as are
comment lines that start with a "#".
Note that the --include/--exclude command-line options do not allow the
full range of rule parsing as described above -- they only allow the
specification of include/exclude patterns plus a "!" token to clear the
list (and the normal comment parsing when rules are read from a file).
If a pattern
does not begin with "- " (dash, space) or "+ " (plus, space), then the
rule will be interpreted as if "+ " (for an include option) or "- " (for
an exclude option) were prefixed to the string. A --filter option, on
the other hand, must always contain either a short or long rule name at the
start of the rule.
Note also that the --filter, --include, and --exclude options take one
rule/pattern each. To add multiple ones, you can repeat the options on
the command-line, use the merge-file syntax of the --filter option, or
the --include-from/--exclude-from options.
You can include and exclude files by specifying patterns using the "+",
"-", etc. filter rules (as introduced in the FILTER RULES section above).
The include/exclude rules each specify a pattern that is matched against
the names of the files that are going to be transferred. These patterns
can take several forms:
You can merge whole files into your filter rules by specifying either a
merge (.) or a dir-merge (:) filter rule (as introduced in the FILTER RULES
section above).
There are two kinds of merged files -- single-instance (’.’) and
per-directory (’:’). A single-instance merge file is read one time, and
its rules are incorporated into the filter list in the place of the "."
rule. For per-directory merge files, rsync will scan every directory that
it traverses for the named file, merging its contents when the file exists
into the current list of inherited rules. These per-directory rule files
must be created on the sending side because it is the sending side that is
being scanned for the available files to transfer. These rule files may
also need to be transferred to the receiving side if you want them to
affect what files don’t get deleted (see PER-DIRECTORY RULES AND DELETE
below).
Some examples:
merge /etc/rsync/default.rules
. /etc/rsync/default.rules
dir-merge .per-dir-filter
dir-merge,n- .non-inherited-per-dir-excludes
:n- .non-inherited-per-dir-excludes
The following modifiers are accepted after a merge or dir-merge rule:
You can clear the current include/exclude list by using the "!" filter
rule (as introduced in the FILTER RULES section above). The "current"
list is either the global list of rules (if the rule is encountered while
parsing the filter options) or a set of per-directory rules (which are
inherited in their own sub-list, so a subdirectory can use this to clear
out the parent’s rules).
As mentioned earlier, global include/exclude patterns are anchored at the
"root of the transfer" (as opposed to per-directory patterns, which are
anchored at the merge-file’s directory). If you think of the transfer as
a subtree of names that are being sent from sender to receiver, the
transfer-root is where the tree starts to be duplicated in the destination
directory. This root governs where patterns that start with a / match.
Because the matching is relative to the transfer-root, changing the
trailing slash on a source path or changing your use of the --relative
option affects the path you need to use in your matching (in addition to
changing how much of the file tree is duplicated on the destination
host). The following examples demonstrate this.
Let’s say that we want to match two source files, one with an absolute
path of "/home/me/foo/bar", and one with a path of "/home/you/bar/baz".
Here is how the various command choices differ for a 2-source transfer:
Example cmd: rsync -a /home/me /home/you /dest
+/- pattern: /me/foo/bar
+/- pattern: /you/bar/baz
Target file: /dest/me/foo/bar
Target file: /dest/you/bar/baz
Example cmd: rsync -a /home/me/ /home/you/ /dest
+/- pattern: /foo/bar (note missing "me")
+/- pattern: /bar/baz (note missing "you")
Target file: /dest/foo/bar
Target file: /dest/bar/baz
Example cmd: rsync -a --relative /home/me/ /home/you /dest
+/- pattern: /home/me/foo/bar (note full path)
+/- pattern: /home/you/bar/baz (ditto)
Target file: /dest/home/me/foo/bar
Target file: /dest/home/you/bar/baz
Example cmd: cd /home; rsync -a --relative me/foo you/ /dest
+/- pattern: /me/foo/bar (starts at specified path)
+/- pattern: /you/bar/baz (ditto)
Target file: /dest/me/foo/bar
Target file: /dest/you/bar/baz
The easiest way to see what name you should filter is to just
look at the output when using --verbose and put a / in front of the name
(use the --dry-run option if you’re not yet ready to copy any files).
Without a delete option, per-directory rules are only relevant on the
sending side, so you can feel free to exclude the merge files themselves
without affecting the transfer. To make this easy, the ’e’ modifier adds
this exclude for you, as seen in these two equivalent commands:
rsync -av --filter=’: .excl’ --exclude=.excl host:src/dir /dest
rsync -av --filter=’:e .excl’ host:src/dir /dest
However, if you want to do a delete on the receiving side AND you want some
files to be excluded from being deleted, you’ll need to be sure that the
receiving side knows what files to exclude. The easiest way is to include
the per-directory merge files in the transfer and use --delete-after,
because this ensures that the receiving side gets all the same exclude
rules as the sending side before it tries to delete anything:
rsync -avF --delete-after host:src/dir /dest
However, if the merge files are not a part of the transfer, you’ll need to
either specify some global exclude rules (i.e. specified on the command
line), or you’ll need to maintain your own per-directory merge files on
the receiving side. An example of the first is this (assume that the
remote .rules files exclude themselves):
rsync -av --filter=’: .rules’ --filter=’. /my/extra.rules’
--delete host:src/dir /dest
rsync -av --filter=’: .rules’ --filter=’. /my/extra.rules’
--delete host:src/dir /dest
In the above example the extra.rules file can affect both sides of the
transfer, but (on the sending side) the rules are subservient to the rules
merged from the .rules files because they were specified after the
per-directory merge rule.
In one final example, the remote side is excluding the .rsync-filter
files from the transfer, but we want to use our own .rsync-filter files
to control what gets deleted on the receiving side. To do this we must
specifically exclude the per-directory merge files (so that they don’t get
deleted) and then put rules into the local files to control what else
should not get deleted. Like one of these commands:
rsync -av --filter=’:e /.rsync-filter’ --delete \
host:src/dir /dest
rsync -avFF --delete host:src/dir /dest
rsync -av --filter=’:e /.rsync-filter’ --delete \
host:src/dir /dest
rsync -avFF --delete host:src/dir /dest
Batch mode can be used to apply the same set of updates to many
identical systems. Suppose one has a tree which is replicated on a
number of hosts. Now suppose some changes have been made to this
source tree and those changes need to be propagated to the other
hosts. In order to do this using batch mode, rsync is run with the
write-batch option to apply the changes made to the source tree to one
of the destination trees. The write-batch option causes the rsync
client to store in a "batch file" all the information needed to repeat
this operation against other, identical destination trees.
To apply the recorded changes to another destination tree, run rsync
with the read-batch option, specifying the name of the same batch
file, and the destination tree. Rsync updates the destination tree
using the information stored in the batch file.
For convenience, one additional file is creating when the write-batch
option is used. This file’s name is created by appending
".sh" to the batch filename. The .sh file contains
a command-line suitable for updating a destination tree using that
batch file. It can be executed using a Bourne (or Bourne-like) shell,
optionally
passing in an alternate destination tree pathname which is then used
instead of the original path. This is useful when the destination tree
path differs from the original destination tree path.
Generating the batch file once saves having to perform the file
status, checksum, and data block generation more than once when
updating multiple destination trees. Multicast transport protocols can
be used to transfer the batch update files in parallel to many hosts
at once, instead of sending the same data to every host individually.
Examples:
$ rsync --write-batch=foo -a host:/source/dir/ /adest/dir/
$ scp foo* remote:
$ ssh remote ./foo.sh /bdest/dir/
$ rsync --write-batch=foo -a /source/dir/ /adest/dir/
$ ssh remote rsync --read-batch=- -a /bdest/dir/ <foo
In these examples, rsync is used to update /adest/dir/ from /source/dir/
and the information to repeat this operation is stored in "foo" and
"foo.sh". The host "remote" is then updated with the batched data going
into the directory /bdest/dir. The differences between the two examples
reveals some of the flexibility you have in how you deal with batches:
The read-batch option expects the destination tree that it is updating
to be identical to the destination tree that was used to create the
batch update fileset. When a difference between the destination trees
is encountered the update might be discarded with a warning (if the file
appears to be up-to-date already) or the file-update may be attempted
and then, if the file fails to verify, the update discarded with an
error. This means that it should be safe to re-run a read-batch operation
if the command got interrupted. If you wish to force the batched-update to
always be attempted regardless of the file’s size and date, use the -I
option (when reading the batch).
If an error occurs, the destination tree will probably be in a
partially updated state. In that case, rsync can
be used in its regular (non-batch) mode of operation to fix up the
destination tree.
The rsync version used on all destinations must be at least as new as the
one used to generate the batch file. Rsync will die with an error if the
protocol version in the batch file is too new for the batch-reading rsync
to handle. See also the --protocol option for a way to have the
creating rsync generate a batch file that an older rsync can understand.
(Note that batch files changed format in version 2.6.3, so mixing versions
older than that with newer versions will not work.)
When reading a batch file, rsync will force the value of certain options
to match the data in the batch file if you didn’t set them to the same
as the batch-writing command. Other options can (and should) be changed.
For instance --write-batch changes to --read-batch,
--files-from is dropped, and the
--filter/--include/--exclude options are not needed unless
one of the --delete options is specified.
The code that creates the BATCH.sh file transforms any filter/include/exclude
options into a single list that is appended as a "here" document to the
shell script file. An advanced user can use this to modify the exclude
list if a change in what gets deleted by --delete is desired. A normal
user can ignore this detail and just use the shell script as an easy way
to run the appropriate --read-batch command for the batched data.
The original batch mode in rsync was based on "rsync+", but the latest
version uses a new implementation.
Three basic behaviors are possible when rsync encounters a symbolic
link in the source directory.
By default, symbolic links are not transferred at all. A message
"skipping non-regular" file is emitted for any symlinks that exist.
If --links is specified, then symlinks are recreated with the same
target on the destination. Note that --archive implies
--links.
If --copy-links is specified, then symlinks are "collapsed" by
copying their referent, rather than the symlink.
rsync also distinguishes "safe" and "unsafe" symbolic links. An
example where this might be used is a web site mirror that wishes
ensure the rsync module they copy does not include symbolic links to
/etc/passwd in the public section of the site. Using
--copy-unsafe-links will cause any links to be copied as the file
they point to on the destination. Using --safe-links will cause
unsafe links to be omitted altogether. (Note that you must specify
--links for --safe-links to have any effect.)
Symbolic links are considered unsafe if they are absolute symlinks
(start with /), empty, or if they contain enough ".."
components to ascend from the directory being copied.
Here’s a summary of how the symlink options are interpreted. The list is
in order of precedence, so if your combination of options isn’t mentioned,
use the first line that is a complete subset of your options:
rsync occasionally produces error messages that may seem a little
cryptic. The one that seems to cause the most confusion is "protocol
version mismatch -- is your shell clean?".
This message is usually caused by your startup scripts or remote shell
facility producing unwanted garbage on the stream that rsync is using
for its transport. The way to diagnose this problem is to run your
remote shell like this:
ssh remotehost /bin/true > out.dat
then look at out.dat. If everything is working correctly then out.dat
should be a zero length file. If you are getting the above error from
rsync then you will probably find that out.dat contains some text or
data. Look at the contents and try to work out what is producing
it. The most common cause is incorrectly configured shell startup
scripts (such as .cshrc or .profile) that contain output statements
for non-interactive logins.
If you are having trouble debugging filter patterns, then
try specifying the -vv option. At this level of verbosity rsync will
show why each individual file is included or excluded.
/etc/rsyncd.conf or rsyncd.conf
times are transferred as *nix time_t values
When transferring to FAT filesystems rsync may re-sync
unmodified files.
See the comments on the --modify-window option.
file permissions, devices, etc. are transferred as native numerical
values
see also the comments on the --delete option
Please report bugs! See the website at
http://rsync.samba.org/
This man page is current for version 2.6.8 of rsync.
rsync is distributed under the GNU public license. See the file
COPYING for details.
A WEB site is available at
http://rsync.samba.org/. The site
includes an FAQ-O-Matic which may cover questions unanswered by this
manual page.
The primary ftp site for rsync is
ftp://rsync.samba.org/pub/rsync.
We would be delighted to hear from you if you like this program.
This program uses the excellent zlib compression library written by
Jean-loup Gailly and Mark Adler.
Thanks to Richard Brent, Brendan Mackay, Bill Waite, Stephen Rothwell
and David Bell for helpful suggestions, patches and testing of rsync.
I’ve probably missed some people, my apologies if I have.
Especial thanks also to: David Dykstra, Jos Backus, Sebastian Krahmer,
Martin Pool, Wayne Davison, J.W. Schultz.
rsync was originally written by Andrew Tridgell and Paul Mackerras.
Many people have later contributed to it.
Mailing lists for support and development are available at
http://lists.samba.org
Advertisements
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 10615,
"s": 10577,
"text": "\nrsync [OPTION]... SRC [SRC]... DEST\n"
},
{
"code": null,
"e": 10665,
"s": 10615,
"text": "\nrsync [OPTION]... SRC [SRC]... [USER@]HOST:DEST\n"
},
{
"code": null,
"e": 10716,
"s": 10665,
"text": "\nrsync [OPTION]... SRC [SRC]... [USER@]HOST::DEST\n"
},
{
"code": null,
"e": 10781,
"s": 10716,
"text": "\nrsync [OPTION]... SRC [SRC]... rsync://[USER@]HOST[:PORT]/DEST\n"
},
{
"code": null,
"e": 10805,
"s": 10781,
"text": "\nrsync [OPTION]... SRC\n"
},
{
"code": null,
"e": 10848,
"s": 10805,
"text": "\nrsync [OPTION]... [USER@]HOST:SRC [DEST]\n"
},
{
"code": null,
"e": 10892,
"s": 10848,
"text": "\nrsync [OPTION]... [USER@]HOST::SRC [DEST]\n"
},
{
"code": null,
"e": 10950,
"s": 10892,
"text": "\nrsync [OPTION]... rsync://[USER@]HOST[:PORT]/SRC [DEST]\n"
},
{
"code": null,
"e": 11169,
"s": 10952,
"text": "\nrsync is a program that behaves in much the same way that rcp does,\nbut has many more options and uses the rsync remote-update protocol to\ngreatly speed up file transfers when the destination file is being\nupdated.\n"
},
{
"code": null,
"e": 11417,
"s": 11169,
"text": "\nThe rsync remote-update protocol allows rsync to transfer just the\ndifferences between two sets of files across the network connection, using\nan efficient checksum-search algorithm described in the technical\nreport that accompanies this package.\n"
},
{
"code": null,
"e": 11465,
"s": 11417,
"text": "\nSome of the additional features of rsync are:\n"
},
{
"code": null,
"e": 11614,
"s": 11467,
"text": "\nRsync copies files either to or from a remote host, or locally on the\ncurrent host (it does not support copying files between two remote hosts).\n"
},
{
"code": null,
"e": 12246,
"s": 11614,
"text": "\nThere are two different ways for rsync to contact a remote system: using a\nremote-shell program as the transport (such as ssh or rsh) or contacting an\nrsync daemon directly via TCP. The remote-shell transport is used whenever\nthe source or destination path contains a single colon (:) separator after\na host specification. Contacting an rsync daemon directly happens when the\nsource or destination path contains a double colon (::) separator after a\nhost specification, OR when an rsync:// URL is specified (see also the\n\"USING RSYNC-DAEMON FEATURES VIA A REMOTE-SHELL CONNECTION\" section for\nan exception to this latter rule).\n"
},
{
"code": null,
"e": 12387,
"s": 12246,
"text": "\nAs a special case, if a single source arg is specified without a\ndestination, the files are listed in an output format similar to \"ls -l\".\n"
},
{
"code": null,
"e": 12526,
"s": 12387,
"text": "\nAs expected, if neither the source or destination path specify a remote\nhost, the copy occurs locally (see also the --list-only option).\n"
},
{
"code": null,
"e": 12581,
"s": 12528,
"text": "\nSee the file README for installation instructions.\n"
},
{
"code": null,
"e": 12916,
"s": 12581,
"text": "\nOnce installed, you can use rsync to any machine that you can access via\na remote shell (as well as some that you can access using the rsync\ndaemon-mode protocol). For remote transfers, a modern rsync uses ssh\nfor its communications, but it may have been configured to use a\ndifferent remote shell by default, such as rsh or remsh.\n"
},
{
"code": null,
"e": 13060,
"s": 12916,
"text": "\nYou can also specify any remote shell you like, either by using the -e\ncommand line option, or by setting the RSYNC_RSH environment variable.\n"
},
{
"code": null,
"e": 13141,
"s": 13060,
"text": "\nNote that rsync must be installed on both the source and destination\nmachines.\n"
},
{
"code": null,
"e": 13261,
"s": 13143,
"text": "\nYou use rsync in the same way you use rcp. You must specify a source\nand a destination, one of which may be remote.\n"
},
{
"code": null,
"e": 13329,
"s": 13261,
"text": "\nPerhaps the best way to explain the syntax is with some examples:\n"
},
{
"code": null,
"e": 13353,
"s": 13329,
"text": "\nrsync -t *.c foo:src/\n"
},
{
"code": null,
"e": 13664,
"s": 13353,
"text": "\nThis would transfer all files matching the pattern *.c from the\ncurrent directory to the directory src on the machine foo. If any of\nthe files already exist on the remote system then the rsync\nremote-update protocol is used to update the file by sending only the\ndifferences. See the tech report for details.\n"
},
{
"code": null,
"e": 13699,
"s": 13664,
"text": "\nrsync -avz foo:src/bar /data/tmp\n"
},
{
"code": null,
"e": 14099,
"s": 13699,
"text": "\nThis would recursively transfer all files from the directory src/bar on the\nmachine foo into the /data/tmp/bar directory on the local machine. The\nfiles are transferred in \"archive\" mode, which ensures that symbolic\nlinks, devices, attributes, permissions, ownerships, etc. are preserved\nin the transfer. Additionally, compression will be used to reduce the\nsize of data portions of the transfer.\n"
},
{
"code": null,
"e": 14135,
"s": 14099,
"text": "\nrsync -avz foo:src/bar/ /data/tmp\n"
},
{
"code": null,
"e": 14657,
"s": 14135,
"text": "\nA trailing slash on the source changes this behavior to avoid creating an\nadditional directory level at the destination. You can think of a trailing\n/ on a source as meaning \"copy the contents of this directory\" as opposed\nto \"copy the directory by name\", but in both cases the attributes of the\ncontaining directory are transferred to the containing directory on the\ndestination. In other words, each of the following commands copies the\nfiles in the same way, including their setting of the attributes of\n/dest/foo:\n"
},
{
"code": null,
"e": 14715,
"s": 14657,
"text": "\nrsync -av /src/foo /dest\n\nrsync -av /src/foo/ /dest/foo\n"
},
{
"code": null,
"e": 14916,
"s": 14715,
"text": "\nNote also that host and module references don’t require a trailing slash to\ncopy the contents of the default directory. For example, both of these\ncopy the remote directory’s contents into \"/dest\":\n"
},
{
"code": null,
"e": 14970,
"s": 14916,
"text": "\nrsync -av host: /dest\n\nrsync -av host::module /dest\n"
},
{
"code": null,
"e": 15138,
"s": 14970,
"text": "\nYou can also use rsync in local-only mode, where both the source and\ndestination don’t have a ’:’ in the name. In this case it behaves like\nan improved copy command.\n"
},
{
"code": null,
"e": 15262,
"s": 15138,
"text": "\nFinally, you can list all the (listable) modules available from a\nparticular rsync daemon by leaving off the module name:\n"
},
{
"code": null,
"e": 15294,
"s": 15262,
"text": "\nrsync somehost.mydomain.com::\n"
},
{
"code": null,
"e": 15340,
"s": 15294,
"text": "\nSee the following section for more details.\n"
},
{
"code": null,
"e": 15461,
"s": 15342,
"text": "\nThe syntax for requesting multiple files from a remote host involves using\nquoted spaces in the SRC. Some examples:\n"
},
{
"code": null,
"e": 15521,
"s": 15461,
"text": "\nrsync host::’modname/dir1/file1 modname/dir2/file2’ /dest\n"
},
{
"code": null,
"e": 15768,
"s": 15521,
"text": "\nThis would copy file1 and file2 into /dest from an rsync daemon. Each\nadditional arg must include the same \"modname/\" prefix as the first one,\nand must be preceded by a single space. All other spaces are assumed\nto be a part of the filenames.\n"
},
{
"code": null,
"e": 15815,
"s": 15768,
"text": "\nrsync -av host:’dir1/file1 dir2/file2’ /dest\n"
},
{
"code": null,
"e": 16302,
"s": 15815,
"text": "\nThis would copy file1 and file2 into /dest using a remote shell. This\nword-splitting is done by the remote shell, so if it doesn’t work it means\nthat the remote shell isn’t configured to split its args based on\nwhitespace (a very rare setting, but not unknown). If you need to transfer\na filename that contains whitespace, you’ll need to either escape the\nwhitespace in a way that the remote shell will understand, or use wildcards\nin place of the spaces. Two examples of this are:\n"
},
{
"code": null,
"e": 16396,
"s": 16302,
"text": "\nrsync -av host:’file\\ name\\ with\\ spaces’ /dest\n\nrsync -av host:file?name?with?spaces /dest\n"
},
{
"code": null,
"e": 16537,
"s": 16396,
"text": "\nThis latter example assumes that your shell passes through unmatched\nwildcards. If it complains about \"no match\", put the name in quotes.\n"
},
{
"code": null,
"e": 16886,
"s": 16539,
"text": "\nIt is also possible to use rsync without a remote shell as the transport.\nIn this case you will directly connect to a remote rsync daemon, typically\nusing TCP port 873. (This obviously requires the daemon to be running on\nthe remote system, so refer to the STARTING AN RSYNC DAEMON TO ACCEPT\nCONNECTIONS section below for information on that.)\n"
},
{
"code": null,
"e": 16969,
"s": 16886,
"text": "\nUsing rsync in this way is the same as using it with a remote shell except\nthat:\n"
},
{
"code": null,
"e": 17007,
"s": 16975,
"text": "\n rsync -av host::src /dest\n"
},
{
"code": null,
"e": 17039,
"s": 17007,
"text": "\n rsync -av host::src /dest\n"
},
{
"code": null,
"e": 17362,
"s": 17043,
"text": "\nSome modules on the remote daemon may require authentication. If so,\nyou will receive a password prompt when you connect. You can avoid the\npassword prompt by setting the environment variable RSYNC_PASSWORD to\nthe password you want to use or using the --password-file option. This\nmay be useful when scripting rsync.\n"
},
{
"code": null,
"e": 17492,
"s": 17362,
"text": "\nWARNING: On some systems environment variables are visible to all\nusers. On those systems using --password-file is recommended.\n"
},
{
"code": null,
"e": 17729,
"s": 17492,
"text": "\nYou may establish the connection via a web proxy by setting the\nenvironment variable RSYNC_PROXY to a hostname:port pair pointing to\nyour web proxy. Note that your web proxy’s configuration must support\nproxy connections to port 873.\n"
},
{
"code": null,
"e": 18571,
"s": 17731,
"text": "\nIt is sometimes useful to use various features of an rsync daemon (such as\nnamed modules) without actually allowing any new socket connections into a\nsystem (other than what is already required to allow remote-shell access).\nRsync supports connecting to a host using a remote shell and then spawning\na single-use \"daemon\" server that expects to read its config file in the\nhome dir of the remote user. This can be useful if you want to encrypt a\ndaemon-style transfer’s data, but since the daemon is started up fresh by\nthe remote user, you may not be able to use features such as chroot or\nchange the uid used by the daemon. (For another way to encrypt a daemon\ntransfer, consider using ssh to tunnel a local port to a remote machine and\nconfigure a normal rsync daemon on that remote host to only allow\nconnections from \"localhost\".)\n"
},
{
"code": null,
"e": 18956,
"s": 18571,
"text": "\nFrom the user’s perspective, a daemon transfer via a remote-shell\nconnection uses nearly the same command-line syntax as a normal\nrsync-daemon transfer, with the only exception being that you must\nexplicitly set the remote shell program on the command-line with the\n--rsh=COMMAND option. (Setting the RSYNC_RSH in the environment\nwill not turn on this functionality.) For example:\n"
},
{
"code": null,
"e": 19005,
"s": 18960,
"text": "\n rsync -av --rsh=ssh host::module /dest\n"
},
{
"code": null,
"e": 19050,
"s": 19005,
"text": "\n rsync -av --rsh=ssh host::module /dest\n"
},
{
"code": null,
"e": 19418,
"s": 19054,
"text": "\nIf you need to specify a different remote-shell user, keep in mind that the\nuser@ prefix in front of the host is specifying the rsync-user value (for a\nmodule that requires user-based authentication). This means that you must\ngive the ’-l user’ option to ssh when specifying the remote-shell, as in\nthis example that uses the short version of the --rsh option:\n"
},
{
"code": null,
"e": 19489,
"s": 19422,
"text": "\n rsync -av -e \"ssh -l ssh-user\" rsync-user@host::module /dest\n"
},
{
"code": null,
"e": 19556,
"s": 19489,
"text": "\n rsync -av -e \"ssh -l ssh-user\" rsync-user@host::module /dest\n"
},
{
"code": null,
"e": 19665,
"s": 19560,
"text": "\nThe \"ssh-user\" will be used at the ssh level; the \"rsync-user\" will be\nused to log-in to the \"module\".\n"
},
{
"code": null,
"e": 20170,
"s": 19667,
"text": "\nIn order to connect to an rsync daemon, the remote system needs to have a\ndaemon already running (or it needs to have configured something like inetd\nto spawn an rsync daemon for incoming connections on a particular port).\nFor full information on how to start a daemon that will handling incoming\nsocket connections, see the rsyncd.conf(5) man page -- that is the config\nfile for the daemon, and it contains the full details for how to run the\ndaemon (including stand-alone and inetd configurations).\n"
},
{
"code": null,
"e": 20293,
"s": 20170,
"text": "\nIf you’re using one of the remote-shell transports for the transfer, there is\nno need to manually start an rsync daemon.\n"
},
{
"code": null,
"e": 20340,
"s": 20295,
"text": "\nHere are some examples of how I use rsync.\n"
},
{
"code": null,
"e": 20461,
"s": 20340,
"text": "\nTo backup my wife’s home directory, which consists of large MS Word\nfiles and mail folders, I use a cron job that runs\n"
},
{
"code": null,
"e": 20495,
"s": 20461,
"text": "\nrsync -Cavz . arvidsjaur:backup\n"
},
{
"code": null,
"e": 20583,
"s": 20495,
"text": "\neach night over a PPP connection to a duplicate directory on my machine\n\"arvidsjaur\".\n"
},
{
"code": null,
"e": 20660,
"s": 20583,
"text": "\nTo synchronize my samba source trees I use the following Makefile\ntargets:\n"
},
{
"code": null,
"e": 20798,
"s": 20664,
"text": "\n get:\n rsync -avuzb --exclude ’*~’ samba:samba/ .\n put:\n rsync -Cavuzb . samba:samba/\n sync: get put\n"
},
{
"code": null,
"e": 20932,
"s": 20798,
"text": "\n get:\n rsync -avuzb --exclude ’*~’ samba:samba/ .\n put:\n rsync -Cavuzb . samba:samba/\n sync: get put\n"
},
{
"code": null,
"e": 21141,
"s": 20936,
"text": "\nthis allows me to sync with a CVS directory at the other end of the\nconnection. I then do CVS operations on the remote machine, which saves a\nlot of time as the remote CVS protocol isn’t very efficient.\n"
},
{
"code": null,
"e": 21219,
"s": 21141,
"text": "\nI mirror a directory between my \"old\" and \"new\" ftp sites with the\ncommand:\n"
},
{
"code": null,
"e": 21287,
"s": 21219,
"text": "\nrsync -az -e ssh --delete ~ftp/pub/samba nimbus:\"~ftp/pub/tridge\"\n"
},
{
"code": null,
"e": 21333,
"s": 21287,
"text": "\nThis is launched from cron every few hours.\n"
},
{
"code": null,
"e": 21472,
"s": 21335,
"text": "\nHere is a short summary of the options available in rsync. Please refer\nto the detailed description below for a complete description. \n"
},
{
"code": null,
"e": 28291,
"s": 21472,
"text": "\n\n -v, --verbose increase verbosity\n -q, --quiet suppress non-error messages\n -c, --checksum skip based on checksum, not mod-time & size\n -a, --archive archive mode; same as -rlptgoD (no -H)\n --no-OPTION turn off an implied OPTION (e.g. --no-D)\n -r, --recursive recurse into directories\n -R, --relative use relative path names\n --no-implied-dirs don’t send implied dirs with --relative\n -b, --backup make backups (see --suffix & --backup-dir)\n --backup-dir=DIR make backups into hierarchy based in DIR\n --suffix=SUFFIX backup suffix (default ~ w/o --backup-dir)\n -u, --update skip files that are newer on the receiver\n --inplace update destination files in-place\n --append append data onto shorter files\n -d, --dirs transfer directories without recursing\n -l, --links copy symlinks as symlinks\n -L, --copy-links transform symlink into referent file/dir\n --copy-unsafe-links only \"unsafe\" symlinks are transformed\n --safe-links ignore symlinks that point outside the tree\n -k, --copy-dirlinks transform symlink to dir into referent dir\n -K, --keep-dirlinks treat symlinked dir on receiver as dir\n -H, --hard-links preserve hard links\n -p, --perms preserve permissions\n -E, --executability preserve executability\n -A, --acls preserve ACLs (implies -p) [non-standard]\n -X, --xattrs preserve extended attrs (implies -p) [n.s.]\n --chmod=CHMOD change destination permissions\n -o, --owner preserve owner (super-user only)\n -g, --group preserve group\n --devices preserve device files (super-user only)\n --specials preserve special files\n -D same as --devices --specials\n -t, --times preserve times\n -O, --omit-dir-times omit directories when preserving times\n --super receiver attempts super-user activities\n -S, --sparse handle sparse files efficiently\n -n, --dry-run show what would have been transferred\n -W, --whole-file copy files whole (without rsync algorithm)\n -x, --one-file-system don’t cross filesystem boundaries\n -B, --block-size=SIZE force a fixed checksum block-size\n -e, --rsh=COMMAND specify the remote shell to use\n --rsync-path=PROGRAM specify the rsync to run on remote machine\n --existing ignore non-existing files on receiving side\n --ignore-existing ignore files that already exist on receiver\n --remove-sent-files sent files/symlinks are removed from sender\n --del an alias for --delete-during\n --delete delete files that don’t exist on sender\n --delete-before receiver deletes before transfer (default)\n --delete-during receiver deletes during xfer, not before\n --delete-after receiver deletes after transfer, not before\n --delete-excluded also delete excluded files on receiver\n --ignore-errors delete even if there are I/O errors\n --force force deletion of dirs even if not empty\n --max-delete=NUM don’t delete more than NUM files\n --max-size=SIZE don’t transfer any file larger than SIZE\n --min-size=SIZE don’t transfer any file smaller than SIZE\n --partial keep partially transferred files\n --partial-dir=DIR put a partially transferred file into DIR\n --delay-updates put all updated files into place at end\n -m, --prune-empty-dirs prune empty directory chains from file-list\n --numeric-ids don’t map uid/gid values by user/group name\n --timeout=TIME set I/O timeout in seconds\n -I, --ignore-times don’t skip files that match size and time\n --size-only skip files that match in size\n --modify-window=NUM compare mod-times with reduced accuracy\n -T, --temp-dir=DIR create temporary files in directory DIR\n -y, --fuzzy find similar file for basis if no dest file\n --compare-dest=DIR also compare received files relative to DIR\n --copy-dest=DIR ... and include copies of unchanged files\n --link-dest=DIR hardlink to files in DIR when unchanged\n -z, --compress compress file data during the transfer\n --compress-level=NUM explicitly set compression level\n -C, --cvs-exclude auto-ignore files in the same way CVS does\n -f, --filter=RULE add a file-filtering RULE\n -F same as --filter=’dir-merge /.rsync-filter’\n repeated: --filter=’- .rsync-filter’\n --exclude=PATTERN exclude files matching PATTERN\n --exclude-from=FILE read exclude patterns from FILE\n --include=PATTERN don’t exclude files matching PATTERN\n --include-from=FILE read include patterns from FILE\n --files-from=FILE read list of source-file names from FILE\n -0, --from0 all *from/filter files are delimited by 0s\n --address=ADDRESS bind address for outgoing socket to daemon\n --port=PORT specify double-colon alternate port number\n --sockopts=OPTIONS specify custom TCP options\n --blocking-io use blocking I/O for the remote shell\n --stats give some file-transfer stats\n -8, --8-bit-output leave high-bit chars unescaped in output\n -h, --human-readable output numbers in a human-readable format\n --progress show progress during transfer\n -P same as --partial --progress\n -i, --itemize-changes output a change-summary for all updates\n --log-format=FORMAT output filenames using the specified format\n --password-file=FILE read password from FILE\n --list-only list the files instead of copying them\n --bwlimit=KBPS limit I/O bandwidth; KBytes per second\n --write-batch=FILE write a batched update to FILE\n --only-write-batch=FILE like --write-batch but w/o updating dest\n --read-batch=FILE read a batched update from FILE\n --protocol=NUM force an older protocol version to be used\n --checksum-seed=NUM set block/file checksum seed (advanced)\n -4, --ipv4 prefer IPv4\n -6, --ipv6 prefer IPv6\n --version print version number\n(-h) --help show this help (see below for -h comment)\n\n"
},
{
"code": null,
"e": 35110,
"s": 28293,
"text": "\n -v, --verbose increase verbosity\n -q, --quiet suppress non-error messages\n -c, --checksum skip based on checksum, not mod-time & size\n -a, --archive archive mode; same as -rlptgoD (no -H)\n --no-OPTION turn off an implied OPTION (e.g. --no-D)\n -r, --recursive recurse into directories\n -R, --relative use relative path names\n --no-implied-dirs don’t send implied dirs with --relative\n -b, --backup make backups (see --suffix & --backup-dir)\n --backup-dir=DIR make backups into hierarchy based in DIR\n --suffix=SUFFIX backup suffix (default ~ w/o --backup-dir)\n -u, --update skip files that are newer on the receiver\n --inplace update destination files in-place\n --append append data onto shorter files\n -d, --dirs transfer directories without recursing\n -l, --links copy symlinks as symlinks\n -L, --copy-links transform symlink into referent file/dir\n --copy-unsafe-links only \"unsafe\" symlinks are transformed\n --safe-links ignore symlinks that point outside the tree\n -k, --copy-dirlinks transform symlink to dir into referent dir\n -K, --keep-dirlinks treat symlinked dir on receiver as dir\n -H, --hard-links preserve hard links\n -p, --perms preserve permissions\n -E, --executability preserve executability\n -A, --acls preserve ACLs (implies -p) [non-standard]\n -X, --xattrs preserve extended attrs (implies -p) [n.s.]\n --chmod=CHMOD change destination permissions\n -o, --owner preserve owner (super-user only)\n -g, --group preserve group\n --devices preserve device files (super-user only)\n --specials preserve special files\n -D same as --devices --specials\n -t, --times preserve times\n -O, --omit-dir-times omit directories when preserving times\n --super receiver attempts super-user activities\n -S, --sparse handle sparse files efficiently\n -n, --dry-run show what would have been transferred\n -W, --whole-file copy files whole (without rsync algorithm)\n -x, --one-file-system don’t cross filesystem boundaries\n -B, --block-size=SIZE force a fixed checksum block-size\n -e, --rsh=COMMAND specify the remote shell to use\n --rsync-path=PROGRAM specify the rsync to run on remote machine\n --existing ignore non-existing files on receiving side\n --ignore-existing ignore files that already exist on receiver\n --remove-sent-files sent files/symlinks are removed from sender\n --del an alias for --delete-during\n --delete delete files that don’t exist on sender\n --delete-before receiver deletes before transfer (default)\n --delete-during receiver deletes during xfer, not before\n --delete-after receiver deletes after transfer, not before\n --delete-excluded also delete excluded files on receiver\n --ignore-errors delete even if there are I/O errors\n --force force deletion of dirs even if not empty\n --max-delete=NUM don’t delete more than NUM files\n --max-size=SIZE don’t transfer any file larger than SIZE\n --min-size=SIZE don’t transfer any file smaller than SIZE\n --partial keep partially transferred files\n --partial-dir=DIR put a partially transferred file into DIR\n --delay-updates put all updated files into place at end\n -m, --prune-empty-dirs prune empty directory chains from file-list\n --numeric-ids don’t map uid/gid values by user/group name\n --timeout=TIME set I/O timeout in seconds\n -I, --ignore-times don’t skip files that match size and time\n --size-only skip files that match in size\n --modify-window=NUM compare mod-times with reduced accuracy\n -T, --temp-dir=DIR create temporary files in directory DIR\n -y, --fuzzy find similar file for basis if no dest file\n --compare-dest=DIR also compare received files relative to DIR\n --copy-dest=DIR ... and include copies of unchanged files\n --link-dest=DIR hardlink to files in DIR when unchanged\n -z, --compress compress file data during the transfer\n --compress-level=NUM explicitly set compression level\n -C, --cvs-exclude auto-ignore files in the same way CVS does\n -f, --filter=RULE add a file-filtering RULE\n -F same as --filter=’dir-merge /.rsync-filter’\n repeated: --filter=’- .rsync-filter’\n --exclude=PATTERN exclude files matching PATTERN\n --exclude-from=FILE read exclude patterns from FILE\n --include=PATTERN don’t exclude files matching PATTERN\n --include-from=FILE read include patterns from FILE\n --files-from=FILE read list of source-file names from FILE\n -0, --from0 all *from/filter files are delimited by 0s\n --address=ADDRESS bind address for outgoing socket to daemon\n --port=PORT specify double-colon alternate port number\n --sockopts=OPTIONS specify custom TCP options\n --blocking-io use blocking I/O for the remote shell\n --stats give some file-transfer stats\n -8, --8-bit-output leave high-bit chars unescaped in output\n -h, --human-readable output numbers in a human-readable format\n --progress show progress during transfer\n -P same as --partial --progress\n -i, --itemize-changes output a change-summary for all updates\n --log-format=FORMAT output filenames using the specified format\n --password-file=FILE read password from FILE\n --list-only list the files instead of copying them\n --bwlimit=KBPS limit I/O bandwidth; KBytes per second\n --write-batch=FILE write a batched update to FILE\n --only-write-batch=FILE like --write-batch but w/o updating dest\n --read-batch=FILE read a batched update from FILE\n --protocol=NUM force an older protocol version to be used\n --checksum-seed=NUM set block/file checksum seed (advanced)\n -4, --ipv4 prefer IPv4\n -6, --ipv6 prefer IPv6\n --version print version number\n(-h) --help show this help (see below for -h comment)\n"
},
{
"code": null,
"e": 35203,
"s": 35116,
"text": "\nRsync can also be run as a daemon, in which case the following options are\naccepted:\n"
},
{
"code": null,
"e": 35825,
"s": 35203,
"text": "\n\n --daemon run as an rsync daemon\n --address=ADDRESS bind to the specified address\n --bwlimit=KBPS limit I/O bandwidth; KBytes per second\n --config=FILE specify alternate rsyncd.conf file\n --no-detach do not detach from the parent\n --port=PORT listen on alternate port number\n --sockopts=OPTIONS specify custom TCP options\n -v, --verbose increase verbosity\n -4, --ipv4 prefer IPv4\n -6, --ipv6 prefer IPv6\n -h, --help show this help (if used after --daemon)\n\n"
},
{
"code": null,
"e": 36447,
"s": 35827,
"text": "\n --daemon run as an rsync daemon\n --address=ADDRESS bind to the specified address\n --bwlimit=KBPS limit I/O bandwidth; KBytes per second\n --config=FILE specify alternate rsyncd.conf file\n --no-detach do not detach from the parent\n --port=PORT listen on alternate port number\n --sockopts=OPTIONS specify custom TCP options\n -v, --verbose increase verbosity\n -4, --ipv4 prefer IPv4\n -6, --ipv6 prefer IPv6\n -h, --help show this help (if used after --daemon)\n"
},
{
"code": null,
"e": 36745,
"s": 36455,
"text": "\nrsync uses the GNU long options package. Many of the command line\noptions have two variants, one short and one long. These are shown\nbelow, separated by commas. Some options only have a long variant.\nThe ’=’ for options that take a parameter is optional; whitespace\ncan be used instead.\n"
},
{
"code": null,
"e": 36792,
"s": 36749,
"text": "\n 782448 63% 110.64kB/s 0:00:04\n"
},
{
"code": null,
"e": 36835,
"s": 36792,
"text": "\n 782448 63% 110.64kB/s 0:00:04\n"
},
{
"code": null,
"e": 36903,
"s": 36841,
"text": "\n 1238099 100% 146.38kB/s 0:00:08 (5, 57.1% of 396)\n"
},
{
"code": null,
"e": 36965,
"s": 36903,
"text": "\n 1238099 100% 146.38kB/s 0:00:08 (5, 57.1% of 396)\n"
},
{
"code": null,
"e": 37010,
"s": 36971,
"text": "\n rsync -av --list-only foo* dest/\n"
},
{
"code": null,
"e": 37049,
"s": 37010,
"text": "\n rsync -av --list-only foo* dest/\n"
},
{
"code": null,
"e": 37121,
"s": 37053,
"text": "\nThe options allowed when starting an rsync daemon are as follows:\n"
},
{
"code": null,
"e": 37399,
"s": 37123,
"text": "\nThe filter rules allow for flexible selection of which files to transfer\n(include) and which files to skip (exclude). The rules either directly\nspecify include/exclude patterns or they specify a way to acquire more\ninclude/exclude patterns (e.g. to read them from a file).\n"
},
{
"code": null,
"e": 37782,
"s": 37399,
"text": "\nAs the list of files/directories to transfer is built, rsync checks each\nname to be transferred against the list of include/exclude patterns in\nturn, and the first matching pattern is acted on: if it is an exclude\npattern, then that file is skipped; if it is an include pattern then that\nfilename is not skipped; if no matching pattern is found, then the\nfilename is not skipped.\n"
},
{
"code": null,
"e": 37904,
"s": 37782,
"text": "\nRsync builds an ordered list of filter rules as specified on the\ncommand-line. Filter rules have the following syntax:\n"
},
{
"code": null,
"e": 37971,
"s": 37904,
"text": "\nRULE [PATTERN_OR_FILENAME]\n\nRULE,MODIFIERS [PATTERN_OR_FILENAME]\n"
},
{
"code": null,
"e": 38299,
"s": 37971,
"text": "\nYou have your choice of using either short or long RULE names, as described\nbelow. If you use a short-named rule, the ’,’ separating the RULE from the\nMODIFIERS is optional. The PATTERN or FILENAME that follows (when present)\nmust come after either a single space or an underscore (_).\nHere are the available rule prefixes:\n"
},
{
"code": null,
"e": 38802,
"s": 38299,
"text": "\nexclude, - specifies an exclude pattern.\n\ninclude, + specifies an include pattern.\n\nmerge, . specifies a merge-file to read for more rules.\n\ndir-merge, : specifies a per-directory merge-file.\n\nhide, H specifies a pattern for hiding files from the transfer.\n\nshow, S files that match the pattern are not hidden.\n\nprotect, P specifies a pattern for protecting files from deletion.\n\nrisk, R files that match the pattern are not protected.\n\nclear, ! clears the current include/exclude list (takes no arg)\n"
},
{
"code": null,
"e": 38912,
"s": 38802,
"text": "\nWhen rules are being read from a file, empty lines are ignored, as are\ncomment lines that start with a \"#\".\n"
},
{
"code": null,
"e": 39521,
"s": 38912,
"text": "\nNote that the --include/--exclude command-line options do not allow the\nfull range of rule parsing as described above -- they only allow the\nspecification of include/exclude patterns plus a \"!\" token to clear the\nlist (and the normal comment parsing when rules are read from a file).\nIf a pattern\ndoes not begin with \"- \" (dash, space) or \"+ \" (plus, space), then the\nrule will be interpreted as if \"+ \" (for an include option) or \"- \" (for\nan exclude option) were prefixed to the string. A --filter option, on\nthe other hand, must always contain either a short or long rule name at the\nstart of the rule.\n"
},
{
"code": null,
"e": 39779,
"s": 39521,
"text": "\nNote also that the --filter, --include, and --exclude options take one\nrule/pattern each. To add multiple ones, you can repeat the options on\nthe command-line, use the merge-file syntax of the --filter option, or\nthe --include-from/--exclude-from options.\n"
},
{
"code": null,
"e": 40099,
"s": 39781,
"text": "\nYou can include and exclude files by specifying patterns using the \"+\",\n\"-\", etc. filter rules (as introduced in the FILTER RULES section above).\nThe include/exclude rules each specify a pattern that is matched against\nthe names of the files that are going to be transferred. These patterns\ncan take several forms:\n"
},
{
"code": null,
"e": 40271,
"s": 40105,
"text": "\nYou can merge whole files into your filter rules by specifying either a\nmerge (.) or a dir-merge (:) filter rule (as introduced in the FILTER RULES\nsection above).\n"
},
{
"code": null,
"e": 41005,
"s": 40271,
"text": "\nThere are two kinds of merged files -- single-instance (’.’) and\nper-directory (’:’). A single-instance merge file is read one time, and\nits rules are incorporated into the filter list in the place of the \".\"\nrule. For per-directory merge files, rsync will scan every directory that\nit traverses for the named file, merging its contents when the file exists\ninto the current list of inherited rules. These per-directory rule files\nmust be created on the sending side because it is the sending side that is\nbeing scanned for the available files to transfer. These rule files may\nalso need to be transferred to the receiving side if you want them to\naffect what files don’t get deleted (see PER-DIRECTORY RULES AND DELETE\nbelow).\n"
},
{
"code": null,
"e": 41022,
"s": 41005,
"text": "\nSome examples:\n"
},
{
"code": null,
"e": 41193,
"s": 41022,
"text": "\nmerge /etc/rsync/default.rules\n\n. /etc/rsync/default.rules\n\ndir-merge .per-dir-filter\n\ndir-merge,n- .non-inherited-per-dir-excludes\n\n:n- .non-inherited-per-dir-excludes\n"
},
{
"code": null,
"e": 41265,
"s": 41193,
"text": "\nThe following modifiers are accepted after a merge or dir-merge rule:\n"
},
{
"code": null,
"e": 41664,
"s": 41277,
"text": "\nYou can clear the current include/exclude list by using the \"!\" filter\nrule (as introduced in the FILTER RULES section above). The \"current\"\nlist is either the global list of rules (if the rule is encountered while\nparsing the filter options) or a set of per-directory rules (which are\ninherited in their own sub-list, so a subdirectory can use this to clear\nout the parent’s rules).\n"
},
{
"code": null,
"e": 42103,
"s": 41666,
"text": "\nAs mentioned earlier, global include/exclude patterns are anchored at the\n\"root of the transfer\" (as opposed to per-directory patterns, which are\nanchored at the merge-file’s directory). If you think of the transfer as\na subtree of names that are being sent from sender to receiver, the\ntransfer-root is where the tree starts to be duplicated in the destination\ndirectory. This root governs where patterns that start with a / match.\n"
},
{
"code": null,
"e": 42434,
"s": 42103,
"text": "\nBecause the matching is relative to the transfer-root, changing the\ntrailing slash on a source path or changing your use of the --relative\noption affects the path you need to use in your matching (in addition to\nchanging how much of the file tree is duplicated on the destination\nhost). The following examples demonstrate this.\n"
},
{
"code": null,
"e": 42651,
"s": 42434,
"text": "\nLet’s say that we want to match two source files, one with an absolute\npath of \"/home/me/foo/bar\", and one with a path of \"/home/you/bar/baz\".\nHere is how the various command choices differ for a 2-source transfer:\n"
},
{
"code": null,
"e": 42816,
"s": 42651,
"text": "\nExample cmd: rsync -a /home/me /home/you /dest\n\n+/- pattern: /me/foo/bar\n\n+/- pattern: /you/bar/baz\n\nTarget file: /dest/me/foo/bar\n\nTarget file: /dest/you/bar/baz\n"
},
{
"code": null,
"e": 43038,
"s": 42816,
"text": "\nExample cmd: rsync -a /home/me/ /home/you/ /dest\n\n+/- pattern: /foo/bar (note missing \"me\")\n\n+/- pattern: /bar/baz (note missing \"you\")\n\nTarget file: /dest/foo/bar\n\nTarget file: /dest/bar/baz\n"
},
{
"code": null,
"e": 43271,
"s": 43038,
"text": "\nExample cmd: rsync -a --relative /home/me/ /home/you /dest\n\n+/- pattern: /home/me/foo/bar (note full path)\n\n+/- pattern: /home/you/bar/baz (ditto)\n\nTarget file: /dest/home/me/foo/bar\n\nTarget file: /dest/home/you/bar/baz\n"
},
{
"code": null,
"e": 43494,
"s": 43271,
"text": "\nExample cmd: cd /home; rsync -a --relative me/foo you/ /dest\n\n+/- pattern: /me/foo/bar (starts at specified path)\n\n+/- pattern: /you/bar/baz (ditto)\n\nTarget file: /dest/me/foo/bar\n\nTarget file: /dest/you/bar/baz\n"
},
{
"code": null,
"e": 43701,
"s": 43494,
"text": "\nThe easiest way to see what name you should filter is to just\nlook at the output when using --verbose and put a / in front of the name\n(use the --dry-run option if you’re not yet ready to copy any files).\n"
},
{
"code": null,
"e": 43986,
"s": 43703,
"text": "\nWithout a delete option, per-directory rules are only relevant on the\nsending side, so you can feel free to exclude the merge files themselves\nwithout affecting the transfer. To make this easy, the ’e’ modifier adds\nthis exclude for you, as seen in these two equivalent commands:\n"
},
{
"code": null,
"e": 44102,
"s": 43986,
"text": "\nrsync -av --filter=’: .excl’ --exclude=.excl host:src/dir /dest\n\nrsync -av --filter=’:e .excl’ host:src/dir /dest\n"
},
{
"code": null,
"e": 44531,
"s": 44102,
"text": "\nHowever, if you want to do a delete on the receiving side AND you want some\nfiles to be excluded from being deleted, you’ll need to be sure that the\nreceiving side knows what files to exclude. The easiest way is to include\nthe per-directory merge files in the transfer and use --delete-after,\nbecause this ensures that the receiving side gets all the same exclude\nrules as the sending side before it tries to delete anything:\n"
},
{
"code": null,
"e": 44578,
"s": 44531,
"text": "\nrsync -avF --delete-after host:src/dir /dest\n"
},
{
"code": null,
"e": 44910,
"s": 44578,
"text": "\nHowever, if the merge files are not a part of the transfer, you’ll need to\neither specify some global exclude rules (i.e. specified on the command\nline), or you’ll need to maintain your own per-directory merge files on\nthe receiving side. An example of the first is this (assume that the\nremote .rules files exclude themselves):\n"
},
{
"code": null,
"e": 45006,
"s": 44914,
"text": "\nrsync -av --filter=’: .rules’ --filter=’. /my/extra.rules’\n --delete host:src/dir /dest\n"
},
{
"code": null,
"e": 45098,
"s": 45006,
"text": "\nrsync -av --filter=’: .rules’ --filter=’. /my/extra.rules’\n --delete host:src/dir /dest\n"
},
{
"code": null,
"e": 45343,
"s": 45102,
"text": "\nIn the above example the extra.rules file can affect both sides of the\ntransfer, but (on the sending side) the rules are subservient to the rules\nmerged from the .rules files because they were specified after the\nper-directory merge rule.\n"
},
{
"code": null,
"e": 45756,
"s": 45343,
"text": "\nIn one final example, the remote side is excluding the .rsync-filter\nfiles from the transfer, but we want to use our own .rsync-filter files\nto control what gets deleted on the receiving side. To do this we must\nspecifically exclude the per-directory merge files (so that they don’t get\ndeleted) and then put rules into the local files to control what else\nshould not get deleted. Like one of these commands:\n"
},
{
"code": null,
"e": 45887,
"s": 45760,
"text": "\n rsync -av --filter=’:e /.rsync-filter’ --delete \\\n host:src/dir /dest\n rsync -avFF --delete host:src/dir /dest\n"
},
{
"code": null,
"e": 46014,
"s": 45887,
"text": "\n rsync -av --filter=’:e /.rsync-filter’ --delete \\\n host:src/dir /dest\n rsync -avFF --delete host:src/dir /dest\n"
},
{
"code": null,
"e": 46619,
"s": 46020,
"text": "\nBatch mode can be used to apply the same set of updates to many\nidentical systems. Suppose one has a tree which is replicated on a\nnumber of hosts. Now suppose some changes have been made to this\nsource tree and those changes need to be propagated to the other\nhosts. In order to do this using batch mode, rsync is run with the\nwrite-batch option to apply the changes made to the source tree to one\nof the destination trees. The write-batch option causes the rsync\nclient to store in a \"batch file\" all the information needed to repeat\nthis operation against other, identical destination trees.\n"
},
{
"code": null,
"e": 46872,
"s": 46619,
"text": "\nTo apply the recorded changes to another destination tree, run rsync\nwith the read-batch option, specifying the name of the same batch\nfile, and the destination tree. Rsync updates the destination tree\nusing the information stored in the batch file.\n"
},
{
"code": null,
"e": 47396,
"s": 46872,
"text": "\nFor convenience, one additional file is creating when the write-batch\noption is used. This file’s name is created by appending\n\".sh\" to the batch filename. The .sh file contains\na command-line suitable for updating a destination tree using that\nbatch file. It can be executed using a Bourne (or Bourne-like) shell,\noptionally\npassing in an alternate destination tree pathname which is then used\ninstead of the original path. This is useful when the destination tree\npath differs from the original destination tree path.\n"
},
{
"code": null,
"e": 47736,
"s": 47396,
"text": "\nGenerating the batch file once saves having to perform the file\nstatus, checksum, and data block generation more than once when\nupdating multiple destination trees. Multicast transport protocols can\nbe used to transfer the batch update files in parallel to many hosts\nat once, instead of sending the same data to every host individually.\n"
},
{
"code": null,
"e": 47748,
"s": 47736,
"text": "\nExamples:\n"
},
{
"code": null,
"e": 47864,
"s": 47748,
"text": "\n$ rsync --write-batch=foo -a host:/source/dir/ /adest/dir/\n\n$ scp foo* remote:\n\n$ ssh remote ./foo.sh /bdest/dir/\n"
},
{
"code": null,
"e": 47975,
"s": 47864,
"text": "\n$ rsync --write-batch=foo -a /source/dir/ /adest/dir/\n\n$ ssh remote rsync --read-batch=- -a /bdest/dir/ <foo\n"
},
{
"code": null,
"e": 48335,
"s": 47975,
"text": "\nIn these examples, rsync is used to update /adest/dir/ from /source/dir/\nand the information to repeat this operation is stored in \"foo\" and\n\"foo.sh\". The host \"remote\" is then updated with the batched data going\ninto the directory /bdest/dir. The differences between the two examples\nreveals some of the flexibility you have in how you deal with batches:\n"
},
{
"code": null,
"e": 49212,
"s": 48337,
"text": "\nThe read-batch option expects the destination tree that it is updating\nto be identical to the destination tree that was used to create the\nbatch update fileset. When a difference between the destination trees\nis encountered the update might be discarded with a warning (if the file\nappears to be up-to-date already) or the file-update may be attempted\nand then, if the file fails to verify, the update discarded with an\nerror. This means that it should be safe to re-run a read-batch operation\nif the command got interrupted. If you wish to force the batched-update to\nalways be attempted regardless of the file’s size and date, use the -I\noption (when reading the batch).\nIf an error occurs, the destination tree will probably be in a\npartially updated state. In that case, rsync can\nbe used in its regular (non-batch) mode of operation to fix up the\ndestination tree.\n"
},
{
"code": null,
"e": 49701,
"s": 49212,
"text": "\nThe rsync version used on all destinations must be at least as new as the\none used to generate the batch file. Rsync will die with an error if the\nprotocol version in the batch file is too new for the batch-reading rsync\nto handle. See also the --protocol option for a way to have the\ncreating rsync generate a batch file that an older rsync can understand.\n(Note that batch files changed format in version 2.6.3, so mixing versions\nolder than that with newer versions will not work.)\n"
},
{
"code": null,
"e": 50107,
"s": 49701,
"text": "\nWhen reading a batch file, rsync will force the value of certain options\nto match the data in the batch file if you didn’t set them to the same\nas the batch-writing command. Other options can (and should) be changed.\nFor instance --write-batch changes to --read-batch,\n--files-from is dropped, and the\n--filter/--include/--exclude options are not needed unless\none of the --delete options is specified.\n"
},
{
"code": null,
"e": 50542,
"s": 50107,
"text": "\nThe code that creates the BATCH.sh file transforms any filter/include/exclude\noptions into a single list that is appended as a \"here\" document to the\nshell script file. An advanced user can use this to modify the exclude\nlist if a change in what gets deleted by --delete is desired. A normal\nuser can ignore this detail and just use the shell script as an easy way\nto run the appropriate --read-batch command for the batched data.\n"
},
{
"code": null,
"e": 50650,
"s": 50542,
"text": "\nThe original batch mode in rsync was based on \"rsync+\", but the latest\nversion uses a new implementation.\n"
},
{
"code": null,
"e": 50752,
"s": 50652,
"text": "\nThree basic behaviors are possible when rsync encounters a symbolic\nlink in the source directory.\n"
},
{
"code": null,
"e": 50888,
"s": 50752,
"text": "\nBy default, symbolic links are not transferred at all. A message\n\"skipping non-regular\" file is emitted for any symlinks that exist.\n"
},
{
"code": null,
"e": 51022,
"s": 50888,
"text": "\nIf --links is specified, then symlinks are recreated with the same\ntarget on the destination. Note that --archive implies\n--links.\n"
},
{
"code": null,
"e": 51136,
"s": 51022,
"text": "\nIf --copy-links is specified, then symlinks are \"collapsed\" by\ncopying their referent, rather than the symlink.\n"
},
{
"code": null,
"e": 51637,
"s": 51136,
"text": "\nrsync also distinguishes \"safe\" and \"unsafe\" symbolic links. An\nexample where this might be used is a web site mirror that wishes\nensure the rsync module they copy does not include symbolic links to\n/etc/passwd in the public section of the site. Using\n--copy-unsafe-links will cause any links to be copied as the file\nthey point to on the destination. Using --safe-links will cause\nunsafe links to be omitted altogether. (Note that you must specify\n--links for --safe-links to have any effect.)\n"
},
{
"code": null,
"e": 51814,
"s": 51637,
"text": "\nSymbolic links are considered unsafe if they are absolute symlinks\n(start with /), empty, or if they contain enough \"..\"\ncomponents to ascend from the directory being copied.\n"
},
{
"code": null,
"e": 52027,
"s": 51814,
"text": "\nHere’s a summary of how the symlink options are interpreted. The list is\nin order of precedence, so if your combination of options isn’t mentioned,\nuse the first line that is a complete subset of your options:\n"
},
{
"code": null,
"e": 52209,
"s": 52029,
"text": "\nrsync occasionally produces error messages that may seem a little\ncryptic. The one that seems to cause the most confusion is \"protocol\nversion mismatch -- is your shell clean?\".\n"
},
{
"code": null,
"e": 52443,
"s": 52209,
"text": "\nThis message is usually caused by your startup scripts or remote shell\nfacility producing unwanted garbage on the stream that rsync is using\nfor its transport. The way to diagnose this problem is to run your\nremote shell like this:\n"
},
{
"code": null,
"e": 52480,
"s": 52443,
"text": "\nssh remotehost /bin/true > out.dat\n"
},
{
"code": null,
"e": 52918,
"s": 52480,
"text": "\nthen look at out.dat. If everything is working correctly then out.dat\nshould be a zero length file. If you are getting the above error from\nrsync then you will probably find that out.dat contains some text or\ndata. Look at the contents and try to work out what is producing\nit. The most common cause is incorrectly configured shell startup\nscripts (such as .cshrc or .profile) that contain output statements\nfor non-interactive logins.\n"
},
{
"code": null,
"e": 53103,
"s": 52918,
"text": "\nIf you are having trouble debugging filter patterns, then\ntry specifying the -vv option. At this level of verbosity rsync will\nshow why each individual file is included or excluded.\n"
},
{
"code": null,
"e": 53143,
"s": 53109,
"text": "\n/etc/rsyncd.conf or rsyncd.conf\n"
},
{
"code": null,
"e": 53193,
"s": 53147,
"text": "\ntimes are transferred as *nix time_t values\n"
},
{
"code": null,
"e": 53316,
"s": 53193,
"text": "\nWhen transferring to FAT filesystems rsync may re-sync\nunmodified files.\nSee the comments on the --modify-window option.\n"
},
{
"code": null,
"e": 53393,
"s": 53316,
"text": "\nfile permissions, devices, etc. are transferred as native numerical\nvalues\n"
},
{
"code": null,
"e": 53440,
"s": 53393,
"text": "\nsee also the comments on the --delete option\n"
},
{
"code": null,
"e": 53505,
"s": 53440,
"text": "\nPlease report bugs! See the website at\nhttp://rsync.samba.org/\n"
},
{
"code": null,
"e": 53562,
"s": 53507,
"text": "\nThis man page is current for version 2.6.8 of rsync.\n"
},
{
"code": null,
"e": 53652,
"s": 53564,
"text": "\nrsync is distributed under the GNU public license. See the file\nCOPYING for details.\n"
},
{
"code": null,
"e": 53798,
"s": 53652,
"text": "\nA WEB site is available at\nhttp://rsync.samba.org/. The site\nincludes an FAQ-O-Matic which may cover questions unanswered by this\nmanual page.\n"
},
{
"code": null,
"e": 53867,
"s": 53798,
"text": "\nThe primary ftp site for rsync is\nftp://rsync.samba.org/pub/rsync.\n"
},
{
"code": null,
"e": 53934,
"s": 53867,
"text": "\nWe would be delighted to hear from you if you like this program.\n"
},
{
"code": null,
"e": 54037,
"s": 53934,
"text": "\nThis program uses the excellent zlib compression library written by\nJean-loup Gailly and Mark Adler.\n"
},
{
"code": null,
"e": 54239,
"s": 54039,
"text": "\nThanks to Richard Brent, Brendan Mackay, Bill Waite, Stephen Rothwell\nand David Bell for helpful suggestions, patches and testing of rsync.\nI’ve probably missed some people, my apologies if I have.\n"
},
{
"code": null,
"e": 54354,
"s": 54239,
"text": "\nEspecial thanks also to: David Dykstra, Jos Backus, Sebastian Krahmer,\nMartin Pool, Wayne Davison, J.W. Schultz.\n"
},
{
"code": null,
"e": 54468,
"s": 54356,
"text": "\nrsync was originally written by Andrew Tridgell and Paul Mackerras.\nMany people have later contributed to it.\n"
},
{
"code": null,
"e": 54561,
"s": 54468,
"text": "\nMailing lists for support and development are available at\nhttp://lists.samba.org\n\n\n\n\n\n\n\n\n\n"
},
{
"code": null,
"e": 54578,
"s": 54561,
"text": "\nAdvertisements\n"
},
{
"code": null,
"e": 54613,
"s": 54578,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 54641,
"s": 54613,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 54675,
"s": 54641,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 54692,
"s": 54675,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 54725,
"s": 54692,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 54736,
"s": 54725,
"text": " Pradeep D"
},
{
"code": null,
"e": 54771,
"s": 54736,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 54787,
"s": 54771,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 54820,
"s": 54787,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 54832,
"s": 54820,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 54864,
"s": 54832,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 54872,
"s": 54864,
"text": " Uplatz"
},
{
"code": null,
"e": 54879,
"s": 54872,
"text": " Print"
},
{
"code": null,
"e": 54890,
"s": 54879,
"text": " Add Notes"
}
] |
Keep Calm and Stack Up— Implement Stacking Regression in Python using mlxtend | by Dehao Zhang | Towards Data Science
|
If you have ever combined multiple ML models to boost your score up on the leaderboard on some Kaggle competition, you know what this is about. In fact, many winning solutions of these Kaggle competitions use ensemble models instead of just a single fine-tuned model.
The intuition behind ensemble models is quite simple: combining different ML algorithms effectively can reduce the risk of an unfortunate selection of one poor model.
In this post, I will discuss Stacking, a popular ensemble method and how to implement a simple 2-layer stacking regression model in Python using the mlxtend library. The sample task that I have chosen is Airbnb pricing prediction.
What is stacking and how does it work?How does stacking model perform compared with the base models?What are the caveats of stacking?What can we do next?
What is stacking and how does it work?
How does stacking model perform compared with the base models?
What are the caveats of stacking?
What can we do next?
Stacking, or Stacked Generalization, is a meta-learning algorithm that learns how to combine the predictions of each base algorithm in the best way [1].
In simple terms, here is how you build a 2-layer stacking model. The first layer, and some people refer to this as the base layer, includes the base models. In the context of classification, you can think of the base models as any classifier that you can use to make prediction as Neural Network, SVM, Decision Tree, etc. Similar logic also applies to regression. After we train these models using the training set, the second layer builds the meta-model by taking the predictions from those models and the expected outputs on the out-of-sample data. You can think of the simplest case of this meta-model is to average out the predictions from base models.
A common approach to avoid over-fitting is to perform cross-validation on these base models, and then use the out-of-fold predictions and the outputs to build the meta-model.
Check out David Wolphet’s paper for more technical details on how stacking works.
I have chosen the Airbnb pricing prediction task from Kaggle (link) to be the example here because it is a relatively simple dataset with small sample size and set of features. The task is to predict the apartment rental listing price on Airbnb based on information such as number of bedrooms, type of rental (whole apartment or private room or shared room), etc.
To see the full Python code, check out my Kaggle kernel.
Without further ado, let’s get to the details!
For the purpose of this post, I won’t discuss the preprocessing steps, but please refer to the Kaggle kernel for full detail.
On a high level, I examined the distribution of each feature, removed outliers, create dummy variables for the categorical ‘room_type’ (since there are only three categories), and standardize the features.
Train/Test Split
I set 70% of the dataset to be training set and the remaining 30% would be used as test set.
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)
Base Models
Let’s first build some base models. Here I have chosen Xgboost, Lasso Regression, and KNN as the three base models. In principle, stacking works best when the models are in a diverse range and their prediction errors are as uncorrelated as possible, so that individual model’s weaknesses and biases are offset by the strengths of others[2].
Performance Metric
In terms of performance metric to evaluate models, I choose to use Mean Absolute Error (MAE), which measures how far the predicted values are away from the measured values.
Performance of the Base Models
Let’s quickly examine the performance of the three base models (all default hyperparameters):
Model: XGBRegressor, MAE: 35.80629559761084Model: Lasso, MAE: 35.0691542225316Model: KNeighborsRegressor, MAE: 38.35917874396135
The MAEs are between 35–38, meaning the predicted prices are about $35-$38 away from the true prices on average.
Build a Stacking Model Using mlxtend
Now, we can build on top of the base models for the meta-learner. Alternatively, we can do a shortcut using ‘StackingCVRegressor’ from the mlxtend library (documentation):
from mlxtend.regressor import StackingCVRegressorstack = StackingCVRegressor(regressors=(XGBRegressor(), Lasso(), KNeighborsRegressor()), meta_regressor=Lasso(), cv=10, use_features_in_secondary=True, store_train_meta_features=True, shuffle=False, random_state=1)
The same three based models are used, and for the meta-learner, I chose to use Lasso. We could also try other regression models as meta-learners, and then build another meta-learner on top (3-layer stacking!) Note that in this configuration, I choose to also use the raw training data as inputs to the meta-model, since it can provide more context to the meta-model.
Now let’s fit our training data into the model and check the performance on the test set:
stack.fit(X_train, y_train)X_test.columns = ['f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10', 'f11'] # Xgboost internally renames the featurespred = stack.predict(X_test)score = mean_absolute_error(y_test, pred)print('Model: {0}, MAE: {1}'.format(type(stack).__name__, score))--------------------------------------------------------------------Model: StackingCVRegressor, MAE: 34.01755981865483
We see that the new MAE is about 34, decreased by 1 compared with the result from the best base model, Lasso.
Although the difference might seem trivial, small gains like this can actually make a huge difference on the leaderboard ranking.
If you want to look into ensemble neural networks, check out this paper.
Despite the capabilities of stacking, here are a few caveats to keep in mind:
Effective use of stacking requires a bit of trials and errors sometimes, and there is no guarantee that stacking would result in an improved performance in all cases.Stacking can be computationally expensive, especially when the number of stacking layer is high.The interpretability of the model decreases as the number of stacking layer increases. This is not a big problem for Kaggle competition but for business cases, understanding the importance of features and its incremental impact on the outcome variable might be more important.
Effective use of stacking requires a bit of trials and errors sometimes, and there is no guarantee that stacking would result in an improved performance in all cases.
Stacking can be computationally expensive, especially when the number of stacking layer is high.
The interpretability of the model decreases as the number of stacking layer increases. This is not a big problem for Kaggle competition but for business cases, understanding the importance of features and its incremental impact on the outcome variable might be more important.
Here are a few things that we can try as next steps:
Hyperparameter tuning — There are a few hyperparameters that we can tune in the selected models to further optimize the performance. ‘GridSearchCV’ can be a helpful tool in this process.Keep stacking — Try to build additional stacking layer(s) and make a plot of the performance metric vs the number of layers to examine if diminishing marginal return holds true (It should!).
Hyperparameter tuning — There are a few hyperparameters that we can tune in the selected models to further optimize the performance. ‘GridSearchCV’ can be a helpful tool in this process.
Keep stacking — Try to build additional stacking layer(s) and make a plot of the performance metric vs the number of layers to examine if diminishing marginal return holds true (It should!).
Let’s quickly recap.
We implemented a simple 2-layer stacking regression model in Python using the mlxtend library, compared its test MAE with the ones of three base models and observed an improvement.
I hope you enjoyed this blog post and please share any thoughts that you may have :)
Check out my other post on dimensionality reduction using t-SNE:
towardsdatascience.com
[1] https://machinelearningmastery.com/stacking-ensemble-machine-learning-with-python/[2] http://support.sas.com/resources/papers/proceedings17/SAS0437-2017.pdf
|
[
{
"code": null,
"e": 314,
"s": 46,
"text": "If you have ever combined multiple ML models to boost your score up on the leaderboard on some Kaggle competition, you know what this is about. In fact, many winning solutions of these Kaggle competitions use ensemble models instead of just a single fine-tuned model."
},
{
"code": null,
"e": 481,
"s": 314,
"text": "The intuition behind ensemble models is quite simple: combining different ML algorithms effectively can reduce the risk of an unfortunate selection of one poor model."
},
{
"code": null,
"e": 712,
"s": 481,
"text": "In this post, I will discuss Stacking, a popular ensemble method and how to implement a simple 2-layer stacking regression model in Python using the mlxtend library. The sample task that I have chosen is Airbnb pricing prediction."
},
{
"code": null,
"e": 866,
"s": 712,
"text": "What is stacking and how does it work?How does stacking model perform compared with the base models?What are the caveats of stacking?What can we do next?"
},
{
"code": null,
"e": 905,
"s": 866,
"text": "What is stacking and how does it work?"
},
{
"code": null,
"e": 968,
"s": 905,
"text": "How does stacking model perform compared with the base models?"
},
{
"code": null,
"e": 1002,
"s": 968,
"text": "What are the caveats of stacking?"
},
{
"code": null,
"e": 1023,
"s": 1002,
"text": "What can we do next?"
},
{
"code": null,
"e": 1176,
"s": 1023,
"text": "Stacking, or Stacked Generalization, is a meta-learning algorithm that learns how to combine the predictions of each base algorithm in the best way [1]."
},
{
"code": null,
"e": 1833,
"s": 1176,
"text": "In simple terms, here is how you build a 2-layer stacking model. The first layer, and some people refer to this as the base layer, includes the base models. In the context of classification, you can think of the base models as any classifier that you can use to make prediction as Neural Network, SVM, Decision Tree, etc. Similar logic also applies to regression. After we train these models using the training set, the second layer builds the meta-model by taking the predictions from those models and the expected outputs on the out-of-sample data. You can think of the simplest case of this meta-model is to average out the predictions from base models."
},
{
"code": null,
"e": 2008,
"s": 1833,
"text": "A common approach to avoid over-fitting is to perform cross-validation on these base models, and then use the out-of-fold predictions and the outputs to build the meta-model."
},
{
"code": null,
"e": 2090,
"s": 2008,
"text": "Check out David Wolphet’s paper for more technical details on how stacking works."
},
{
"code": null,
"e": 2454,
"s": 2090,
"text": "I have chosen the Airbnb pricing prediction task from Kaggle (link) to be the example here because it is a relatively simple dataset with small sample size and set of features. The task is to predict the apartment rental listing price on Airbnb based on information such as number of bedrooms, type of rental (whole apartment or private room or shared room), etc."
},
{
"code": null,
"e": 2511,
"s": 2454,
"text": "To see the full Python code, check out my Kaggle kernel."
},
{
"code": null,
"e": 2558,
"s": 2511,
"text": "Without further ado, let’s get to the details!"
},
{
"code": null,
"e": 2684,
"s": 2558,
"text": "For the purpose of this post, I won’t discuss the preprocessing steps, but please refer to the Kaggle kernel for full detail."
},
{
"code": null,
"e": 2890,
"s": 2684,
"text": "On a high level, I examined the distribution of each feature, removed outliers, create dummy variables for the categorical ‘room_type’ (since there are only three categories), and standardize the features."
},
{
"code": null,
"e": 2907,
"s": 2890,
"text": "Train/Test Split"
},
{
"code": null,
"e": 3000,
"s": 2907,
"text": "I set 70% of the dataset to be training set and the remaining 30% would be used as test set."
},
{
"code": null,
"e": 3089,
"s": 3000,
"text": "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)"
},
{
"code": null,
"e": 3101,
"s": 3089,
"text": "Base Models"
},
{
"code": null,
"e": 3442,
"s": 3101,
"text": "Let’s first build some base models. Here I have chosen Xgboost, Lasso Regression, and KNN as the three base models. In principle, stacking works best when the models are in a diverse range and their prediction errors are as uncorrelated as possible, so that individual model’s weaknesses and biases are offset by the strengths of others[2]."
},
{
"code": null,
"e": 3461,
"s": 3442,
"text": "Performance Metric"
},
{
"code": null,
"e": 3634,
"s": 3461,
"text": "In terms of performance metric to evaluate models, I choose to use Mean Absolute Error (MAE), which measures how far the predicted values are away from the measured values."
},
{
"code": null,
"e": 3665,
"s": 3634,
"text": "Performance of the Base Models"
},
{
"code": null,
"e": 3759,
"s": 3665,
"text": "Let’s quickly examine the performance of the three base models (all default hyperparameters):"
},
{
"code": null,
"e": 3888,
"s": 3759,
"text": "Model: XGBRegressor, MAE: 35.80629559761084Model: Lasso, MAE: 35.0691542225316Model: KNeighborsRegressor, MAE: 38.35917874396135"
},
{
"code": null,
"e": 4001,
"s": 3888,
"text": "The MAEs are between 35–38, meaning the predicted prices are about $35-$38 away from the true prices on average."
},
{
"code": null,
"e": 4038,
"s": 4001,
"text": "Build a Stacking Model Using mlxtend"
},
{
"code": null,
"e": 4210,
"s": 4038,
"text": "Now, we can build on top of the base models for the meta-learner. Alternatively, we can do a shortcut using ‘StackingCVRegressor’ from the mlxtend library (documentation):"
},
{
"code": null,
"e": 4637,
"s": 4210,
"text": "from mlxtend.regressor import StackingCVRegressorstack = StackingCVRegressor(regressors=(XGBRegressor(), Lasso(), KNeighborsRegressor()), meta_regressor=Lasso(), cv=10, use_features_in_secondary=True, store_train_meta_features=True, shuffle=False, random_state=1)"
},
{
"code": null,
"e": 5004,
"s": 4637,
"text": "The same three based models are used, and for the meta-learner, I chose to use Lasso. We could also try other regression models as meta-learners, and then build another meta-learner on top (3-layer stacking!) Note that in this configuration, I choose to also use the raw training data as inputs to the meta-model, since it can provide more context to the meta-model."
},
{
"code": null,
"e": 5094,
"s": 5004,
"text": "Now let’s fit our training data into the model and check the performance on the test set:"
},
{
"code": null,
"e": 5507,
"s": 5094,
"text": "stack.fit(X_train, y_train)X_test.columns = ['f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10', 'f11'] # Xgboost internally renames the featurespred = stack.predict(X_test)score = mean_absolute_error(y_test, pred)print('Model: {0}, MAE: {1}'.format(type(stack).__name__, score))--------------------------------------------------------------------Model: StackingCVRegressor, MAE: 34.01755981865483"
},
{
"code": null,
"e": 5617,
"s": 5507,
"text": "We see that the new MAE is about 34, decreased by 1 compared with the result from the best base model, Lasso."
},
{
"code": null,
"e": 5747,
"s": 5617,
"text": "Although the difference might seem trivial, small gains like this can actually make a huge difference on the leaderboard ranking."
},
{
"code": null,
"e": 5820,
"s": 5747,
"text": "If you want to look into ensemble neural networks, check out this paper."
},
{
"code": null,
"e": 5898,
"s": 5820,
"text": "Despite the capabilities of stacking, here are a few caveats to keep in mind:"
},
{
"code": null,
"e": 6437,
"s": 5898,
"text": "Effective use of stacking requires a bit of trials and errors sometimes, and there is no guarantee that stacking would result in an improved performance in all cases.Stacking can be computationally expensive, especially when the number of stacking layer is high.The interpretability of the model decreases as the number of stacking layer increases. This is not a big problem for Kaggle competition but for business cases, understanding the importance of features and its incremental impact on the outcome variable might be more important."
},
{
"code": null,
"e": 6604,
"s": 6437,
"text": "Effective use of stacking requires a bit of trials and errors sometimes, and there is no guarantee that stacking would result in an improved performance in all cases."
},
{
"code": null,
"e": 6701,
"s": 6604,
"text": "Stacking can be computationally expensive, especially when the number of stacking layer is high."
},
{
"code": null,
"e": 6978,
"s": 6701,
"text": "The interpretability of the model decreases as the number of stacking layer increases. This is not a big problem for Kaggle competition but for business cases, understanding the importance of features and its incremental impact on the outcome variable might be more important."
},
{
"code": null,
"e": 7031,
"s": 6978,
"text": "Here are a few things that we can try as next steps:"
},
{
"code": null,
"e": 7408,
"s": 7031,
"text": "Hyperparameter tuning — There are a few hyperparameters that we can tune in the selected models to further optimize the performance. ‘GridSearchCV’ can be a helpful tool in this process.Keep stacking — Try to build additional stacking layer(s) and make a plot of the performance metric vs the number of layers to examine if diminishing marginal return holds true (It should!)."
},
{
"code": null,
"e": 7595,
"s": 7408,
"text": "Hyperparameter tuning — There are a few hyperparameters that we can tune in the selected models to further optimize the performance. ‘GridSearchCV’ can be a helpful tool in this process."
},
{
"code": null,
"e": 7786,
"s": 7595,
"text": "Keep stacking — Try to build additional stacking layer(s) and make a plot of the performance metric vs the number of layers to examine if diminishing marginal return holds true (It should!)."
},
{
"code": null,
"e": 7807,
"s": 7786,
"text": "Let’s quickly recap."
},
{
"code": null,
"e": 7988,
"s": 7807,
"text": "We implemented a simple 2-layer stacking regression model in Python using the mlxtend library, compared its test MAE with the ones of three base models and observed an improvement."
},
{
"code": null,
"e": 8073,
"s": 7988,
"text": "I hope you enjoyed this blog post and please share any thoughts that you may have :)"
},
{
"code": null,
"e": 8138,
"s": 8073,
"text": "Check out my other post on dimensionality reduction using t-SNE:"
},
{
"code": null,
"e": 8161,
"s": 8138,
"text": "towardsdatascience.com"
}
] |
Generate a string with maximum possible alphabets with odd frequencies - GeeksforGeeks
|
19 Apr, 2021
Given an integer N, the task is to generate a string str which contains maximum possible lowercase alphabets with each of them appearing an odd number of times.Examples:
Input: N = 17 Output: bcdefghijklmnopqr Explanation: In order to maximize the number of characters, any 17 characters can be selected and made to appear once. Thus, abcdefghijklmnopq, bcdefghijklmnopqx, etc can be also be valid outputs.Input: N = 35 Output: bcdefghijklmnopqrstuvwxyaaaaaaaaaaa Explanation: In order to maximize the number of characters, add any 24 different characters once, and fill the remaining length by any other character.
Approach:
If N is less than equal to 26, we fill the string by N different characters each appearing once.
Otherwise: If N is odd, we add all 24 characters from ‘b’-‘y’ once and fill the remaining odd length by ‘a’.If N is even, we add all 25 characters from ‘b’-‘z’ once and fill the remaining odd length by ‘a’.
If N is odd, we add all 24 characters from ‘b’-‘y’ once and fill the remaining odd length by ‘a’.
If N is even, we add all 25 characters from ‘b’-‘z’ once and fill the remaining odd length by ‘a’.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to generate a string// of length n with maximum possible// alphabets with each of them// occuring odd number of times. #include <bits/stdc++.h>using namespace std; // Function to generate a string// of length n with maximum possible// alphabets each occuring odd// number of times.string generateTheString(int n){ string ans=""; // If n is odd if(n%2) { // Add all characters from // b-y for(int i=0;i<min(n,24);i++) { ans+=(char)('b' + i); } // Append a to fill the // remaining length if(n>24) { for(int i=0;i<(n-24);i++) ans+='a'; } } // If n is even else { // Add all characters from // b-z for(int i=0;i<min(n,25);i++) { ans+=(char)('b' + i); } // Append a to fill the // remaining length if(n>25) { for(int i=0;i<(n-25);i++) ans+='a'; } } return ans;} // Driven codeint main(){ int n = 34; cout << generateTheString(n); return 0;}
// Java program to generate a string// of length n with maximum possible// alphabets with each of them// occuring odd number of times.import java.util.*; class GFG{ // Function to generate a string// of length n with maximum possible// alphabets each occuring odd// number of times.static String generateTheString(int n){ String ans = ""; // If n is odd if (n % 2 != 0) { // Add all characters from // b-y for(int i = 0; i < Math.min(n, 24); i++) { ans += (char)('b' + i); } // Append a to fill the // remaining length if (n > 24) { for(int i = 0; i < (n - 24); i++) ans += 'a'; } } // If n is even else { // Add all characters from // b-z for(int i = 0; i < Math.min(n, 25); i++) { ans += (char)('b' + i); } // Append a to fill the // remaining length if (n > 25) { for(int i = 0; i < (n - 25); i++) ans += 'a'; } } return ans;} // Driver codepublic static void main(String[] args){ int n = 34; System.out.println(generateTheString(n));}} // This code is contributed by offbeat
# Python3 program to generate a string# of length n with maximum possible# alphabets with each of them# occuring odd number of times. # Function to generate a string# of length n with maximum possible# alphabets each occuring odd# number of times.def generateTheString( n): ans = "" # If n is odd if(n % 2): # Add all characters from # b-y for i in range(min(n, 24)): ans += chr(ord('b') + i) # Append a to fill the # remaining length if(n > 24): for i in range((n - 24)): ans += 'a' # If n is even else: # Add all characters from # b-z for i in range(min(n, 25)): ans += chr(ord('b') + i) # Append a to fill the # remaining length if(n > 25): for i in range((n - 25)): ans += 'a' return ans # Driver codeif __name__ == "__main__": n = 34 print(generateTheString(n)) # This code is contributed by chitranayal
// C# program to generate a string// of length n with maximum possible// alphabets with each of them// occuring odd number of times.using System;class GFG{ // Function to generate a string// of length n with maximum possible// alphabets each occuring odd// number of times.static string generateTheString(int n){ string ans = ""; // If n is odd if(n % 2 == 0) { // Add all characters from // b-y for(int i = 0; i < Math.Min(n, 24); i++) { ans += (char)('b' + i); } // Append a to fill the // remaining length if(n > 24) { for(int i = 0; i < (n - 24); i++) ans += 'a'; } } // If n is even else { // Add all characters from // b-z for(int i = 0; i < Math.Min(n, 25); i++) { ans += (char)('b' + i); } // Append a to fill the // remaining length if(n > 25) { for(int i = 0; i < (n - 25); i++) ans += 'a'; } } return ans;} // Driven codepublic static void Main(){ int n = 34; Console.Write(generateTheString(n));}} // This code is contributed by Nidhi_Biet
<script> // Javascript program to generate a string// of length n with maximum possible// alphabets with each of them// occuring odd number of times. // Function to generate a string// of length n with maximum possible// alphabets each occuring odd// number of times.function generateTheString(n){ var ans=""; // If n is odd if(n%2) { // Add all characters from // b-y for(var i=0;i<min(n,24);i++) { ans+=(char)('b' + i); } // Append a to fill the // remaining length if(n>24) { for(var i=0;i<(n-24);i++) ans+='a'; } } // If n is even else { // Add all characters from // b-z for(var i=0;i<Math.min(n,25);i++) { ans+= String.fromCharCode('b'.charCodeAt(0) + i); } // Append a to fill the // remaining length if(n>25) { for(var i=0;i<(n-25);i++) ans+='a'; } } return ans;} // Driven codevar n = 34;document.write( generateTheString(n)); </script>
bcdefghijklmnopqrstuvwxyzaaaaaaaaa
ukasp
nidhi_biet
offbeat
noob2000
Competitive Programming
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Shortest path in a directed graph by Dijkstra’s algorithm
Breadth First Traversal ( BFS ) on a 2D array
Multistage Graph (Shortest Path)
Runtime Errors
Graph implementation using STL for competitive programming | Set 2 (Weighted graph)
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
C++ Data Types
|
[
{
"code": null,
"e": 25024,
"s": 24996,
"text": "\n19 Apr, 2021"
},
{
"code": null,
"e": 25196,
"s": 25024,
"text": "Given an integer N, the task is to generate a string str which contains maximum possible lowercase alphabets with each of them appearing an odd number of times.Examples: "
},
{
"code": null,
"e": 25644,
"s": 25196,
"text": "Input: N = 17 Output: bcdefghijklmnopqr Explanation: In order to maximize the number of characters, any 17 characters can be selected and made to appear once. Thus, abcdefghijklmnopq, bcdefghijklmnopqx, etc can be also be valid outputs.Input: N = 35 Output: bcdefghijklmnopqrstuvwxyaaaaaaaaaaa Explanation: In order to maximize the number of characters, add any 24 different characters once, and fill the remaining length by any other character. "
},
{
"code": null,
"e": 25658,
"s": 25646,
"text": "Approach: "
},
{
"code": null,
"e": 25755,
"s": 25658,
"text": "If N is less than equal to 26, we fill the string by N different characters each appearing once."
},
{
"code": null,
"e": 25962,
"s": 25755,
"text": "Otherwise: If N is odd, we add all 24 characters from ‘b’-‘y’ once and fill the remaining odd length by ‘a’.If N is even, we add all 25 characters from ‘b’-‘z’ once and fill the remaining odd length by ‘a’."
},
{
"code": null,
"e": 26060,
"s": 25962,
"text": "If N is odd, we add all 24 characters from ‘b’-‘y’ once and fill the remaining odd length by ‘a’."
},
{
"code": null,
"e": 26159,
"s": 26060,
"text": "If N is even, we add all 25 characters from ‘b’-‘z’ once and fill the remaining odd length by ‘a’."
},
{
"code": null,
"e": 26211,
"s": 26159,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26215,
"s": 26211,
"text": "C++"
},
{
"code": null,
"e": 26220,
"s": 26215,
"text": "Java"
},
{
"code": null,
"e": 26228,
"s": 26220,
"text": "Python3"
},
{
"code": null,
"e": 26231,
"s": 26228,
"text": "C#"
},
{
"code": null,
"e": 26242,
"s": 26231,
"text": "Javascript"
},
{
"code": "// C++ program to generate a string// of length n with maximum possible// alphabets with each of them// occuring odd number of times. #include <bits/stdc++.h>using namespace std; // Function to generate a string// of length n with maximum possible// alphabets each occuring odd// number of times.string generateTheString(int n){ string ans=\"\"; // If n is odd if(n%2) { // Add all characters from // b-y for(int i=0;i<min(n,24);i++) { ans+=(char)('b' + i); } // Append a to fill the // remaining length if(n>24) { for(int i=0;i<(n-24);i++) ans+='a'; } } // If n is even else { // Add all characters from // b-z for(int i=0;i<min(n,25);i++) { ans+=(char)('b' + i); } // Append a to fill the // remaining length if(n>25) { for(int i=0;i<(n-25);i++) ans+='a'; } } return ans;} // Driven codeint main(){ int n = 34; cout << generateTheString(n); return 0;}",
"e": 27352,
"s": 26242,
"text": null
},
{
"code": "// Java program to generate a string// of length n with maximum possible// alphabets with each of them// occuring odd number of times.import java.util.*; class GFG{ // Function to generate a string// of length n with maximum possible// alphabets each occuring odd// number of times.static String generateTheString(int n){ String ans = \"\"; // If n is odd if (n % 2 != 0) { // Add all characters from // b-y for(int i = 0; i < Math.min(n, 24); i++) { ans += (char)('b' + i); } // Append a to fill the // remaining length if (n > 24) { for(int i = 0; i < (n - 24); i++) ans += 'a'; } } // If n is even else { // Add all characters from // b-z for(int i = 0; i < Math.min(n, 25); i++) { ans += (char)('b' + i); } // Append a to fill the // remaining length if (n > 25) { for(int i = 0; i < (n - 25); i++) ans += 'a'; } } return ans;} // Driver codepublic static void main(String[] args){ int n = 34; System.out.println(generateTheString(n));}} // This code is contributed by offbeat",
"e": 28688,
"s": 27352,
"text": null
},
{
"code": "# Python3 program to generate a string# of length n with maximum possible# alphabets with each of them# occuring odd number of times. # Function to generate a string# of length n with maximum possible# alphabets each occuring odd# number of times.def generateTheString( n): ans = \"\" # If n is odd if(n % 2): # Add all characters from # b-y for i in range(min(n, 24)): ans += chr(ord('b') + i) # Append a to fill the # remaining length if(n > 24): for i in range((n - 24)): ans += 'a' # If n is even else: # Add all characters from # b-z for i in range(min(n, 25)): ans += chr(ord('b') + i) # Append a to fill the # remaining length if(n > 25): for i in range((n - 25)): ans += 'a' return ans # Driver codeif __name__ == \"__main__\": n = 34 print(generateTheString(n)) # This code is contributed by chitranayal",
"e": 29735,
"s": 28688,
"text": null
},
{
"code": "// C# program to generate a string// of length n with maximum possible// alphabets with each of them// occuring odd number of times.using System;class GFG{ // Function to generate a string// of length n with maximum possible// alphabets each occuring odd// number of times.static string generateTheString(int n){ string ans = \"\"; // If n is odd if(n % 2 == 0) { // Add all characters from // b-y for(int i = 0; i < Math.Min(n, 24); i++) { ans += (char)('b' + i); } // Append a to fill the // remaining length if(n > 24) { for(int i = 0; i < (n - 24); i++) ans += 'a'; } } // If n is even else { // Add all characters from // b-z for(int i = 0; i < Math.Min(n, 25); i++) { ans += (char)('b' + i); } // Append a to fill the // remaining length if(n > 25) { for(int i = 0; i < (n - 25); i++) ans += 'a'; } } return ans;} // Driven codepublic static void Main(){ int n = 34; Console.Write(generateTheString(n));}} // This code is contributed by Nidhi_Biet",
"e": 30965,
"s": 29735,
"text": null
},
{
"code": "<script> // Javascript program to generate a string// of length n with maximum possible// alphabets with each of them// occuring odd number of times. // Function to generate a string// of length n with maximum possible// alphabets each occuring odd// number of times.function generateTheString(n){ var ans=\"\"; // If n is odd if(n%2) { // Add all characters from // b-y for(var i=0;i<min(n,24);i++) { ans+=(char)('b' + i); } // Append a to fill the // remaining length if(n>24) { for(var i=0;i<(n-24);i++) ans+='a'; } } // If n is even else { // Add all characters from // b-z for(var i=0;i<Math.min(n,25);i++) { ans+= String.fromCharCode('b'.charCodeAt(0) + i); } // Append a to fill the // remaining length if(n>25) { for(var i=0;i<(n-25);i++) ans+='a'; } } return ans;} // Driven codevar n = 34;document.write( generateTheString(n)); </script>",
"e": 32060,
"s": 30965,
"text": null
},
{
"code": null,
"e": 32095,
"s": 32060,
"text": "bcdefghijklmnopqrstuvwxyzaaaaaaaaa"
},
{
"code": null,
"e": 32103,
"s": 32097,
"text": "ukasp"
},
{
"code": null,
"e": 32114,
"s": 32103,
"text": "nidhi_biet"
},
{
"code": null,
"e": 32122,
"s": 32114,
"text": "offbeat"
},
{
"code": null,
"e": 32131,
"s": 32122,
"text": "noob2000"
},
{
"code": null,
"e": 32155,
"s": 32131,
"text": "Competitive Programming"
},
{
"code": null,
"e": 32163,
"s": 32155,
"text": "Strings"
},
{
"code": null,
"e": 32171,
"s": 32163,
"text": "Strings"
},
{
"code": null,
"e": 32269,
"s": 32171,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32278,
"s": 32269,
"text": "Comments"
},
{
"code": null,
"e": 32291,
"s": 32278,
"text": "Old Comments"
},
{
"code": null,
"e": 32349,
"s": 32291,
"text": "Shortest path in a directed graph by Dijkstra’s algorithm"
},
{
"code": null,
"e": 32395,
"s": 32349,
"text": "Breadth First Traversal ( BFS ) on a 2D array"
},
{
"code": null,
"e": 32428,
"s": 32395,
"text": "Multistage Graph (Shortest Path)"
},
{
"code": null,
"e": 32443,
"s": 32428,
"text": "Runtime Errors"
},
{
"code": null,
"e": 32527,
"s": 32443,
"text": "Graph implementation using STL for competitive programming | Set 2 (Weighted graph)"
},
{
"code": null,
"e": 32552,
"s": 32527,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 32598,
"s": 32552,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 32632,
"s": 32598,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 32692,
"s": 32632,
"text": "Write a program to print all permutations of a given string"
}
] |
Generate Parentheses in Python
|
Suppose we have a value n. We have to generate all possible well-formed parentheses where n number of opening and closing parentheses are present. So if the value of n = 3, then the parentheses set will be ["()()()","()(())","(())()","(()())","((()))"]
To solve this, we will follow these steps −
Define method called genParenthesisRec(). This takes left, right, temp string and result array. initially result array is empty
The function genParenthesisRec, will work like below
if left = 0 and right := 0, then insert temp into result, and return
if left > 0getParenthesisRec(left – 1, right, temp + “(”, result)
getParenthesisRec(left – 1, right, temp + “(”, result)
if right > leftgetParenthesisRec(left, right – 1, temp + “)”, result)
getParenthesisRec(left, right – 1, temp + “)”, result)
Let us see the following implementation to get a better understanding −
Live Demo
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
result = []
self.generateParenthesisUtil(n,n,"",result)
return result
def generateParenthesisUtil(self, left,right,temp,result):
if left == 0 and right == 0:
result.append(temp)
return
if left>0:
self.generateParenthesisUtil(left-1,right,temp+'(',result)
if right > left:
self.generateParenthesisUtil(left, right-1, temp + ')', result)
ob = Solution()
print(ob.generateParenthesis(4))
4
["(((())))",
"((()()))",
"((())())",
"((()))()",
"(()(()))",
"(()()())",
"(()())()",
"(())(())",
"(())()()",
"()((()))",
"()(()())",
"()(())()",
"()()(())",
"()()()()"]
|
[
{
"code": null,
"e": 1315,
"s": 1062,
"text": "Suppose we have a value n. We have to generate all possible well-formed parentheses where n number of opening and closing parentheses are present. So if the value of n = 3, then the parentheses set will be [\"()()()\",\"()(())\",\"(())()\",\"(()())\",\"((()))\"]"
},
{
"code": null,
"e": 1359,
"s": 1315,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1487,
"s": 1359,
"text": "Define method called genParenthesisRec(). This takes left, right, temp string and result array. initially result array is empty"
},
{
"code": null,
"e": 1540,
"s": 1487,
"text": "The function genParenthesisRec, will work like below"
},
{
"code": null,
"e": 1609,
"s": 1540,
"text": "if left = 0 and right := 0, then insert temp into result, and return"
},
{
"code": null,
"e": 1675,
"s": 1609,
"text": "if left > 0getParenthesisRec(left – 1, right, temp + “(”, result)"
},
{
"code": null,
"e": 1730,
"s": 1675,
"text": "getParenthesisRec(left – 1, right, temp + “(”, result)"
},
{
"code": null,
"e": 1800,
"s": 1730,
"text": "if right > leftgetParenthesisRec(left, right – 1, temp + “)”, result)"
},
{
"code": null,
"e": 1855,
"s": 1800,
"text": "getParenthesisRec(left, right – 1, temp + “)”, result)"
},
{
"code": null,
"e": 1927,
"s": 1855,
"text": "Let us see the following implementation to get a better understanding −"
},
{
"code": null,
"e": 1938,
"s": 1927,
"text": " Live Demo"
},
{
"code": null,
"e": 2522,
"s": 1938,
"text": "class Solution(object):\n def generateParenthesis(self, n):\n \"\"\"\n :type n: int\n :rtype: List[str]\n \"\"\"\n result = []\n self.generateParenthesisUtil(n,n,\"\",result)\n return result\n def generateParenthesisUtil(self, left,right,temp,result):\n if left == 0 and right == 0:\n result.append(temp)\n return\n if left>0:\n self.generateParenthesisUtil(left-1,right,temp+'(',result)\n if right > left:\n self.generateParenthesisUtil(left, right-1, temp + ')', result)\nob = Solution()\nprint(ob.generateParenthesis(4))"
},
{
"code": null,
"e": 2524,
"s": 2522,
"text": "4"
},
{
"code": null,
"e": 2693,
"s": 2524,
"text": "[\"(((())))\",\n\"((()()))\",\n\"((())())\",\n\"((()))()\",\n\"(()(()))\",\n\"(()()())\",\n\"(()())()\",\n\"(())(())\",\n\"(())()()\",\n\"()((()))\",\n\"()(()())\",\n\"()(())()\",\n\"()()(())\",\n\"()()()()\"]"
}
] |
Program to find the surface area of the square pyramid - GeeksforGeeks
|
22 Mar, 2021
Given the base length(b) and slant height(s) of the square pyramid. The task is to find the surface area of the Square Pyramid. A Pyramid with a square base, 4 triangular faces, and an apex is a square pyramid.
In this figure, b – base length of the square pyramid. s – slant height of the square pyramid. h – height of the square pyramid.Examples:
Input: b = 3, s = 4
Output: 33
Input: b = 4, s = 5
Output: 56
Formula for calculating the surface are of the square pyramid with (b) base length and (s) slant height.
Below is the implementation using the above formula:
C++
Java
Python 3
C#
PHP
Javascript
// CPP program to find the surface area// Of Square pyramid#include <bits/stdc++.h>using namespace std; // function to find the surface areaint surfaceArea(int b, int s){ return 2 * b * s + pow(b, 2);} // Driver programint main(){ int b = 3, s = 4; // surface area of the square pyramid cout << surfaceArea(b, s) << endl; return 0;}
// Java program to find the surface area// Of Square pyramid import java.io.*; class GFG { // function to find the surface areastatic int surfaceArea(int b, int s){ return 2 * b * s + (int)Math.pow(b, 2);} // Driver program public static void main (String[] args) { int b = 3, s = 4; // surface area of the square pyramid System.out.println( surfaceArea(b, s)); }}//This code is contributed by anuj_67..
# Python 3 program to find the# surface area Of Square pyramid # function to find the surface areadef surfaceArea(b, s): return 2 * b * s + pow(b, 2) # Driver Codeif __name__ == "__main__": b = 3 s = 4 # surface area of the square pyramid print(surfaceArea(b, s)) # This code is contributed# by ChitraNayal
// C# program to find the surface// area Of Square pyramidusing System; class GFG{ // function to find the surface areastatic int surfaceArea(int b, int s){ return 2 * b * s + (int)Math.Pow(b, 2);} // Driver Codepublic static void Main (){ int b = 3, s = 4; // surface area of the square pyramid Console.WriteLine(surfaceArea(b, s));}} // This code is contributed// by inder_verma
<?php// PHP program to find the surface// area Of Square pyramid // function to find the surface areafunction surfaceArea($b, $s){ return 2 * $b * $s + pow($b, 2);} // Driver Code$b = 3; $s = 4; // surface area of the// square pyramidecho surfaceArea($b, $s); // This code is contributed// by anuj_67?>
<script>// javascript program to find the surface area// Of Square pyramid // function to find the surface areafunction surfaceArea(b , s){ return 2 * b * s + parseInt(Math.pow(b, 2));} // Driver programvar b = 3, s = 4; // surface area of the square pyramiddocument.write( surfaceArea(b, s)); // This code is contributed by shikhasingrajput</script>
33
vt_m
inderDuMCA
ukasp
shikhasingrajput
area-volume-programs
Geometric
Mathematical
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for distance between two points on earth
Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)
Convex Hull | Set 2 (Graham Scan)
Given n line segments, find if any two segments intersect
Closest Pair of Points | O(nlogn) Implementation
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 25036,
"s": 25008,
"text": "\n22 Mar, 2021"
},
{
"code": null,
"e": 25248,
"s": 25036,
"text": "Given the base length(b) and slant height(s) of the square pyramid. The task is to find the surface area of the Square Pyramid. A Pyramid with a square base, 4 triangular faces, and an apex is a square pyramid. "
},
{
"code": null,
"e": 25388,
"s": 25248,
"text": "In this figure, b – base length of the square pyramid. s – slant height of the square pyramid. h – height of the square pyramid.Examples: "
},
{
"code": null,
"e": 25451,
"s": 25388,
"text": "Input: b = 3, s = 4\nOutput: 33\n\nInput: b = 4, s = 5\nOutput: 56"
},
{
"code": null,
"e": 25559,
"s": 25453,
"text": "Formula for calculating the surface are of the square pyramid with (b) base length and (s) slant height. "
},
{
"code": null,
"e": 25619,
"s": 25564,
"text": "Below is the implementation using the above formula: "
},
{
"code": null,
"e": 25623,
"s": 25619,
"text": "C++"
},
{
"code": null,
"e": 25628,
"s": 25623,
"text": "Java"
},
{
"code": null,
"e": 25637,
"s": 25628,
"text": "Python 3"
},
{
"code": null,
"e": 25640,
"s": 25637,
"text": "C#"
},
{
"code": null,
"e": 25644,
"s": 25640,
"text": "PHP"
},
{
"code": null,
"e": 25655,
"s": 25644,
"text": "Javascript"
},
{
"code": "// CPP program to find the surface area// Of Square pyramid#include <bits/stdc++.h>using namespace std; // function to find the surface areaint surfaceArea(int b, int s){ return 2 * b * s + pow(b, 2);} // Driver programint main(){ int b = 3, s = 4; // surface area of the square pyramid cout << surfaceArea(b, s) << endl; return 0;}",
"e": 26005,
"s": 25655,
"text": null
},
{
"code": "// Java program to find the surface area// Of Square pyramid import java.io.*; class GFG { // function to find the surface areastatic int surfaceArea(int b, int s){ return 2 * b * s + (int)Math.pow(b, 2);} // Driver program public static void main (String[] args) { int b = 3, s = 4; // surface area of the square pyramid System.out.println( surfaceArea(b, s)); }}//This code is contributed by anuj_67..",
"e": 26441,
"s": 26005,
"text": null
},
{
"code": "# Python 3 program to find the# surface area Of Square pyramid # function to find the surface areadef surfaceArea(b, s): return 2 * b * s + pow(b, 2) # Driver Codeif __name__ == \"__main__\": b = 3 s = 4 # surface area of the square pyramid print(surfaceArea(b, s)) # This code is contributed# by ChitraNayal",
"e": 26765,
"s": 26441,
"text": null
},
{
"code": "// C# program to find the surface// area Of Square pyramidusing System; class GFG{ // function to find the surface areastatic int surfaceArea(int b, int s){ return 2 * b * s + (int)Math.Pow(b, 2);} // Driver Codepublic static void Main (){ int b = 3, s = 4; // surface area of the square pyramid Console.WriteLine(surfaceArea(b, s));}} // This code is contributed// by inder_verma",
"e": 27164,
"s": 26765,
"text": null
},
{
"code": "<?php// PHP program to find the surface// area Of Square pyramid // function to find the surface areafunction surfaceArea($b, $s){ return 2 * $b * $s + pow($b, 2);} // Driver Code$b = 3; $s = 4; // surface area of the// square pyramidecho surfaceArea($b, $s); // This code is contributed// by anuj_67?>",
"e": 27470,
"s": 27164,
"text": null
},
{
"code": "<script>// javascript program to find the surface area// Of Square pyramid // function to find the surface areafunction surfaceArea(b , s){ return 2 * b * s + parseInt(Math.pow(b, 2));} // Driver programvar b = 3, s = 4; // surface area of the square pyramiddocument.write( surfaceArea(b, s)); // This code is contributed by shikhasingrajput</script>",
"e": 27824,
"s": 27470,
"text": null
},
{
"code": null,
"e": 27827,
"s": 27824,
"text": "33"
},
{
"code": null,
"e": 27834,
"s": 27829,
"text": "vt_m"
},
{
"code": null,
"e": 27845,
"s": 27834,
"text": "inderDuMCA"
},
{
"code": null,
"e": 27851,
"s": 27845,
"text": "ukasp"
},
{
"code": null,
"e": 27868,
"s": 27851,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 27889,
"s": 27868,
"text": "area-volume-programs"
},
{
"code": null,
"e": 27899,
"s": 27889,
"text": "Geometric"
},
{
"code": null,
"e": 27912,
"s": 27899,
"text": "Mathematical"
},
{
"code": null,
"e": 27925,
"s": 27912,
"text": "Mathematical"
},
{
"code": null,
"e": 27935,
"s": 27925,
"text": "Geometric"
},
{
"code": null,
"e": 28033,
"s": 27935,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28082,
"s": 28033,
"text": "Program for distance between two points on earth"
},
{
"code": null,
"e": 28135,
"s": 28082,
"text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)"
},
{
"code": null,
"e": 28169,
"s": 28135,
"text": "Convex Hull | Set 2 (Graham Scan)"
},
{
"code": null,
"e": 28227,
"s": 28169,
"text": "Given n line segments, find if any two segments intersect"
},
{
"code": null,
"e": 28276,
"s": 28227,
"text": "Closest Pair of Points | O(nlogn) Implementation"
},
{
"code": null,
"e": 28306,
"s": 28276,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 28366,
"s": 28306,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 28381,
"s": 28366,
"text": "C++ Data Types"
},
{
"code": null,
"e": 28424,
"s": 28381,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Calculating the mean of all pixels for each band in an image using the Pillow library
|
In this program, we will calculate the mean of all the pixels in each channel using the Pillow library. There are a total three channels in an image and therefore, we will get a list of three values.
Step 1: Import the Image and ImageStat libraries.
Step 2: Open the image.
Step 3: Pass the image to the stat function of the imagestat class.
Step 4: Print the mean of the pixels.
from PIL import Image, ImageStat
im = Image.open('image_test.jpg')
stat = ImageStat.Stat(im)
print(stat.mean)
[76.00257724463832, 69.6674300254453, 64.38017448200654]
|
[
{
"code": null,
"e": 1262,
"s": 1062,
"text": "In this program, we will calculate the mean of all the pixels in each channel using the Pillow library. There are a total three channels in an image and therefore, we will get a list of three values."
},
{
"code": null,
"e": 1442,
"s": 1262,
"text": "Step 1: Import the Image and ImageStat libraries.\nStep 2: Open the image.\nStep 3: Pass the image to the stat function of the imagestat class.\nStep 4: Print the mean of the pixels."
},
{
"code": null,
"e": 1553,
"s": 1442,
"text": "from PIL import Image, ImageStat\n\nim = Image.open('image_test.jpg')\nstat = ImageStat.Stat(im)\nprint(stat.mean)"
},
{
"code": null,
"e": 1610,
"s": 1553,
"text": "[76.00257724463832, 69.6674300254453, 64.38017448200654]"
}
] |
How to count number of occurrences of repeated names in an array of objects in JavaScript ? - GeeksforGeeks
|
24 Apr, 2021
Given an array of objects and the task is to find the occurrences of a given key according to its value.
Example:
Input : arr = [
{
employeeName: "Ram",
employeeId: 23
},
{
employeeName: "Shyam",
employeeId: 24
},
{
employeeName: "Ram",
employeeId: 21
},
{
employeeName: "Ram",
employeeId: 25
},
{
employeeName: "Kisan",
employeeId: 22
},
{
employeeName: "Shyam",
employeeId: 20
}
]
key = "employeeName"
Output: [
{employeeName: "Ram", occurrences: 3},
{employeeName: "Shyam", occurrences: 2},
{employeeName: "Kisan", occurrences: 1}
]
To achieve this we have the following approaches:
In this approach, we follow the steps below.
Create an empty output array.
Using the forEach iterate the input array.
Check if the output array contains any object which contains the provided key’s value
If not, then create a new object and initialize the object with the key(the provided key name) set to value (the key’s value of the object of the present iteration) and occurrence set to value 1
If yes, then iterate the output array and search if the key of the present iteration is equal to the key of the input array iteration then increase the occurrence to 1.
Javascript
<script>function findOcc(arr, key){ let arr2 = []; arr.forEach((x)=>{ // Checking if there is any object in arr2 // which contains the key value if(arr2.some((val)=>{ return val[key] == x[key] })){ // If yes! then increase the occurrence by 1 arr2.forEach((k)=>{ if(k[key] === x[key]){ k["occurrence"]++ } }) }else{ // If not! Then create a new object initialize // it with the present iteration key's value and // set the occurrence to 1 let a = {} a[key] = x[key] a["occurrence"] = 1 arr2.push(a); } }) return arr2} let arr = [ { employeeName: "Ram", employeeId: 23 }, { employeeName: "Shyam", employeeId: 24 }, { employeeName: "Ram", employeeId: 21 }, { employeeName: "Ram", employeeId: 25 }, { employeeName: "Kisan", employeeId: 22 }, { employeeName: "Shyam", employeeId: 20 }] let key = "employeeName"console.log(findOcc(arr, key))</script>
Output:
[
{
employeeName: "Ram",
occurrence: 3
},
{
employeeName: "Shyam",
occurrence: 2
},
{
employeeName: "Kisan",
occurrence: 1
}
]
javascript-array
javascript-basics
JavaScript-Questions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
How to calculate the number of days between two dates in javascript?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
File uploading in React.js
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": 37970,
"s": 37942,
"text": "\n24 Apr, 2021"
},
{
"code": null,
"e": 38075,
"s": 37970,
"text": "Given an array of objects and the task is to find the occurrences of a given key according to its value."
},
{
"code": null,
"e": 38084,
"s": 38075,
"text": "Example:"
},
{
"code": null,
"e": 38630,
"s": 38084,
"text": "Input : arr = [\n {\n employeeName: \"Ram\",\n employeeId: 23\n },\n {\n employeeName: \"Shyam\",\n employeeId: 24\n },\n {\n employeeName: \"Ram\",\n employeeId: 21\n },\n {\n employeeName: \"Ram\",\n employeeId: 25\n },\n {\n employeeName: \"Kisan\",\n employeeId: 22\n },\n {\n employeeName: \"Shyam\",\n employeeId: 20\n }\n]\n\nkey = \"employeeName\"\n\nOutput: [\n {employeeName: \"Ram\", occurrences: 3},\n {employeeName: \"Shyam\", occurrences: 2},\n {employeeName: \"Kisan\", occurrences: 1}\n] "
},
{
"code": null,
"e": 38680,
"s": 38630,
"text": "To achieve this we have the following approaches:"
},
{
"code": null,
"e": 38725,
"s": 38680,
"text": "In this approach, we follow the steps below."
},
{
"code": null,
"e": 38755,
"s": 38725,
"text": "Create an empty output array."
},
{
"code": null,
"e": 38798,
"s": 38755,
"text": "Using the forEach iterate the input array."
},
{
"code": null,
"e": 38884,
"s": 38798,
"text": "Check if the output array contains any object which contains the provided key’s value"
},
{
"code": null,
"e": 39079,
"s": 38884,
"text": "If not, then create a new object and initialize the object with the key(the provided key name) set to value (the key’s value of the object of the present iteration) and occurrence set to value 1"
},
{
"code": null,
"e": 39248,
"s": 39079,
"text": "If yes, then iterate the output array and search if the key of the present iteration is equal to the key of the input array iteration then increase the occurrence to 1."
},
{
"code": null,
"e": 39259,
"s": 39248,
"text": "Javascript"
},
{
"code": "<script>function findOcc(arr, key){ let arr2 = []; arr.forEach((x)=>{ // Checking if there is any object in arr2 // which contains the key value if(arr2.some((val)=>{ return val[key] == x[key] })){ // If yes! then increase the occurrence by 1 arr2.forEach((k)=>{ if(k[key] === x[key]){ k[\"occurrence\"]++ } }) }else{ // If not! Then create a new object initialize // it with the present iteration key's value and // set the occurrence to 1 let a = {} a[key] = x[key] a[\"occurrence\"] = 1 arr2.push(a); } }) return arr2} let arr = [ { employeeName: \"Ram\", employeeId: 23 }, { employeeName: \"Shyam\", employeeId: 24 }, { employeeName: \"Ram\", employeeId: 21 }, { employeeName: \"Ram\", employeeId: 25 }, { employeeName: \"Kisan\", employeeId: 22 }, { employeeName: \"Shyam\", employeeId: 20 }] let key = \"employeeName\"console.log(findOcc(arr, key))</script>",
"e": 40336,
"s": 39259,
"text": null
},
{
"code": null,
"e": 40344,
"s": 40336,
"text": "Output:"
},
{
"code": null,
"e": 40522,
"s": 40344,
"text": "[\n {\n employeeName: \"Ram\",\n occurrence: 3\n }, \n {\n employeeName: \"Shyam\",\n occurrence: 2\n }, \n {\n employeeName: \"Kisan\",\n occurrence: 1\n }\n]"
},
{
"code": null,
"e": 40539,
"s": 40522,
"text": "javascript-array"
},
{
"code": null,
"e": 40557,
"s": 40539,
"text": "javascript-basics"
},
{
"code": null,
"e": 40578,
"s": 40557,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 40589,
"s": 40578,
"text": "JavaScript"
},
{
"code": null,
"e": 40606,
"s": 40589,
"text": "Web Technologies"
},
{
"code": null,
"e": 40704,
"s": 40606,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40713,
"s": 40704,
"text": "Comments"
},
{
"code": null,
"e": 40726,
"s": 40713,
"text": "Old Comments"
},
{
"code": null,
"e": 40771,
"s": 40726,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 40840,
"s": 40771,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 40901,
"s": 40840,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 40973,
"s": 40901,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 41000,
"s": 40973,
"text": "File uploading in React.js"
},
{
"code": null,
"e": 41042,
"s": 41000,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 41075,
"s": 41042,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 41118,
"s": 41075,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 41180,
"s": 41118,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
DATE_FORMAT() Function in MariaDB - GeeksforGeeks
|
26 Oct, 2020
DATE_FORMAT() Function :In MariaDB, the DATE_FORMAT() function uses two parameters – a date as specified by a format mask. In this function, the first parameter will be a date and the second parameter will be the mask. This function will return the date in the given mask. This function will convert the date with the masking format.
Syntax :
DATE_FORMAT(date, format_mask)
Parameters : Required.
date – The date to format.
format_mask – The format to apply to the date.
Returns : The converted date as per the masking format.
Format :
%Y : Year as a numeric, 4-digit value
%y : Year as a numeric, 2-digit value
%a : Weekday name abbreviated (Sun to Sat)
%b : Month name abbreviated (Jan to Dec)
%c : Month as a numeric value (0 to 12)
%D : Day of the month as a numeric value, followed by a suffix (1st, 2nd, 3rd, ...)
%d : Day of the month as a numeric value (01 to 31)
%e : Day of the month as a numeric value (0 to 31)
%f : Microseconds (000000 to 999999)
%H : Hour (00 to 23)
%h : Hour (00 to 12)
%I : Hour (00 to 12)
%i : Minutes (00 to 59)
%j : Day of the year (001 to 366)
%k : Hour (00 to 23)
%l : Hour (1 to 12)
%M : Month name in full (January to December)
%m : Month name as a numeric value (00 to 12)
%p : AM or PM
%r : Time in 12 hour AM or PM format (hh:mm:ss AM/PM)
%S : Seconds (00 to 59)
%s : Seconds (00 to 59)
%T : Time in 24-hour format (hh:mm: ss)
%U : Week where Sunday is the first day of the week (00 to 53)
%u : Week where Monday is the first day of the week (00 to 53)
%V : Week where Sunday is the first day of the week (01 to 53)
%v : Week where Monday is the first day of the week (01 to 53)
%W : Weekday name in full (Sunday to Saturday)
%w : Day of the week where Sunday=0 and Saturday=6
%X : Year for the week where Sunday is the first day of the week
%x : Year for the week where Monday is the first day of the week
Example-1 :
SELECT DATE_FORMAT('2020-04-09', '%M %d, %Y');
Output –
'April 09, 2020'
Example-2 :
SELECT DATE_FORMAT('2020-10-18', '%W');
Output –
'Sunday'
Example-3 :
SELECT DATE_FORMAT('2020-10-20', '%M %e %Y');
Output –
'October 20 2020'
Example-4 :
SELECT DATE_FORMAT('2020-10-19', '%W, %M %e, %Y');
Output –
'Monday, October 19, 2020'
Example-5 :
SELECT DATE_FORMAT('2014-05-17 08:44:21.000001', '%h');
Output –
8
Example-6 :
SELECT DATE_FORMAT('2019-08-11 10:44:21', '%s');
Output –
44
Example-7 :
SELECT DATE_FORMAT('2012-06-15 11:23:16', '%t');
Output –
11:23:16
Example-8 :
SELECT DATE_FORMAT('2019-03-13', '%M');
Output –
March
Example-9 :
SELECT DATE_FORMAT('2020-10-23', '%W');
Output –
Friday
Example-10 :
SELECT DATE_FORMAT('2019-05-13', '%Y');
Output –
'2019'
DBMS-SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Update Multiple Columns in Single Update Statement in SQL?
How to Alter Multiple Columns at Once in SQL Server?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL | Subquery
SQL Query to Convert VARCHAR to INT
SQL | Date functions
SQL - SELECT from Multiple Tables with MS SQL Server
SQL Query to Insert Multiple Rows
|
[
{
"code": null,
"e": 24268,
"s": 24240,
"text": "\n26 Oct, 2020"
},
{
"code": null,
"e": 24602,
"s": 24268,
"text": "DATE_FORMAT() Function :In MariaDB, the DATE_FORMAT() function uses two parameters – a date as specified by a format mask. In this function, the first parameter will be a date and the second parameter will be the mask. This function will return the date in the given mask. This function will convert the date with the masking format."
},
{
"code": null,
"e": 24611,
"s": 24602,
"text": "Syntax :"
},
{
"code": null,
"e": 24642,
"s": 24611,
"text": "DATE_FORMAT(date, format_mask)"
},
{
"code": null,
"e": 24665,
"s": 24642,
"text": "Parameters : Required."
},
{
"code": null,
"e": 24692,
"s": 24665,
"text": "date – The date to format."
},
{
"code": null,
"e": 24739,
"s": 24692,
"text": "format_mask – The format to apply to the date."
},
{
"code": null,
"e": 24795,
"s": 24739,
"text": "Returns : The converted date as per the masking format."
},
{
"code": null,
"e": 24804,
"s": 24795,
"text": "Format :"
},
{
"code": null,
"e": 24842,
"s": 24804,
"text": "%Y : Year as a numeric, 4-digit value"
},
{
"code": null,
"e": 24880,
"s": 24842,
"text": "%y : Year as a numeric, 2-digit value"
},
{
"code": null,
"e": 24923,
"s": 24880,
"text": "%a : Weekday name abbreviated (Sun to Sat)"
},
{
"code": null,
"e": 24964,
"s": 24923,
"text": "%b : Month name abbreviated (Jan to Dec)"
},
{
"code": null,
"e": 25004,
"s": 24964,
"text": "%c : Month as a numeric value (0 to 12)"
},
{
"code": null,
"e": 25088,
"s": 25004,
"text": "%D : Day of the month as a numeric value, followed by a suffix (1st, 2nd, 3rd, ...)"
},
{
"code": null,
"e": 25140,
"s": 25088,
"text": "%d : Day of the month as a numeric value (01 to 31)"
},
{
"code": null,
"e": 25191,
"s": 25140,
"text": "%e : Day of the month as a numeric value (0 to 31)"
},
{
"code": null,
"e": 25228,
"s": 25191,
"text": "%f : Microseconds (000000 to 999999)"
},
{
"code": null,
"e": 25249,
"s": 25228,
"text": "%H : Hour (00 to 23)"
},
{
"code": null,
"e": 25270,
"s": 25249,
"text": "%h : Hour (00 to 12)"
},
{
"code": null,
"e": 25291,
"s": 25270,
"text": "%I : Hour (00 to 12)"
},
{
"code": null,
"e": 25315,
"s": 25291,
"text": "%i : Minutes (00 to 59)"
},
{
"code": null,
"e": 25349,
"s": 25315,
"text": "%j : Day of the year (001 to 366)"
},
{
"code": null,
"e": 25370,
"s": 25349,
"text": "%k : Hour (00 to 23)"
},
{
"code": null,
"e": 25390,
"s": 25370,
"text": "%l : Hour (1 to 12)"
},
{
"code": null,
"e": 25436,
"s": 25390,
"text": "%M : Month name in full (January to December)"
},
{
"code": null,
"e": 25482,
"s": 25436,
"text": "%m : Month name as a numeric value (00 to 12)"
},
{
"code": null,
"e": 25496,
"s": 25482,
"text": "%p : AM or PM"
},
{
"code": null,
"e": 25550,
"s": 25496,
"text": "%r : Time in 12 hour AM or PM format (hh:mm:ss AM/PM)"
},
{
"code": null,
"e": 25574,
"s": 25550,
"text": "%S : Seconds (00 to 59)"
},
{
"code": null,
"e": 25598,
"s": 25574,
"text": "%s : Seconds (00 to 59)"
},
{
"code": null,
"e": 25638,
"s": 25598,
"text": "%T : Time in 24-hour format (hh:mm: ss)"
},
{
"code": null,
"e": 25701,
"s": 25638,
"text": "%U : Week where Sunday is the first day of the week (00 to 53)"
},
{
"code": null,
"e": 25764,
"s": 25701,
"text": "%u : Week where Monday is the first day of the week (00 to 53)"
},
{
"code": null,
"e": 25827,
"s": 25764,
"text": "%V : Week where Sunday is the first day of the week (01 to 53)"
},
{
"code": null,
"e": 25890,
"s": 25827,
"text": "%v : Week where Monday is the first day of the week (01 to 53)"
},
{
"code": null,
"e": 25937,
"s": 25890,
"text": "%W : Weekday name in full (Sunday to Saturday)"
},
{
"code": null,
"e": 25988,
"s": 25937,
"text": "%w : Day of the week where Sunday=0 and Saturday=6"
},
{
"code": null,
"e": 26053,
"s": 25988,
"text": "%X : Year for the week where Sunday is the first day of the week"
},
{
"code": null,
"e": 26118,
"s": 26053,
"text": "%x : Year for the week where Monday is the first day of the week"
},
{
"code": null,
"e": 26130,
"s": 26118,
"text": "Example-1 :"
},
{
"code": null,
"e": 26177,
"s": 26130,
"text": "SELECT DATE_FORMAT('2020-04-09', '%M %d, %Y');"
},
{
"code": null,
"e": 26186,
"s": 26177,
"text": "Output –"
},
{
"code": null,
"e": 26203,
"s": 26186,
"text": "'April 09, 2020'"
},
{
"code": null,
"e": 26215,
"s": 26203,
"text": "Example-2 :"
},
{
"code": null,
"e": 26255,
"s": 26215,
"text": "SELECT DATE_FORMAT('2020-10-18', '%W');"
},
{
"code": null,
"e": 26264,
"s": 26255,
"text": "Output –"
},
{
"code": null,
"e": 26273,
"s": 26264,
"text": "'Sunday'"
},
{
"code": null,
"e": 26285,
"s": 26273,
"text": "Example-3 :"
},
{
"code": null,
"e": 26331,
"s": 26285,
"text": "SELECT DATE_FORMAT('2020-10-20', '%M %e %Y');"
},
{
"code": null,
"e": 26340,
"s": 26331,
"text": "Output –"
},
{
"code": null,
"e": 26358,
"s": 26340,
"text": "'October 20 2020'"
},
{
"code": null,
"e": 26370,
"s": 26358,
"text": "Example-4 :"
},
{
"code": null,
"e": 26421,
"s": 26370,
"text": "SELECT DATE_FORMAT('2020-10-19', '%W, %M %e, %Y');"
},
{
"code": null,
"e": 26430,
"s": 26421,
"text": "Output –"
},
{
"code": null,
"e": 26457,
"s": 26430,
"text": "'Monday, October 19, 2020'"
},
{
"code": null,
"e": 26469,
"s": 26457,
"text": "Example-5 :"
},
{
"code": null,
"e": 26525,
"s": 26469,
"text": "SELECT DATE_FORMAT('2014-05-17 08:44:21.000001', '%h');"
},
{
"code": null,
"e": 26534,
"s": 26525,
"text": "Output –"
},
{
"code": null,
"e": 26536,
"s": 26534,
"text": "8"
},
{
"code": null,
"e": 26548,
"s": 26536,
"text": "Example-6 :"
},
{
"code": null,
"e": 26597,
"s": 26548,
"text": "SELECT DATE_FORMAT('2019-08-11 10:44:21', '%s');"
},
{
"code": null,
"e": 26606,
"s": 26597,
"text": "Output –"
},
{
"code": null,
"e": 26609,
"s": 26606,
"text": "44"
},
{
"code": null,
"e": 26621,
"s": 26609,
"text": "Example-7 :"
},
{
"code": null,
"e": 26670,
"s": 26621,
"text": "SELECT DATE_FORMAT('2012-06-15 11:23:16', '%t');"
},
{
"code": null,
"e": 26679,
"s": 26670,
"text": "Output –"
},
{
"code": null,
"e": 26688,
"s": 26679,
"text": "11:23:16"
},
{
"code": null,
"e": 26700,
"s": 26688,
"text": "Example-8 :"
},
{
"code": null,
"e": 26740,
"s": 26700,
"text": "SELECT DATE_FORMAT('2019-03-13', '%M');"
},
{
"code": null,
"e": 26749,
"s": 26740,
"text": "Output –"
},
{
"code": null,
"e": 26755,
"s": 26749,
"text": "March"
},
{
"code": null,
"e": 26767,
"s": 26755,
"text": "Example-9 :"
},
{
"code": null,
"e": 26807,
"s": 26767,
"text": "SELECT DATE_FORMAT('2020-10-23', '%W');"
},
{
"code": null,
"e": 26816,
"s": 26807,
"text": "Output –"
},
{
"code": null,
"e": 26823,
"s": 26816,
"text": "Friday"
},
{
"code": null,
"e": 26836,
"s": 26823,
"text": "Example-10 :"
},
{
"code": null,
"e": 26876,
"s": 26836,
"text": "SELECT DATE_FORMAT('2019-05-13', '%Y');"
},
{
"code": null,
"e": 26885,
"s": 26876,
"text": "Output –"
},
{
"code": null,
"e": 26892,
"s": 26885,
"text": "'2019'"
},
{
"code": null,
"e": 26901,
"s": 26892,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 26905,
"s": 26901,
"text": "SQL"
},
{
"code": null,
"e": 26909,
"s": 26905,
"text": "SQL"
},
{
"code": null,
"e": 27007,
"s": 26909,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27016,
"s": 27007,
"text": "Comments"
},
{
"code": null,
"e": 27029,
"s": 27016,
"text": "Old Comments"
},
{
"code": null,
"e": 27095,
"s": 27029,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 27148,
"s": 27095,
"text": "How to Alter Multiple Columns at Once in SQL Server?"
},
{
"code": null,
"e": 27180,
"s": 27148,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 27258,
"s": 27180,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 27275,
"s": 27258,
"text": "SQL using Python"
},
{
"code": null,
"e": 27290,
"s": 27275,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 27326,
"s": 27290,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 27347,
"s": 27326,
"text": "SQL | Date functions"
},
{
"code": null,
"e": 27400,
"s": 27347,
"text": "SQL - SELECT from Multiple Tables with MS SQL Server"
}
] |
Analyzing lyrics from different music genres with universal sentence encoding | by Sam Ho | Towards Data Science
|
My enduring love affair with music was ignited in 1992 when on my 12th Christmas, my doting parents stumped up the pennies and bought me an Alba HiFi.
Belt-drive Turntable? Check! Twin Cassette Players? Check!Graphic Equalizer with BASS BOOST? Of course!
I have been listening to all kinds of music ever since.
I’m now almost 40 and in those 28 music-infused years I have deepened my relationship with music. I am a guitarist, a DJ, and a dance music producer. Music has punctuated my life in a multitude of joyous ways — as it has for many of you I would expect.
So though I feel I’m (reasonably) qualified to talk about music genres, I find that it can be quite hard to define them and/or differentiate them from one another.
Boundaries that divide genres are fuzzy and the passing of time augments this even more. The Rolling Stones and the Beatles were initially chastised by some as being the work of the devil* yet nowadays are as mainstream as flat-pack furniture.
*Slayer reign supreme for the Devil’s work FYI. \m/
When commercial interests overshadow authenticity (almost always sadly), ‘genres’ can be manufactured. These contrived labels are used by record companies to target groups of customers for commercial advantage, sometimes in ways that reflect deeper flaws in society.
It is evident that genre classification can be subjective, contentious, and maybe even futile — after all, good music is good music, right?
However, I would say there are at least two valid ways to differentiate genres from one another: a song’s musicality and a song’s lyrics.
Is it...
Live or sequenced? (Rock vs. Techno?)
Loud or quiet? (Dubstep vs. Chillout?)
Dissonant or melodic? (Thrash metal vs. Soul?)
Predictable or unexpected? (Pop vs. Jazz?)
Are the lyrics anchored in certain emotions (e.g. sadness, happiness, anger)?
Are the lyrics talking about topics (love, loss, war, injustice, oppression, death)?
For this project, I want to focus specifically on lyrics and the language that songwriters use in their songs.
Qualitatively we all feel that lyrical content varies by genre. But is there a way we can measure this, quantitatively?
There are differences between the lyrics of different genres and we can quantify and measure this!
We will scrape lyrics from Musixmatch.com, a free website that hosts a tonne of accurate lyric content
We will represent lyrics using high dimensional vectors from Google’s Universal Sentence Encoder
We will apply Principal Component Analysis (PCA) to reduce these high dimensional representations to n=1,2,3 dimensions
We will use Plotly and build a combination of simple plots and more sophisticated 2d and 3d scatter plots to see where there are similarities and differences in lyrics
All notebooks and full raw data are available on my GitHub here
In preparation for this project, I discovered that it’s really hard to find an accurate source of lyrics online. Songs are either incomplete or the volume available is less than comprehensive.
Musixmatch.com seems to be one of a few sites that :
Has a lot of content.Is reasonably accurate.
Has a lot of content.
Is reasonably accurate.
So let’s use that as our data source.
Musixmatch have a developer API that we could use to get lyric data but they only allow you to make 2k calls a day and you can only have about 30% of each song’s lyrics to play with.
Let’s get around this by scraping the site using a combination of requests and HTML parsing. This is an ‘out-of-browser’ process so we can easily implement multi-threading to speed the process up. This means we can get more content in a shorter period of time.
I’ve written a Python class below which contains all the methods to extract lyric content for an artist.
All you need to do is to instantiate the class with a Musixmatch artist URL and a genre label...
scraper = MusixmatchScraper('https://www.musixmatch.com/artist/Jack-Johnson','folk')
..and then call the self.Run() method to start the scraper.
Caveat — if you want to scrape a lot of lyrics, you should rotate your IP address where possible. If you make too many requests to Musixmatch.com your IP will be blocked, albeit temporarily. I find you can get away with scraping c.250 songs before this happens.
MusixmatchScraper() is coded in a way that allows you to scrape the content for one artist. If you want to get multiple artists you could create a loop like so:
The class returns a Pandas DataFrame which looks like this:
Great, now that we have our data. Let’s explore the data to see what we have.
Before we start looking at sentence embedding, let’s fire up some simple plots using Plotly.
I generally prefer Plotly visualizations over anything else. They look nicer, are interactive and you can easily curate and share them using Plotly Chart Studio. The only downside is that it can take quite a lot of code (and a lot of nested dictionaries!) to get something useful out of Plotly which is annoying when all you want to do is to quickly explore the data.
One thing I would recommend is updating Plotly to at least 4.8 as Pandas can now use Plotly as the library for backend plotting as opposed to the ‘aesthetically impaired’ Matplotlib.
In the code block below — we can fire up a simple bar chart from Pandas DataFrame just by adding .plot.bar() to a DataFrame object.
Simple as 123,abc!
pd.DataFrame([1,2,3],['a','b','c']).plot.bar()
You can tweak the look and feel of your figure if you want by using the same parameters you’d normally use with a Plotly Graph Objects, so there is that added familiar flexibility.
Ok back to the project...
I decided to get lyrics from a range of genres, some more extreme than others in order to see if we can see differences but I also chose very overlapping genres to see if there are commonalities.
Let’s look at how many songs in each genre we have.
#plot genresfig_genre = pd.DataFrame(df.genre.value_counts()).plot.bar(template='ggplot2')#title parameterstitle_param = dict(text='<b>Count of Genre</b><br></b>', font=dict(size=20))#update layoutfig_genre.update_layout(title=title_param, width=1000, height=500, xaxis = dict(title='Genre'), yaxis = dict(title='Count'))#change the colourfig_genre.update_traces(marker_color='rgb(148, 103, 189)')#show plotfig_genre.show()
Each genre is reasonably well represented — enough to make meaningful comparisons at least.
What about artists by genre?
Let’s go to town with some visualization and create a sunburst map of genre and artist. If you want to interact with the plot, the link to the original plot is in the footnote.
I’ve got a range of bands and artists who I feel represent those genres. You might disagree with me. That’s fine, genre definition can be contentious.
Let’s explore lyric length by genre.
#get lyric frequencies for each songdf['lyric_count'] = df['lyrics'].map(lambda x: len(x.split()))
Hip-hop is a very lyric heavy genre — many of the key descriptive metrics that describe lyric count for hip-hop are different from all other genres.
It will be interesting to see if the content of those lyrics are also different when we analyze the content of those lyrics. Which conveniently leads me to the next part of the EDA...Part of Speech (PoS) analysis.
So the next thing which would be interesting to look at is to understand the content of these lyrics. To do this I will use a spaCy model to classify lyrical content into its relevant parts of speech i.e classifying which words in the lyrics are nouns, verbs, adjectives, and so on. This will enable us to understand a little more about the differences in lyrical content across genres and may allude to where similarities and differences may lie.
import spacy#load spacy modelnlp = spacy.load('en_core_web_sm')def pos(string,pos): """Returns any token that qualifies as a specific part of speech""" doc = nlp(string) #fit model return ' '.join(list(set([i.text for i in doc if i.pos_ == pos]))) #return any tokens that qualify
Let’s call the function above in a loop and get new columns containing all the useful parts of speech.
#get nounspos_of_interest = ['NOUNS','VERBS','ADJ','ADV]#loop through each PoSfor pos in pos_of_interest: df[pos] = df.lyrics.map(lambda x: pos(x,pos))
Below is a function that will count the most common tokens in a string. We can use this to analyze the most common words in a song— including the PoS we have just made.
#call the function on one grammusixmatch_mostcommon(df.lyrics,token=1).head(10)
It will be more useful to find a way to use this function across all genres and by different parts of speech. An effective way to do this is to use Treemap visualizations. Plotly has a good template for this, so I’ve built a function that can do this for us.
Let’s call the function and look at the output
noun_treemap = musixmatch_genremap(df,pos='nouns')
WARNING — some of these lyrics are explicit
If you’re on a desktop I would strongly recommend you visit the link in the treemap footnote (above) in order to interact with it.
Now we get to the really fun part — using vectors to represent our lyrics. We can then use various techniques that can show us which vectors/lyrics are similar or different.
Vector representations of words were a significant step-change for natural language processing. Early methods that attempted to ‘understand’ language usually involved counting words (e.g. a bag of words model or weighted models / TFIDF approaches). These were limited in that they failed to capture the context of language. After all, the sentence ‘kid breaks skateboard’ is very different in meaning to ‘skateboard breaks kid’ ....despite having the same type and number of words.
Word2vec by Tomas Mikolov et al. was game-changer in that words were no longer rudimentarily represented as counts but as high-dimensional vectors. These vectors, or embeddings, were created through the training of a simple neural network on a corpus of text. These word embeddings represent a word’s relationship with a neighboring word and therefore its context. Therefore the vectors for the word ‘walking’ and ‘walked’ would be more similar than the words ‘swimming’ and ‘swam’.
If you want to learn more about this I would recommend reading the original whitepaper or a previous project I did with ASOS review on TrustPilot.
For this project, we will be using Google’s Universal Sentence Encoder, a state of the art encoder that has been trained on millions (possibly billions?) of documents.
It’s like word2vec but on steroids.
The Universal Sentence Encoder encodes text into high dimensional vectors that can be used for text classification, semantic similarity, clustering and other natural language tasks.
The model is trained and optimized for greater-than-word length text, such as sentences, phrases or short paragraphs. It is trained on a variety of data sources and a variety of tasks with the aim of dynamically accommodating a wide variety of natural language understanding tasks.
Source: https://tfhub.dev/google/universal-sentence-encoder/4
If you want to find out more about this model, I would strongly recommend you read the documentation on TensorFlow hub as it covers a lot more detail.
Let’s use Tensorflow Hub to load the model..
#get universal sentence encoderUSE = hub.load("https://tfhub.dev/google/universal-sentence-encoder/4")
And let’s write a short function that can get a high dimensional vector for any string input using the model.
def getUSEEmbed(_string,USE = USE): """Function takes a string argument and returns its high dimensional vector from USE""" return np.array(USE([_string])[0])
Let’s get the vector for a simple sentence....
example = getUSEEmbed('Hello how are you?')
As you can see a simple sentence has now been encoded as a high dimensional vector with a shape of (512,)
The cornerstone of this project is to find a way to find similarities and differences in song lyrics. As we are encoding lyrics into vector representations then we need to use techniques that allow us find similarities and differences in vectors
We can do this by:
Using cosine similarityDimension reduction and visualization (using something like Principal Component Analysis)
Using cosine similarity
Dimension reduction and visualization (using something like Principal Component Analysis)
Often when we have continuous, low dimensional data we would use something like Euclidean distance to gauge similarity/difference. We would use this distance metric with something like a KNN classifier or even when clustering dimensionally reduced vectors such as after a PCA.
However, because our vectors from the sentence encoder have very high dimensionality then using cosine similarity is a better proximity metric to use than Euclidean distance, to begin with at least.
A cosine similarity closer to 1 would mean there is minimal variance between the two vectors (the input strings are similar) whereas a cosine similarity closer to 0 would mean that two vectors are very different (the input stings are different)
Let me show you an example with four sentences.
Two of which are about weather..
“The weather is going to be really warm today”
“Today is going to be the sunniest day of the year”
And another two that are about breakfast
“I like my eggs sunny side up”
“Breakfast is my favourite meal”
I’ve specifically chosen examples where the word ‘sunny’/’sunniest’ has been used as a metaphor and as an adjective. Let’s see if the encoding can capture this difference.
#some example sentencesexample_sentences = ["The weather is going to be really warm today", "Today is going to be the sunniest day of the year", "I like my eggs sunny side up", "Breakfast is my favourite meal"]#get embeddings for each example sentenceembed = [getUSEEmbed(i) for i in example_sentences]#set up a dictionary where each sentece is a key and its value is its 512 vector embeddingdic_ = dict(zip(example_sentences,embed))#let's find all the unique pairwise sentence combinationscombo = [list(i) for i in itertools.combinations(example_sentences, 2)]
Now we need a function to calculate similarity.
def cosineSimilarity(vec_x,vec_y): """Function returns pairwise cosine similarity of two vector arguments""" return cosine_similarity([vec_x],[vec_y])[0][0]
Let’s make a DataFrame that maps the cosine similarity for each unique sentence pair.
#empty list for datacs = []#lop through each unique sentence pairingfor i in range(len(combo)): #get cosine similarity for each cs_ = cosineSimilarity(dic_[combo[i][0]],dic_[combo[i][1]]) #append data to list cs.append((combo[i][0],combo[i][1],cs_))#construct DataFramecs_df = pd.DataFrame(cs,columns['sent_1','sent_2','cosine_similarity']).\ sort_values(by='cosine_similarity',ascending=False)
Let’s inspect the DataFrame.
This is so cool. The sentences that are most similar have more similar vectors (cosine similarity of 0.41 / 0.51). Even with the ambiguity of using a word that functions as a metaphor and an adjective, the encoding is sufficiently differentiated. Let’s see if we can apply this with our song lyrics.
First, we need to get the vectors for each song.
#get USE embeddings for each songdf_embed = pd.DataFrame([getUSEEmbed(df.lyrics[i]) for i in range(df.shape[0])],\ index=[df.song[i] for i in range(df.shape[0])])
Inspect the DataFrame with df_embed.head(5)
Let’s use another data reduction technique — Principal Component Analysis, to reduce the dimensionality of these embeddings whilst retaining as much variance as possible.
I’ve built a comprehensive function to do this.
Let’s call this function and get three new DataFrames.
pc_1 = musixmatch_PCA(df,df_embed,n_components=1)pc_2 = musixmatch_PCA(df,df_embed,n_components=2)pc_3 = musixmatch_PCA(df,df_embed,n_components=3)
Let’s do some grouping to explore which artists have lyrics that are most similar to each other.
As we can see — even with just one component, artists from genres tend to cluster together. Death metal, heavy metal, and rock differ slightly from one another but vastly different to pop and soul. This makes sense.
If you are familiar with these bands as you scroll down you will get a strong sense of how genres evolve and that we can see this in the variance across principal component 1.
Let’s look at the same analysis but grouped by genre.
This averaged view confirms what we suspected above.
Let’s make a more sophisticated visualization that uses scatter plots to show this data, by song.
We can look at this in two dimensions (PC1,PC2) but also in three dimensions (PC1,PC2,PC3)
The function below combines a few functions from above with some more complex Plotly functions to generate scatter plots, either in 2d (PC1 / PC2) or in 3D (PC1 / PC2 / PC3)
Let’s call the function and see what the plot looks like. Again, I would strongly recommend you click on the plot link in the footer for the screengrab below if you want to interact with all the genres and where they lie on the plot.
scatPlot_2 = musixmatch_scatplot(df,df_embed,n_components=2)
We can also create a similar plot but utilize the 3 dimensions of the PCA.
scatPlot_3 = musixmatch_scatplot(df,df_embed,n_components=3)
We have shown that lyrics from different music genres do vary although what is interesting is that there is quite a clear relationship between lyrical content as we move from one genre to another in a stepwise fashion. I think the visualization below quite clearly brings this to life.
The lyrics of different genres aren’t entirely mutually exclusive — unless you compare the extremes. i.e. there is a huge difference between death metal and soul/r&b but little in the way to differentiate pop and pop/rock.
These findings reflect the true nature of music in that music genres are fluid and that for each genre, there is likely to be a ‘neighbouring’ genre that is similar in its lyrical content.
After all, many fans of r&b/soul will also like pop.....but maybe not punk and/or metal?
We have shown that universal sentence encoding/transfer learning is a very powerful and incredibly easy technique that can be used to pull out the differences and similarities in song lyrics across genres.
Its applications on other problems are numerous:
Song/lyric recommender systems — using similarity metrics to find songs with similar lyrics
Segmenting large volumes of text by finding similar documents e.g. emails, customer feedback/reviews
Identifying plagiarism
To be used as features for classification tasks
Thanks for reading and get in touch if you want to talk further! I’ve saved my notebook on my GitHub with all the code ready to go and be used in other projects. Let me know if you do, I’d love to see.
Sam
[1] GitHub (containing Jupyter notebook): https://github.com/kitsamho/songlyrics_univeral_sentence_encoder
[2] Beautiful Soup : https://www.crummy.com/software/BeautifulSoup/bs4/doc/
[3] Google Universal Sentence Encoder: https://tfhub.dev/google/universal-sentence-encoder/4
[4] Plotly: https://plot.ly/python/
[5] Musixmatch.com: https://www.musixmatch.com/
|
[
{
"code": null,
"e": 198,
"s": 47,
"text": "My enduring love affair with music was ignited in 1992 when on my 12th Christmas, my doting parents stumped up the pennies and bought me an Alba HiFi."
},
{
"code": null,
"e": 302,
"s": 198,
"text": "Belt-drive Turntable? Check! Twin Cassette Players? Check!Graphic Equalizer with BASS BOOST? Of course!"
},
{
"code": null,
"e": 358,
"s": 302,
"text": "I have been listening to all kinds of music ever since."
},
{
"code": null,
"e": 611,
"s": 358,
"text": "I’m now almost 40 and in those 28 music-infused years I have deepened my relationship with music. I am a guitarist, a DJ, and a dance music producer. Music has punctuated my life in a multitude of joyous ways — as it has for many of you I would expect."
},
{
"code": null,
"e": 775,
"s": 611,
"text": "So though I feel I’m (reasonably) qualified to talk about music genres, I find that it can be quite hard to define them and/or differentiate them from one another."
},
{
"code": null,
"e": 1019,
"s": 775,
"text": "Boundaries that divide genres are fuzzy and the passing of time augments this even more. The Rolling Stones and the Beatles were initially chastised by some as being the work of the devil* yet nowadays are as mainstream as flat-pack furniture."
},
{
"code": null,
"e": 1071,
"s": 1019,
"text": "*Slayer reign supreme for the Devil’s work FYI. \\m/"
},
{
"code": null,
"e": 1338,
"s": 1071,
"text": "When commercial interests overshadow authenticity (almost always sadly), ‘genres’ can be manufactured. These contrived labels are used by record companies to target groups of customers for commercial advantage, sometimes in ways that reflect deeper flaws in society."
},
{
"code": null,
"e": 1478,
"s": 1338,
"text": "It is evident that genre classification can be subjective, contentious, and maybe even futile — after all, good music is good music, right?"
},
{
"code": null,
"e": 1616,
"s": 1478,
"text": "However, I would say there are at least two valid ways to differentiate genres from one another: a song’s musicality and a song’s lyrics."
},
{
"code": null,
"e": 1625,
"s": 1616,
"text": "Is it..."
},
{
"code": null,
"e": 1663,
"s": 1625,
"text": "Live or sequenced? (Rock vs. Techno?)"
},
{
"code": null,
"e": 1702,
"s": 1663,
"text": "Loud or quiet? (Dubstep vs. Chillout?)"
},
{
"code": null,
"e": 1749,
"s": 1702,
"text": "Dissonant or melodic? (Thrash metal vs. Soul?)"
},
{
"code": null,
"e": 1792,
"s": 1749,
"text": "Predictable or unexpected? (Pop vs. Jazz?)"
},
{
"code": null,
"e": 1870,
"s": 1792,
"text": "Are the lyrics anchored in certain emotions (e.g. sadness, happiness, anger)?"
},
{
"code": null,
"e": 1955,
"s": 1870,
"text": "Are the lyrics talking about topics (love, loss, war, injustice, oppression, death)?"
},
{
"code": null,
"e": 2066,
"s": 1955,
"text": "For this project, I want to focus specifically on lyrics and the language that songwriters use in their songs."
},
{
"code": null,
"e": 2186,
"s": 2066,
"text": "Qualitatively we all feel that lyrical content varies by genre. But is there a way we can measure this, quantitatively?"
},
{
"code": null,
"e": 2285,
"s": 2186,
"text": "There are differences between the lyrics of different genres and we can quantify and measure this!"
},
{
"code": null,
"e": 2388,
"s": 2285,
"text": "We will scrape lyrics from Musixmatch.com, a free website that hosts a tonne of accurate lyric content"
},
{
"code": null,
"e": 2485,
"s": 2388,
"text": "We will represent lyrics using high dimensional vectors from Google’s Universal Sentence Encoder"
},
{
"code": null,
"e": 2605,
"s": 2485,
"text": "We will apply Principal Component Analysis (PCA) to reduce these high dimensional representations to n=1,2,3 dimensions"
},
{
"code": null,
"e": 2773,
"s": 2605,
"text": "We will use Plotly and build a combination of simple plots and more sophisticated 2d and 3d scatter plots to see where there are similarities and differences in lyrics"
},
{
"code": null,
"e": 2837,
"s": 2773,
"text": "All notebooks and full raw data are available on my GitHub here"
},
{
"code": null,
"e": 3030,
"s": 2837,
"text": "In preparation for this project, I discovered that it’s really hard to find an accurate source of lyrics online. Songs are either incomplete or the volume available is less than comprehensive."
},
{
"code": null,
"e": 3083,
"s": 3030,
"text": "Musixmatch.com seems to be one of a few sites that :"
},
{
"code": null,
"e": 3128,
"s": 3083,
"text": "Has a lot of content.Is reasonably accurate."
},
{
"code": null,
"e": 3150,
"s": 3128,
"text": "Has a lot of content."
},
{
"code": null,
"e": 3174,
"s": 3150,
"text": "Is reasonably accurate."
},
{
"code": null,
"e": 3212,
"s": 3174,
"text": "So let’s use that as our data source."
},
{
"code": null,
"e": 3395,
"s": 3212,
"text": "Musixmatch have a developer API that we could use to get lyric data but they only allow you to make 2k calls a day and you can only have about 30% of each song’s lyrics to play with."
},
{
"code": null,
"e": 3656,
"s": 3395,
"text": "Let’s get around this by scraping the site using a combination of requests and HTML parsing. This is an ‘out-of-browser’ process so we can easily implement multi-threading to speed the process up. This means we can get more content in a shorter period of time."
},
{
"code": null,
"e": 3761,
"s": 3656,
"text": "I’ve written a Python class below which contains all the methods to extract lyric content for an artist."
},
{
"code": null,
"e": 3858,
"s": 3761,
"text": "All you need to do is to instantiate the class with a Musixmatch artist URL and a genre label..."
},
{
"code": null,
"e": 3943,
"s": 3858,
"text": "scraper = MusixmatchScraper('https://www.musixmatch.com/artist/Jack-Johnson','folk')"
},
{
"code": null,
"e": 4003,
"s": 3943,
"text": "..and then call the self.Run() method to start the scraper."
},
{
"code": null,
"e": 4265,
"s": 4003,
"text": "Caveat — if you want to scrape a lot of lyrics, you should rotate your IP address where possible. If you make too many requests to Musixmatch.com your IP will be blocked, albeit temporarily. I find you can get away with scraping c.250 songs before this happens."
},
{
"code": null,
"e": 4426,
"s": 4265,
"text": "MusixmatchScraper() is coded in a way that allows you to scrape the content for one artist. If you want to get multiple artists you could create a loop like so:"
},
{
"code": null,
"e": 4486,
"s": 4426,
"text": "The class returns a Pandas DataFrame which looks like this:"
},
{
"code": null,
"e": 4564,
"s": 4486,
"text": "Great, now that we have our data. Let’s explore the data to see what we have."
},
{
"code": null,
"e": 4657,
"s": 4564,
"text": "Before we start looking at sentence embedding, let’s fire up some simple plots using Plotly."
},
{
"code": null,
"e": 5025,
"s": 4657,
"text": "I generally prefer Plotly visualizations over anything else. They look nicer, are interactive and you can easily curate and share them using Plotly Chart Studio. The only downside is that it can take quite a lot of code (and a lot of nested dictionaries!) to get something useful out of Plotly which is annoying when all you want to do is to quickly explore the data."
},
{
"code": null,
"e": 5208,
"s": 5025,
"text": "One thing I would recommend is updating Plotly to at least 4.8 as Pandas can now use Plotly as the library for backend plotting as opposed to the ‘aesthetically impaired’ Matplotlib."
},
{
"code": null,
"e": 5340,
"s": 5208,
"text": "In the code block below — we can fire up a simple bar chart from Pandas DataFrame just by adding .plot.bar() to a DataFrame object."
},
{
"code": null,
"e": 5359,
"s": 5340,
"text": "Simple as 123,abc!"
},
{
"code": null,
"e": 5406,
"s": 5359,
"text": "pd.DataFrame([1,2,3],['a','b','c']).plot.bar()"
},
{
"code": null,
"e": 5587,
"s": 5406,
"text": "You can tweak the look and feel of your figure if you want by using the same parameters you’d normally use with a Plotly Graph Objects, so there is that added familiar flexibility."
},
{
"code": null,
"e": 5613,
"s": 5587,
"text": "Ok back to the project..."
},
{
"code": null,
"e": 5809,
"s": 5613,
"text": "I decided to get lyrics from a range of genres, some more extreme than others in order to see if we can see differences but I also chose very overlapping genres to see if there are commonalities."
},
{
"code": null,
"e": 5861,
"s": 5809,
"text": "Let’s look at how many songs in each genre we have."
},
{
"code": null,
"e": 6385,
"s": 5861,
"text": "#plot genresfig_genre = pd.DataFrame(df.genre.value_counts()).plot.bar(template='ggplot2')#title parameterstitle_param = dict(text='<b>Count of Genre</b><br></b>', font=dict(size=20))#update layoutfig_genre.update_layout(title=title_param, width=1000, height=500, xaxis = dict(title='Genre'), yaxis = dict(title='Count'))#change the colourfig_genre.update_traces(marker_color='rgb(148, 103, 189)')#show plotfig_genre.show()"
},
{
"code": null,
"e": 6477,
"s": 6385,
"text": "Each genre is reasonably well represented — enough to make meaningful comparisons at least."
},
{
"code": null,
"e": 6506,
"s": 6477,
"text": "What about artists by genre?"
},
{
"code": null,
"e": 6683,
"s": 6506,
"text": "Let’s go to town with some visualization and create a sunburst map of genre and artist. If you want to interact with the plot, the link to the original plot is in the footnote."
},
{
"code": null,
"e": 6834,
"s": 6683,
"text": "I’ve got a range of bands and artists who I feel represent those genres. You might disagree with me. That’s fine, genre definition can be contentious."
},
{
"code": null,
"e": 6871,
"s": 6834,
"text": "Let’s explore lyric length by genre."
},
{
"code": null,
"e": 6970,
"s": 6871,
"text": "#get lyric frequencies for each songdf['lyric_count'] = df['lyrics'].map(lambda x: len(x.split()))"
},
{
"code": null,
"e": 7119,
"s": 6970,
"text": "Hip-hop is a very lyric heavy genre — many of the key descriptive metrics that describe lyric count for hip-hop are different from all other genres."
},
{
"code": null,
"e": 7333,
"s": 7119,
"text": "It will be interesting to see if the content of those lyrics are also different when we analyze the content of those lyrics. Which conveniently leads me to the next part of the EDA...Part of Speech (PoS) analysis."
},
{
"code": null,
"e": 7781,
"s": 7333,
"text": "So the next thing which would be interesting to look at is to understand the content of these lyrics. To do this I will use a spaCy model to classify lyrical content into its relevant parts of speech i.e classifying which words in the lyrics are nouns, verbs, adjectives, and so on. This will enable us to understand a little more about the differences in lyrical content across genres and may allude to where similarities and differences may lie."
},
{
"code": null,
"e": 8082,
"s": 7781,
"text": "import spacy#load spacy modelnlp = spacy.load('en_core_web_sm')def pos(string,pos): \"\"\"Returns any token that qualifies as a specific part of speech\"\"\" doc = nlp(string) #fit model return ' '.join(list(set([i.text for i in doc if i.pos_ == pos]))) #return any tokens that qualify"
},
{
"code": null,
"e": 8185,
"s": 8082,
"text": "Let’s call the function above in a loop and get new columns containing all the useful parts of speech."
},
{
"code": null,
"e": 8342,
"s": 8185,
"text": "#get nounspos_of_interest = ['NOUNS','VERBS','ADJ','ADV]#loop through each PoSfor pos in pos_of_interest: df[pos] = df.lyrics.map(lambda x: pos(x,pos))"
},
{
"code": null,
"e": 8511,
"s": 8342,
"text": "Below is a function that will count the most common tokens in a string. We can use this to analyze the most common words in a song— including the PoS we have just made."
},
{
"code": null,
"e": 8591,
"s": 8511,
"text": "#call the function on one grammusixmatch_mostcommon(df.lyrics,token=1).head(10)"
},
{
"code": null,
"e": 8850,
"s": 8591,
"text": "It will be more useful to find a way to use this function across all genres and by different parts of speech. An effective way to do this is to use Treemap visualizations. Plotly has a good template for this, so I’ve built a function that can do this for us."
},
{
"code": null,
"e": 8897,
"s": 8850,
"text": "Let’s call the function and look at the output"
},
{
"code": null,
"e": 8948,
"s": 8897,
"text": "noun_treemap = musixmatch_genremap(df,pos='nouns')"
},
{
"code": null,
"e": 8992,
"s": 8948,
"text": "WARNING — some of these lyrics are explicit"
},
{
"code": null,
"e": 9123,
"s": 8992,
"text": "If you’re on a desktop I would strongly recommend you visit the link in the treemap footnote (above) in order to interact with it."
},
{
"code": null,
"e": 9297,
"s": 9123,
"text": "Now we get to the really fun part — using vectors to represent our lyrics. We can then use various techniques that can show us which vectors/lyrics are similar or different."
},
{
"code": null,
"e": 9779,
"s": 9297,
"text": "Vector representations of words were a significant step-change for natural language processing. Early methods that attempted to ‘understand’ language usually involved counting words (e.g. a bag of words model or weighted models / TFIDF approaches). These were limited in that they failed to capture the context of language. After all, the sentence ‘kid breaks skateboard’ is very different in meaning to ‘skateboard breaks kid’ ....despite having the same type and number of words."
},
{
"code": null,
"e": 10262,
"s": 9779,
"text": "Word2vec by Tomas Mikolov et al. was game-changer in that words were no longer rudimentarily represented as counts but as high-dimensional vectors. These vectors, or embeddings, were created through the training of a simple neural network on a corpus of text. These word embeddings represent a word’s relationship with a neighboring word and therefore its context. Therefore the vectors for the word ‘walking’ and ‘walked’ would be more similar than the words ‘swimming’ and ‘swam’."
},
{
"code": null,
"e": 10409,
"s": 10262,
"text": "If you want to learn more about this I would recommend reading the original whitepaper or a previous project I did with ASOS review on TrustPilot."
},
{
"code": null,
"e": 10577,
"s": 10409,
"text": "For this project, we will be using Google’s Universal Sentence Encoder, a state of the art encoder that has been trained on millions (possibly billions?) of documents."
},
{
"code": null,
"e": 10613,
"s": 10577,
"text": "It’s like word2vec but on steroids."
},
{
"code": null,
"e": 10795,
"s": 10613,
"text": "The Universal Sentence Encoder encodes text into high dimensional vectors that can be used for text classification, semantic similarity, clustering and other natural language tasks."
},
{
"code": null,
"e": 11077,
"s": 10795,
"text": "The model is trained and optimized for greater-than-word length text, such as sentences, phrases or short paragraphs. It is trained on a variety of data sources and a variety of tasks with the aim of dynamically accommodating a wide variety of natural language understanding tasks."
},
{
"code": null,
"e": 11139,
"s": 11077,
"text": "Source: https://tfhub.dev/google/universal-sentence-encoder/4"
},
{
"code": null,
"e": 11290,
"s": 11139,
"text": "If you want to find out more about this model, I would strongly recommend you read the documentation on TensorFlow hub as it covers a lot more detail."
},
{
"code": null,
"e": 11335,
"s": 11290,
"text": "Let’s use Tensorflow Hub to load the model.."
},
{
"code": null,
"e": 11438,
"s": 11335,
"text": "#get universal sentence encoderUSE = hub.load(\"https://tfhub.dev/google/universal-sentence-encoder/4\")"
},
{
"code": null,
"e": 11548,
"s": 11438,
"text": "And let’s write a short function that can get a high dimensional vector for any string input using the model."
},
{
"code": null,
"e": 11721,
"s": 11548,
"text": "def getUSEEmbed(_string,USE = USE): \"\"\"Function takes a string argument and returns its high dimensional vector from USE\"\"\" return np.array(USE([_string])[0])"
},
{
"code": null,
"e": 11768,
"s": 11721,
"text": "Let’s get the vector for a simple sentence...."
},
{
"code": null,
"e": 11812,
"s": 11768,
"text": "example = getUSEEmbed('Hello how are you?')"
},
{
"code": null,
"e": 11918,
"s": 11812,
"text": "As you can see a simple sentence has now been encoded as a high dimensional vector with a shape of (512,)"
},
{
"code": null,
"e": 12164,
"s": 11918,
"text": "The cornerstone of this project is to find a way to find similarities and differences in song lyrics. As we are encoding lyrics into vector representations then we need to use techniques that allow us find similarities and differences in vectors"
},
{
"code": null,
"e": 12183,
"s": 12164,
"text": "We can do this by:"
},
{
"code": null,
"e": 12296,
"s": 12183,
"text": "Using cosine similarityDimension reduction and visualization (using something like Principal Component Analysis)"
},
{
"code": null,
"e": 12320,
"s": 12296,
"text": "Using cosine similarity"
},
{
"code": null,
"e": 12410,
"s": 12320,
"text": "Dimension reduction and visualization (using something like Principal Component Analysis)"
},
{
"code": null,
"e": 12687,
"s": 12410,
"text": "Often when we have continuous, low dimensional data we would use something like Euclidean distance to gauge similarity/difference. We would use this distance metric with something like a KNN classifier or even when clustering dimensionally reduced vectors such as after a PCA."
},
{
"code": null,
"e": 12886,
"s": 12687,
"text": "However, because our vectors from the sentence encoder have very high dimensionality then using cosine similarity is a better proximity metric to use than Euclidean distance, to begin with at least."
},
{
"code": null,
"e": 13131,
"s": 12886,
"text": "A cosine similarity closer to 1 would mean there is minimal variance between the two vectors (the input strings are similar) whereas a cosine similarity closer to 0 would mean that two vectors are very different (the input stings are different)"
},
{
"code": null,
"e": 13179,
"s": 13131,
"text": "Let me show you an example with four sentences."
},
{
"code": null,
"e": 13212,
"s": 13179,
"text": "Two of which are about weather.."
},
{
"code": null,
"e": 13259,
"s": 13212,
"text": "“The weather is going to be really warm today”"
},
{
"code": null,
"e": 13311,
"s": 13259,
"text": "“Today is going to be the sunniest day of the year”"
},
{
"code": null,
"e": 13352,
"s": 13311,
"text": "And another two that are about breakfast"
},
{
"code": null,
"e": 13383,
"s": 13352,
"text": "“I like my eggs sunny side up”"
},
{
"code": null,
"e": 13416,
"s": 13383,
"text": "“Breakfast is my favourite meal”"
},
{
"code": null,
"e": 13588,
"s": 13416,
"text": "I’ve specifically chosen examples where the word ‘sunny’/’sunniest’ has been used as a metaphor and as an adjective. Let’s see if the encoding can capture this difference."
},
{
"code": null,
"e": 14273,
"s": 13588,
"text": "#some example sentencesexample_sentences = [\"The weather is going to be really warm today\", \"Today is going to be the sunniest day of the year\", \"I like my eggs sunny side up\", \"Breakfast is my favourite meal\"]#get embeddings for each example sentenceembed = [getUSEEmbed(i) for i in example_sentences]#set up a dictionary where each sentece is a key and its value is its 512 vector embeddingdic_ = dict(zip(example_sentences,embed))#let's find all the unique pairwise sentence combinationscombo = [list(i) for i in itertools.combinations(example_sentences, 2)]"
},
{
"code": null,
"e": 14321,
"s": 14273,
"text": "Now we need a function to calculate similarity."
},
{
"code": null,
"e": 14492,
"s": 14321,
"text": "def cosineSimilarity(vec_x,vec_y): \"\"\"Function returns pairwise cosine similarity of two vector arguments\"\"\" return cosine_similarity([vec_x],[vec_y])[0][0]"
},
{
"code": null,
"e": 14578,
"s": 14492,
"text": "Let’s make a DataFrame that maps the cosine similarity for each unique sentence pair."
},
{
"code": null,
"e": 15012,
"s": 14578,
"text": "#empty list for datacs = []#lop through each unique sentence pairingfor i in range(len(combo)): #get cosine similarity for each cs_ = cosineSimilarity(dic_[combo[i][0]],dic_[combo[i][1]]) #append data to list cs.append((combo[i][0],combo[i][1],cs_))#construct DataFramecs_df = pd.DataFrame(cs,columns['sent_1','sent_2','cosine_similarity']).\\ sort_values(by='cosine_similarity',ascending=False)"
},
{
"code": null,
"e": 15041,
"s": 15012,
"text": "Let’s inspect the DataFrame."
},
{
"code": null,
"e": 15341,
"s": 15041,
"text": "This is so cool. The sentences that are most similar have more similar vectors (cosine similarity of 0.41 / 0.51). Even with the ambiguity of using a word that functions as a metaphor and an adjective, the encoding is sufficiently differentiated. Let’s see if we can apply this with our song lyrics."
},
{
"code": null,
"e": 15390,
"s": 15341,
"text": "First, we need to get the vectors for each song."
},
{
"code": null,
"e": 15576,
"s": 15390,
"text": "#get USE embeddings for each songdf_embed = pd.DataFrame([getUSEEmbed(df.lyrics[i]) for i in range(df.shape[0])],\\ index=[df.song[i] for i in range(df.shape[0])])"
},
{
"code": null,
"e": 15620,
"s": 15576,
"text": "Inspect the DataFrame with df_embed.head(5)"
},
{
"code": null,
"e": 15791,
"s": 15620,
"text": "Let’s use another data reduction technique — Principal Component Analysis, to reduce the dimensionality of these embeddings whilst retaining as much variance as possible."
},
{
"code": null,
"e": 15839,
"s": 15791,
"text": "I’ve built a comprehensive function to do this."
},
{
"code": null,
"e": 15894,
"s": 15839,
"text": "Let’s call this function and get three new DataFrames."
},
{
"code": null,
"e": 16042,
"s": 15894,
"text": "pc_1 = musixmatch_PCA(df,df_embed,n_components=1)pc_2 = musixmatch_PCA(df,df_embed,n_components=2)pc_3 = musixmatch_PCA(df,df_embed,n_components=3)"
},
{
"code": null,
"e": 16139,
"s": 16042,
"text": "Let’s do some grouping to explore which artists have lyrics that are most similar to each other."
},
{
"code": null,
"e": 16355,
"s": 16139,
"text": "As we can see — even with just one component, artists from genres tend to cluster together. Death metal, heavy metal, and rock differ slightly from one another but vastly different to pop and soul. This makes sense."
},
{
"code": null,
"e": 16531,
"s": 16355,
"text": "If you are familiar with these bands as you scroll down you will get a strong sense of how genres evolve and that we can see this in the variance across principal component 1."
},
{
"code": null,
"e": 16585,
"s": 16531,
"text": "Let’s look at the same analysis but grouped by genre."
},
{
"code": null,
"e": 16638,
"s": 16585,
"text": "This averaged view confirms what we suspected above."
},
{
"code": null,
"e": 16736,
"s": 16638,
"text": "Let’s make a more sophisticated visualization that uses scatter plots to show this data, by song."
},
{
"code": null,
"e": 16827,
"s": 16736,
"text": "We can look at this in two dimensions (PC1,PC2) but also in three dimensions (PC1,PC2,PC3)"
},
{
"code": null,
"e": 17001,
"s": 16827,
"text": "The function below combines a few functions from above with some more complex Plotly functions to generate scatter plots, either in 2d (PC1 / PC2) or in 3D (PC1 / PC2 / PC3)"
},
{
"code": null,
"e": 17235,
"s": 17001,
"text": "Let’s call the function and see what the plot looks like. Again, I would strongly recommend you click on the plot link in the footer for the screengrab below if you want to interact with all the genres and where they lie on the plot."
},
{
"code": null,
"e": 17296,
"s": 17235,
"text": "scatPlot_2 = musixmatch_scatplot(df,df_embed,n_components=2)"
},
{
"code": null,
"e": 17371,
"s": 17296,
"text": "We can also create a similar plot but utilize the 3 dimensions of the PCA."
},
{
"code": null,
"e": 17432,
"s": 17371,
"text": "scatPlot_3 = musixmatch_scatplot(df,df_embed,n_components=3)"
},
{
"code": null,
"e": 17718,
"s": 17432,
"text": "We have shown that lyrics from different music genres do vary although what is interesting is that there is quite a clear relationship between lyrical content as we move from one genre to another in a stepwise fashion. I think the visualization below quite clearly brings this to life."
},
{
"code": null,
"e": 17941,
"s": 17718,
"text": "The lyrics of different genres aren’t entirely mutually exclusive — unless you compare the extremes. i.e. there is a huge difference between death metal and soul/r&b but little in the way to differentiate pop and pop/rock."
},
{
"code": null,
"e": 18130,
"s": 17941,
"text": "These findings reflect the true nature of music in that music genres are fluid and that for each genre, there is likely to be a ‘neighbouring’ genre that is similar in its lyrical content."
},
{
"code": null,
"e": 18219,
"s": 18130,
"text": "After all, many fans of r&b/soul will also like pop.....but maybe not punk and/or metal?"
},
{
"code": null,
"e": 18425,
"s": 18219,
"text": "We have shown that universal sentence encoding/transfer learning is a very powerful and incredibly easy technique that can be used to pull out the differences and similarities in song lyrics across genres."
},
{
"code": null,
"e": 18474,
"s": 18425,
"text": "Its applications on other problems are numerous:"
},
{
"code": null,
"e": 18566,
"s": 18474,
"text": "Song/lyric recommender systems — using similarity metrics to find songs with similar lyrics"
},
{
"code": null,
"e": 18667,
"s": 18566,
"text": "Segmenting large volumes of text by finding similar documents e.g. emails, customer feedback/reviews"
},
{
"code": null,
"e": 18690,
"s": 18667,
"text": "Identifying plagiarism"
},
{
"code": null,
"e": 18738,
"s": 18690,
"text": "To be used as features for classification tasks"
},
{
"code": null,
"e": 18940,
"s": 18738,
"text": "Thanks for reading and get in touch if you want to talk further! I’ve saved my notebook on my GitHub with all the code ready to go and be used in other projects. Let me know if you do, I’d love to see."
},
{
"code": null,
"e": 18944,
"s": 18940,
"text": "Sam"
},
{
"code": null,
"e": 19051,
"s": 18944,
"text": "[1] GitHub (containing Jupyter notebook): https://github.com/kitsamho/songlyrics_univeral_sentence_encoder"
},
{
"code": null,
"e": 19127,
"s": 19051,
"text": "[2] Beautiful Soup : https://www.crummy.com/software/BeautifulSoup/bs4/doc/"
},
{
"code": null,
"e": 19220,
"s": 19127,
"text": "[3] Google Universal Sentence Encoder: https://tfhub.dev/google/universal-sentence-encoder/4"
},
{
"code": null,
"e": 19256,
"s": 19220,
"text": "[4] Plotly: https://plot.ly/python/"
}
] |
SAP Payroll - Indirect Evaluation
|
Indirect Evaluation is used to calculate payroll for some specific wage types that are defaulted under the Basic Pay Infotype (0008) or Infotype 0014 or 001 (recurring payment/deductions or Additional payments).
Note − While using indirect evaluation, it is also possible to calculate INVAL as numbers instead of using value as amount considering the wage type configured correctly.
For example − You can configure INVAL for an employee to be eligible for 10 liters of petrol each month. This represents INVAL as number.
There are quite a few types of variants for indirect evaluation, which are −
Variant A − This is used to calculate the wage type value as a fixed amount.
Variant A − This is used to calculate the wage type value as a fixed amount.
Variant B − This is used to calculate the amount as percentage of the base wage type added to a fixed amount. In this, multiple amounts with same or different percentage of the base wage type, can be calculated for an INVAL wage type. In this case, the amount that will be Indirectly Evaluated will be the sum of all such calculated amounts added to a fixed amount.
Variant B − This is used to calculate the amount as percentage of the base wage type added to a fixed amount. In this, multiple amounts with same or different percentage of the base wage type, can be calculated for an INVAL wage type. In this case, the amount that will be Indirectly Evaluated will be the sum of all such calculated amounts added to a fixed amount.
For example − Wage type M230, consider the following different INVAL B amounts.
10% of MB10
30% of M220
Fixed amount of Rs.1000
So in this scenario, wage type M230 will have INVAL amount as sum of a, b and c.
Variant C − This is used to calculate the amount as a percentage of a base wage type subject to a maximum limit. More than one such amount, with same or different percentage of the base wage type, can be calculated for an INVAL wage type. In this case, the amount that will be Indirectly Evaluated will be the sum of all such calculated amounts, subject to a maximum limit.
Variant C − This is used to calculate the amount as a percentage of a base wage type subject to a maximum limit. More than one such amount, with same or different percentage of the base wage type, can be calculated for an INVAL wage type. In this case, the amount that will be Indirectly Evaluated will be the sum of all such calculated amounts, subject to a maximum limit.
For example − Wage type M230, consider the following different INVAL C amounts.
15% of MB10
20% of M220
Limit of Rs.4000
In this scenario, INVAL amount for the wage type M230 will be the sum of a, and b
subject to a maximum of c.
Variant D − This is used to calculate the amount as one or any combination of the following INVAL Module variants based on Basic salary slabs.
Variant D − This is used to calculate the amount as one or any combination of the following INVAL Module variants based on Basic salary slabs.
This is used to calculate the fixed amount and the percentage of the basic slab. This is done by first calculating the percentage of a base wage type added to a fixed amount. And then secondly, the percentage of a base wage type which is subject to a maximum limit.
25 Lectures
6 hours
Sanjo Thomas
26 Lectures
2 hours
Neha Gupta
30 Lectures
2.5 hours
Sumit Agarwal
30 Lectures
4 hours
Sumit Agarwal
14 Lectures
1.5 hours
Neha Malik
13 Lectures
1.5 hours
Neha Malik
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2194,
"s": 1982,
"text": "Indirect Evaluation is used to calculate payroll for some specific wage types that are defaulted under the Basic Pay Infotype (0008) or Infotype 0014 or 001 (recurring payment/deductions or Additional payments)."
},
{
"code": null,
"e": 2365,
"s": 2194,
"text": "Note − While using indirect evaluation, it is also possible to calculate INVAL as numbers instead of using value as amount considering the wage type configured correctly."
},
{
"code": null,
"e": 2503,
"s": 2365,
"text": "For example − You can configure INVAL for an employee to be eligible for 10 liters of petrol each month. This represents INVAL as number."
},
{
"code": null,
"e": 2580,
"s": 2503,
"text": "There are quite a few types of variants for indirect evaluation, which are −"
},
{
"code": null,
"e": 2657,
"s": 2580,
"text": "Variant A − This is used to calculate the wage type value as a fixed amount."
},
{
"code": null,
"e": 2734,
"s": 2657,
"text": "Variant A − This is used to calculate the wage type value as a fixed amount."
},
{
"code": null,
"e": 3100,
"s": 2734,
"text": "Variant B − This is used to calculate the amount as percentage of the base wage type added to a fixed amount. In this, multiple amounts with same or different percentage of the base wage type, can be calculated for an INVAL wage type. In this case, the amount that will be Indirectly Evaluated will be the sum of all such calculated amounts added to a fixed amount."
},
{
"code": null,
"e": 3466,
"s": 3100,
"text": "Variant B − This is used to calculate the amount as percentage of the base wage type added to a fixed amount. In this, multiple amounts with same or different percentage of the base wage type, can be calculated for an INVAL wage type. In this case, the amount that will be Indirectly Evaluated will be the sum of all such calculated amounts added to a fixed amount."
},
{
"code": null,
"e": 3546,
"s": 3466,
"text": "For example − Wage type M230, consider the following different INVAL B amounts."
},
{
"code": null,
"e": 3676,
"s": 3546,
"text": "10% of MB10\n30% of M220\nFixed amount of Rs.1000\nSo in this scenario, wage type M230 will have INVAL amount as sum of a, b and c.\n"
},
{
"code": null,
"e": 4050,
"s": 3676,
"text": "Variant C − This is used to calculate the amount as a percentage of a base wage type subject to a maximum limit. More than one such amount, with same or different percentage of the base wage type, can be calculated for an INVAL wage type. In this case, the amount that will be Indirectly Evaluated will be the sum of all such calculated amounts, subject to a maximum limit."
},
{
"code": null,
"e": 4424,
"s": 4050,
"text": "Variant C − This is used to calculate the amount as a percentage of a base wage type subject to a maximum limit. More than one such amount, with same or different percentage of the base wage type, can be calculated for an INVAL wage type. In this case, the amount that will be Indirectly Evaluated will be the sum of all such calculated amounts, subject to a maximum limit."
},
{
"code": null,
"e": 4504,
"s": 4424,
"text": "For example − Wage type M230, consider the following different INVAL C amounts."
},
{
"code": null,
"e": 4656,
"s": 4504,
"text": "15% of MB10\n20% of M220\nLimit of Rs.4000\nIn this scenario, INVAL amount for the wage type M230 will be the sum of a, and b \nsubject to a maximum of c.\n"
},
{
"code": null,
"e": 4799,
"s": 4656,
"text": "Variant D − This is used to calculate the amount as one or any combination of the following INVAL Module variants based on Basic salary slabs."
},
{
"code": null,
"e": 4942,
"s": 4799,
"text": "Variant D − This is used to calculate the amount as one or any combination of the following INVAL Module variants based on Basic salary slabs."
},
{
"code": null,
"e": 5208,
"s": 4942,
"text": "This is used to calculate the fixed amount and the percentage of the basic slab. This is done by first calculating the percentage of a base wage type added to a fixed amount. And then secondly, the percentage of a base wage type which is subject to a maximum limit."
},
{
"code": null,
"e": 5241,
"s": 5208,
"text": "\n 25 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5255,
"s": 5241,
"text": " Sanjo Thomas"
},
{
"code": null,
"e": 5288,
"s": 5255,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5300,
"s": 5288,
"text": " Neha Gupta"
},
{
"code": null,
"e": 5335,
"s": 5300,
"text": "\n 30 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5350,
"s": 5335,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 5383,
"s": 5350,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5398,
"s": 5383,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 5433,
"s": 5398,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5445,
"s": 5433,
"text": " Neha Malik"
},
{
"code": null,
"e": 5480,
"s": 5445,
"text": "\n 13 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5492,
"s": 5480,
"text": " Neha Malik"
},
{
"code": null,
"e": 5499,
"s": 5492,
"text": " Print"
},
{
"code": null,
"e": 5510,
"s": 5499,
"text": " Add Notes"
}
] |
Can we create non static variables in an interface using java?
|
Interface in Java is similar to class but, it contains only abstract methods and fields which are final and static.
Since all the methods are abstract you cannot instantiate it. To use it, you need to implement this interface using a class and provide body to all the abstract methods int it.
No you cannot have non-static variables in an interface. By default,
All the members (methods and fields) of an interface are public
All the members (methods and fields) of an interface are public
All the methods in an interface are public and abstract (except static and default).
All the methods in an interface are public and abstract (except static and default).
All the fields of an interface are public, static and, final by default.
All the fields of an interface are public, static and, final by default.
If you declare/define fields without public or, static or, final or, all the three modifiers. Java compiler places them on your behalf.
In the following Java program, we are having a filed without public or, static or, final modifiers.
public interface MyInterface{
int num = 40;
void demo();
}
If you compile this using the javac command as shown below −
c:\Examples>javac MyInterface.java
it gets compiled without errors. But, if you verify the interface after compilation using the javap command as shown below −
c:\Examples>javap MyInterface
Compiled from "MyInterface.java"
public interface MyInterface {
public static final int num;
public abstract void demo();
}
You can observe that the compiler has placed the public, static and, final modifiers before the field on behalf of you.
|
[
{
"code": null,
"e": 1178,
"s": 1062,
"text": "Interface in Java is similar to class but, it contains only abstract methods and fields which are final and static."
},
{
"code": null,
"e": 1355,
"s": 1178,
"text": "Since all the methods are abstract you cannot instantiate it. To use it, you need to implement this interface using a class and provide body to all the abstract methods int it."
},
{
"code": null,
"e": 1424,
"s": 1355,
"text": "No you cannot have non-static variables in an interface. By default,"
},
{
"code": null,
"e": 1488,
"s": 1424,
"text": "All the members (methods and fields) of an interface are public"
},
{
"code": null,
"e": 1552,
"s": 1488,
"text": "All the members (methods and fields) of an interface are public"
},
{
"code": null,
"e": 1637,
"s": 1552,
"text": "All the methods in an interface are public and abstract (except static and default)."
},
{
"code": null,
"e": 1722,
"s": 1637,
"text": "All the methods in an interface are public and abstract (except static and default)."
},
{
"code": null,
"e": 1795,
"s": 1722,
"text": "All the fields of an interface are public, static and, final by default."
},
{
"code": null,
"e": 1868,
"s": 1795,
"text": "All the fields of an interface are public, static and, final by default."
},
{
"code": null,
"e": 2004,
"s": 1868,
"text": "If you declare/define fields without public or, static or, final or, all the three modifiers. Java compiler places them on your behalf."
},
{
"code": null,
"e": 2104,
"s": 2004,
"text": "In the following Java program, we are having a filed without public or, static or, final modifiers."
},
{
"code": null,
"e": 2169,
"s": 2104,
"text": "public interface MyInterface{\n int num = 40;\n void demo();\n}"
},
{
"code": null,
"e": 2230,
"s": 2169,
"text": "If you compile this using the javac command as shown below −"
},
{
"code": null,
"e": 2265,
"s": 2230,
"text": "c:\\Examples>javac MyInterface.java"
},
{
"code": null,
"e": 2390,
"s": 2265,
"text": "it gets compiled without errors. But, if you verify the interface after compilation using the javap command as shown below −"
},
{
"code": null,
"e": 2550,
"s": 2390,
"text": "c:\\Examples>javap MyInterface\nCompiled from \"MyInterface.java\"\npublic interface MyInterface {\n public static final int num;\n public abstract void demo();\n}"
},
{
"code": null,
"e": 2670,
"s": 2550,
"text": "You can observe that the compiler has placed the public, static and, final modifiers before the field on behalf of you."
}
] |
6 Steps To Write Any Machine Learning Algorithm From Scratch: Perceptron Case Study | by John Sullivan | Towards Data Science
|
Writing a machine learning algorithm from scratch is an extremely rewarding learning experience.
It provides you with that “ah ha!” moment where it finally clicks, and you understand what’s really going on under the hood.
Some algorithms are just more complicated than others, so start with something simple, such as the single layer Perceptron.
I’ll walk you through the following 6-step process to write algorithms from scratch, using the Perceptron as a case-study:
Get a basic understanding of the algorithmFind some different learning sourcesBreak the algorithm into chunksStart with a simple exampleValidate with a trusted implementationWrite up your process
Get a basic understanding of the algorithm
Find some different learning sources
Break the algorithm into chunks
Start with a simple example
Validate with a trusted implementation
Write up your process
This goes back to what I originally stated. If you don’t understand the basics, don’t tackle an algorithm from scratch.
At the very least, you should be able to answer the following questions:
What is it?
What is it typically used for?
When CAN’T I use this?
For the Perceptron, let’s go ahead and answer these questions:
The single layer Perceptron is the most basic neural network. It’s typically used for binary classification problems (1 or 0, “yes” or “no”).
Some simple uses might be sentiment analysis (positive or negative response) or loan default prediction (“will default”, “will not default”). For both cases, the decision boundary would need to be linear.
If the decision boundary is non-linear, you really can’t use the Perceptron. For those problems, you’ll need to use something different.
After you have a basic understanding of the model, it’s time to start doing your research.
Some people learn better with textbooks, some people learn better with video.
Personally, I like to bounce around and use various types of sources.
For the mathematical details, textbooks do a great job, but for more practical examples, I prefer blog posts and YouTube videos.
For the Perceptron, here’s some great sources:
Textbooks
The Elements of Statistical Learning, Sec. 4.5.1
Understanding Machine Learning: From Theory To Algorithms, Sec. 21.4
Blogs
How To Implement The Perceptron Algorithm From Scratch In Python, by Jason Brownlee
Single-Layer Neural Networks and Gradient Descent, by Sebastian Raschka
Videos
Perceptron Training
How the Perceptron Algorithm Works
Now that we’ve gathered our sources, it’s time to start learning.
Rather than read a chapter or blog post all the way through, start by skimming for section headings, and other important info.
Write down bullet points, and try to outline the algorithm.
After going through the sources, I’ve broken the Perceptron into the following 5 chunks:
Initialize the weightsMultiply weights by input and sum them upCompare result against the threshold to compute the output (1 or 0)Update the weightsRepeat
Initialize the weights
Multiply weights by input and sum them up
Compare result against the threshold to compute the output (1 or 0)
Update the weights
Repeat
Let’s go through each in detail.
1. Initialize the weights
To start, we’ll initialize the weight vector.
The number of weights needs to match the number of features. Assuming we have three features, here’s what the weight vector will look like
The weight vector is usually initialized with zeros, so I’m going to stick with that for the example.
Next, we’re going to multiply the weights by the inputs, and then sum them up.
To make it easier to follow along, I’ve colored the weights and their corresponding features in the first row.
After we multiply the weights by the features, we sum them up. This is also known as the dot product.
The final result is 0. I’m going to refer to this temporary result as “f”.
After we’ve calculated the dot product, we need to compare it against a threshold.
I’ve chosen to use 0 as my threshold, but you can play around with this and try some different numbers.
Since the dot product “f” that we calculated (0) is not greater than our threshold (0), our estimate is equal to zero.
I’ve denoted the estimate as a y with a hat (aka, “y hat”), with a 0 subscript to correspond with the first row. You could have used a 1 for the first row instead, it doesn’t really matter. I just chose to start with 0.
If we compare this result with the actual value, we can see that our current weights did not correctly predict the actual output.
Since our prediction was wrong, we need to update the weights, which brings us to the next step.
Next, we’re going to update the weights. Here’s the equation that we’re going to use:
The basic idea is that we adjust the current weight at iteration “n” so that we get a new weight to use in the next iteration, “n+1”.
To adjust the weight, we need to set a “learning rate”. This is denoted by the Greek letter “eta”.
I’ve chosen to use 0.1 for the learning rate, but you can play around with different numbers, just like with the threshold.
Here’s a quick summary of what we have so far:
Now let’s go ahead and calculate the new weights for iteration n=2.
We’ve successfully completed the first iteration of the Perceptron algorithm.
Since our algorithm didn’t compute the right output, we need to keep going.
Typically we’ll need numerous iterations. Looping through each row in the data set, we’ll update the weights each time.
One complete sweep through the data set is known as an “epoch.”
Since our data set has 3 rows, it will take us three iterations to complete 1 epoch.
We could either set a total number of iterations or epochs to continue performing the algorithm. Maybe we want to specify 30 iterations (or 10 epochs).
As with the threshold and learning rate, the number of epochs is a parameter that you can play around with.
In the next iteration, we move on to the second row of features.
I won’t go through every step again, but here’s the next calculation of the dot product:
Next we would compare the dot product with the threshold to calculate a new estimate, update the weights, and then keep going. If our data is linearly separable, the Perceptron will converge.
Now that we’ve broken the algorithm into chunks by hand, it’s time to start implementing it in code.
To keep things simple, I always like to start with a very small “toy data set.”
A nice small, linearly separable data set for this type of problem is a NAND gate. This is a common logic gate used in digital electronics.
Since this is a fairly small data set, we can just manually enter it in to Python.
I’m going to add in a dummy feature “x0” which is a column of 1’s. I did this so that our model will calculate the bias term.
You can think of the bias as the intercept term that correctly allows our model to separate the two classes.
Here’s the code for entering in the data:
# Importing libraries# NAND Gate# Note: x0 is a dummy variable for the bias term# x0 x1 x2x = [[1., 0., 0.], [1., 0., 1.], [1., 1., 0.], [1., 1., 1.]]y =[1., 1., 1., 0.]
As with the previous section, I’ll step through the algorithm in chunks, writing code and testing it as we go.
The first step is to initialize the weights.
# Initialize the weightsimport numpy as npw = np.zeros(len(x[0]))Out:[ 0. 0. 0.]
Keep in mind that the length of the weight vector needs to match the number of features. For this NAND gate example, that length is 3.
Next, we’re going to multiply the weights by the inputs, and then sum them up.
Another name for this is the “dot product.”
Again, we can use Numpy to easily perform this operation. The method we’ll use is .dot().
Let’s start by taking the dot product of the weight vector and the first row of features.
# Dot Productf = np.dot(w, x[0])print fOut:0.0
As expected, the result is 0.
To stay consistent with our notes in the previous section, I assigned the dot product to the variable “f”.
After we’ve computed the dot product, we’re ready to compare the result against the threshold to make our prediction of the output.
Again, I’m going to stay consistent with our notes in the previous section.
I’m going to make the threshold “z” equal to 0. If the dot product “f” is greater than 0, our prediction will be 1. Otherwise, it will be zero.
Keep in mind that the prediction is usually denoted with a carat over the top, also know as a “hat”. The variable I’ll assign the prediction to is yhat.
# Activation Functionz = 0.0if f > z: yhat = 1.else: yhat = 0. print yhatOut:0.0
As expected, the prediction is 0.
You’ll notice that in the note above the code I’ve called this the “Activation function”. This is a more formal description of what we’re doing.
Taking a look at the first row of the NAND output, we can see that the actual value is 1. Since our prediction was wrong, we’ll need to go ahead and update the weights.
Now that we’ve made our prediction, we’re ready to update the weights.
We’ll need to set a learning rate before we can do that. To be consistent with our previous example, I’ll assign the learning rate “eta” a value of 0.1.
I’m going to hard code the update for each weight to make things easier to read.
# Update the weightseta = 0.1w[0] = w[0] + eta*(y[0] - yhat)*x[0][0]w[1] = w[1] + eta*(y[0] - yhat)*x[0][1]w[2] = w[2] + eta*(y[0] - yhat)*x[0][2]print wOut:[ 0.1 0. 0. ]
We can see that our weights have now been updated, so we’re ready to keep going.
Now that we’ve worked through each step, it’s time to put everything together.
The one final piece we haven’t discussed is our loss function. This is the function we’re trying to minimize, which in our case will be the sum-of-squared (SSE) error.
This is what we’ll use to calculate our error, and see how the model is performing.
Tying it all together, here’s what the full function looks like:
import numpy as np# Perceptron functiondef perceptron(x, y, z, eta, t): ''' Input Parameters: x: data set of input features y: actual outputs z: activation function threshold eta: learning rate t: number of iterations ''' # initializing the weights w = np.zeros(len(x[0])) n = 0 # initializing additional parameters to compute sum-of-squared errors yhat_vec = np.ones(len(y)) # vector for predictions errors = np.ones(len(y)) # vector for errors (actual - predictions) J = [] # vector for the SSE cost function while n < t: for i in xrange(0, len(x)): # dot product f = np.dot(x[i], w) # activation function if f >= z: yhat = 1. else: yhat = 0. yhat_vec[i] = yhat # updating the weights for j in xrange(0, len(w)): w[j] = w[j] + eta*(y[i]-yhat)*x[i][j] n += 1 # computing the sum-of-squared errors for i in xrange(0,len(y)): errors[i] = (y[i]-yhat_vec[i])**2 J.append(0.5*np.sum(errors)) return w, J
Now that we’ve coded the full Perceptron, let’s go ahead and run it:
# x0 x1 x2x = [[1., 0., 0.], [1., 0., 1.], [1., 1., 0.], [1., 1., 1.]]y =[1., 1., 1., 0.]z = 0.0eta = 0.1t = 50print "The weights are:"print perceptron(x, y, z, eta, t)[0]print "The errors are:"print perceptron(x, y, z, eta, t)[0]Out:The weights are:[ 0.2 -0.2 -0.1]The errors are:[0.5, 1.5, 1.5, 1.0, 0.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]
Taking a look at the errors we can see that the error went to 0 around the 6th iteration. For the remainder of the iterations it remained at 0.
When the error goes to 0 and stays there, we know that our model has converged. This tells us that our model has correctly “learned” the appropriate weights.
In the next section we’ll use our calculated weights on a larger dataset to make predictions.
Up to this point we’ve found different learning resources, worked through the algorithm by hand, and tested it in code with a simple example.
Now it’s time to compare our results with a trusted implementation. For comparison, we’ll use the Perceptron from scikit-learn.
We’ll work through this comparison using the following steps:
Import the dataSplit the data into train/test setsTrain our PerceptronTest the PerceptronCompare with the scikit-learn Perceptron
Import the data
Split the data into train/test sets
Train our Perceptron
Test the Perceptron
Compare with the scikit-learn Perceptron
Lets start by importing the data. You can get a copy of the dataset here.
This is a linearly separable dataset that I created to make sure that the Perceptron would work. Just to confirm, let’s go ahead and plot the data.
import pandas as pdimport numpy as npimport matplotlib.pyplot as pltdf = pd.read_csv("dataset.csv")plt.scatter(df.values[:,1], df.values[:,2], c = df['3'], alpha=0.8)
Taking a look at the plot it’s pretty easy to see that we can separate this data with a straight line.
Before we move on, I’ll explain my plotting code above.
I used Pandas to import the csv, which automatically puts the data in a dataframe.
To plot the data I had to pull the values out of the dataframe, so that’s why i used the .values method.
The features are in columns 1 and 2, so that’s why I used those in the scatterplot function. Column 0 is a dummy feature of 1’s that I included so that the intercept is calculated. This should be familiar to what we did with the NAND gate in the previous section.
Finally, I colored the two classes using c = df['3'], alpha = 0.8 in the scatterplot function. The output is the data in column 3 (0 or 1), so I told the function to color the two classes using column ‘3’.
You can find more info on Matplotlib’s scatterplot function here.
Now that we’ve confirmed the data can be separated linearly, it’s time to split the data.
It’s always good practice to train a model on a separate dataset from the one you test on. This helps to avoid overfitting.
There’s different methods for doing this, but to keep things simple I’ll just use a training set and a test set.
I’ll start by shuffling up my data. If you take a look at the original file you’ll see that the data is grouped by rows with 0 in the output (third column) and then followed by all of the 1’s. I want to shake things up and add some randomness, so I’m going to shuffle it.
df = df.values np.random.seed(5)np.random.shuffle(df)
I started by changing the data from a dataframe to a numpy array. This is going to make it easier to work with a lot of the numpy functions I’m going to use, such as .shuffle.
To make the results reproducible for you I set a random seed (5). After we’ve finished, try changing the random seed and see how the results change.
Next I’m going split 70% of my data into a training set, and 30% into a test set.
train = df[0:int(0.7*len(df))]test = df[int(0.7*len(df)):int(len(df))]
The final step is to separate out the features and the outputs for the training and test sets.
x_train = train[:, 0:3]y_train = train[:, 3]x_test = test[:, 0:3]y_test = test[:, 3]
I chose 70%/30% for my train/test sets just for the sake of this example, but I encourage you to look into other methods, such as k-fold cross validation.
Next, we’ll train our Perceptron.
This is pretty straightforward, we’re just going to reuse the code that we build in the previous section.
def perceptron_train(x, y, z, eta, t): ''' Input Parameters: x: data set of input features y: actual outputs z: activation function threshold eta: learning rate t: number of iterations ''' # initializing the weights w = np.zeros(len(x[0])) n = 0 # initializing additional parameters to compute sum-of-squared errors yhat_vec = np.ones(len(y)) # vector for predictions errors = np.ones(len(y)) # vector for errors (actual - predictions) J = [] # vector for the SSE cost function while n < t: for i in xrange(0, len(x)): # dot product f = np.dot(x[i], w) # activation function if f >= z: yhat = 1. else: yhat = 0. yhat_vec[i] = yhat # updating the weights for j in xrange(0, len(w)): w[j] = w[j] + eta*(y[i]-yhat)*x[i][j] n += 1 # computing the sum-of-squared errors for i in xrange(0,len(y)): errors[i] = (y[i]-yhat_vec[i])**2 J.append(0.5*np.sum(errors)) return w, Jz = 0.0eta = 0.1t = 50perceptron_train(x_train, y_train, z, eta, t)
Let’s go ahead and take a look at the weights and the sum-of-squared error.
w = perceptron_train(x_train, y_train, z, eta, t)[0]J = perceptron_train(x_train, y_train, z, eta, t)[1]print wprint JOut:[-0.5 -0.29850122 0.35054929][4.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]
The weights don’t mean much to us right now, but we’ll use those numbers in the next section to test our Perceptron. We’ll also use the weights to compare our model to the scikit-learn model.
Taking a look at the sum-of-squared error we can see that our Perceptron has converged, which we’d expect since the data is linearly separable.
Now it’s time to test our Perceptron. To do that we’ll build a small perceptron_test function.
This is very similar to what we’ve already seen. This function takes the dot product of the weights we calculated using the perceptron_train function and the features, along with the activation function, to make predictions.
The only piece we haven’t seen is the accuracy_score. This is an evaluation metric function from scikit-learn. You can learn more about it here.
Putting all of this together, here’s what the code looks like:
from sklearn.metrics import accuracy_scorew = perceptron_train(x_train, y_train, z, eta, t)[0]def perceptron_test(x, w, z, eta, t): y_pred = [] for i in xrange(0, len(x-1)): f = np.dot(x[i], w) # activation function if f > z: yhat = 1 else: yhat = 0 y_pred.append(yhat) return y_predy_pred = perceptron_test(x_test, w, z, eta, t)print "The accuracy score is:"print accuracy_score(y_test, y_pred)Out:The accuracy score is:1.0
A score of 1.0 indicates that our model correctly made predictions on all of the test data. This dataset is clearly separable, so we’d expect this result.
The final step is to compare our results with the Perceptron from scikit-learn. Here’s the code from that model:
from sklearn.linear_model import Perceptron# training the sklearn Perceptronclf = Perceptron(random_state=None, eta0=0.1, shuffle=False, fit_intercept=False)clf.fit(x_train, y_train)y_predict = clf.predict(x_test)
Now that we’ve trained the model, lets compare the weights to the weights that our model calculated.
Out:sklearn weights:[-0.5 -0.29850122 0.35054929]my perceptron weights:[-0.5 -0.29850122 0.35054929]
The weights from the scikit-learn model are identical to our weights. This means that our model is working correctly, which is great news.
There’s a few minor points to go over before we wrap up. In the scikit-learn model we had to set the random state to ‘None’ and turn off the shuffling. We already set a random seed and shuffled the data, so we didn’t need to do this again.
We also had to set the learning rate ‘eta0’ to 0.1 to be identical to our model.
The final point is the intercept. Since we already include a dummy feature column of 1s we were fitting intercept automatically, so we didn’t need to turn this on in the scikit-learn Perceptron.
These all seem like minor details, but if we didn’t set these, we wouldn’t be able to reproduce the same results as our model.
This is an important point. Before using a model, it’s very important to read the documentation and understand what all of the different settings do.
This last step in the process is probably the most important.
You’ve just gone through all the work of learning, taking notes, writing the algorithm from scratch, and comparing it with a trusted implementation. Don’t let all that good work go to waste!
Writing up the process is important for two reasons:
You’ll gain an even deeper understanding because you’re teaching others what you just learned.
You can showcase it to potential employers.
It’s one thing to show that you can implement an algorithm from a machine learning library, but it’s even more impressive if you can implement it yourself from scratch.
A great way to showcase your work is with a GitHub Pages portfolio.
In this post we learned how to implement the Perceptron from scratch.
More importantly, we learned how to find useful learning resources, and how to break an algorithm into chunks.
We then learned how to implement and test an algorithm in code using a toy dataset.
Finally, we finished up by comparing the results from our model to a trusted implementation.
This is a great methodology to learn an algorithm on a deeper level so that you can implement it yourself.
Most of the time you’ll use a trusted implementation, but if you really want to gain a deeper understanding of what’s going on under the hood, implementing it from scratch is a great exercise!
|
[
{
"code": null,
"e": 269,
"s": 172,
"text": "Writing a machine learning algorithm from scratch is an extremely rewarding learning experience."
},
{
"code": null,
"e": 394,
"s": 269,
"text": "It provides you with that “ah ha!” moment where it finally clicks, and you understand what’s really going on under the hood."
},
{
"code": null,
"e": 518,
"s": 394,
"text": "Some algorithms are just more complicated than others, so start with something simple, such as the single layer Perceptron."
},
{
"code": null,
"e": 641,
"s": 518,
"text": "I’ll walk you through the following 6-step process to write algorithms from scratch, using the Perceptron as a case-study:"
},
{
"code": null,
"e": 837,
"s": 641,
"text": "Get a basic understanding of the algorithmFind some different learning sourcesBreak the algorithm into chunksStart with a simple exampleValidate with a trusted implementationWrite up your process"
},
{
"code": null,
"e": 880,
"s": 837,
"text": "Get a basic understanding of the algorithm"
},
{
"code": null,
"e": 917,
"s": 880,
"text": "Find some different learning sources"
},
{
"code": null,
"e": 949,
"s": 917,
"text": "Break the algorithm into chunks"
},
{
"code": null,
"e": 977,
"s": 949,
"text": "Start with a simple example"
},
{
"code": null,
"e": 1016,
"s": 977,
"text": "Validate with a trusted implementation"
},
{
"code": null,
"e": 1038,
"s": 1016,
"text": "Write up your process"
},
{
"code": null,
"e": 1158,
"s": 1038,
"text": "This goes back to what I originally stated. If you don’t understand the basics, don’t tackle an algorithm from scratch."
},
{
"code": null,
"e": 1231,
"s": 1158,
"text": "At the very least, you should be able to answer the following questions:"
},
{
"code": null,
"e": 1243,
"s": 1231,
"text": "What is it?"
},
{
"code": null,
"e": 1274,
"s": 1243,
"text": "What is it typically used for?"
},
{
"code": null,
"e": 1297,
"s": 1274,
"text": "When CAN’T I use this?"
},
{
"code": null,
"e": 1360,
"s": 1297,
"text": "For the Perceptron, let’s go ahead and answer these questions:"
},
{
"code": null,
"e": 1502,
"s": 1360,
"text": "The single layer Perceptron is the most basic neural network. It’s typically used for binary classification problems (1 or 0, “yes” or “no”)."
},
{
"code": null,
"e": 1707,
"s": 1502,
"text": "Some simple uses might be sentiment analysis (positive or negative response) or loan default prediction (“will default”, “will not default”). For both cases, the decision boundary would need to be linear."
},
{
"code": null,
"e": 1844,
"s": 1707,
"text": "If the decision boundary is non-linear, you really can’t use the Perceptron. For those problems, you’ll need to use something different."
},
{
"code": null,
"e": 1935,
"s": 1844,
"text": "After you have a basic understanding of the model, it’s time to start doing your research."
},
{
"code": null,
"e": 2013,
"s": 1935,
"text": "Some people learn better with textbooks, some people learn better with video."
},
{
"code": null,
"e": 2083,
"s": 2013,
"text": "Personally, I like to bounce around and use various types of sources."
},
{
"code": null,
"e": 2212,
"s": 2083,
"text": "For the mathematical details, textbooks do a great job, but for more practical examples, I prefer blog posts and YouTube videos."
},
{
"code": null,
"e": 2259,
"s": 2212,
"text": "For the Perceptron, here’s some great sources:"
},
{
"code": null,
"e": 2269,
"s": 2259,
"text": "Textbooks"
},
{
"code": null,
"e": 2318,
"s": 2269,
"text": "The Elements of Statistical Learning, Sec. 4.5.1"
},
{
"code": null,
"e": 2387,
"s": 2318,
"text": "Understanding Machine Learning: From Theory To Algorithms, Sec. 21.4"
},
{
"code": null,
"e": 2393,
"s": 2387,
"text": "Blogs"
},
{
"code": null,
"e": 2477,
"s": 2393,
"text": "How To Implement The Perceptron Algorithm From Scratch In Python, by Jason Brownlee"
},
{
"code": null,
"e": 2549,
"s": 2477,
"text": "Single-Layer Neural Networks and Gradient Descent, by Sebastian Raschka"
},
{
"code": null,
"e": 2556,
"s": 2549,
"text": "Videos"
},
{
"code": null,
"e": 2576,
"s": 2556,
"text": "Perceptron Training"
},
{
"code": null,
"e": 2611,
"s": 2576,
"text": "How the Perceptron Algorithm Works"
},
{
"code": null,
"e": 2677,
"s": 2611,
"text": "Now that we’ve gathered our sources, it’s time to start learning."
},
{
"code": null,
"e": 2804,
"s": 2677,
"text": "Rather than read a chapter or blog post all the way through, start by skimming for section headings, and other important info."
},
{
"code": null,
"e": 2864,
"s": 2804,
"text": "Write down bullet points, and try to outline the algorithm."
},
{
"code": null,
"e": 2953,
"s": 2864,
"text": "After going through the sources, I’ve broken the Perceptron into the following 5 chunks:"
},
{
"code": null,
"e": 3108,
"s": 2953,
"text": "Initialize the weightsMultiply weights by input and sum them upCompare result against the threshold to compute the output (1 or 0)Update the weightsRepeat"
},
{
"code": null,
"e": 3131,
"s": 3108,
"text": "Initialize the weights"
},
{
"code": null,
"e": 3173,
"s": 3131,
"text": "Multiply weights by input and sum them up"
},
{
"code": null,
"e": 3241,
"s": 3173,
"text": "Compare result against the threshold to compute the output (1 or 0)"
},
{
"code": null,
"e": 3260,
"s": 3241,
"text": "Update the weights"
},
{
"code": null,
"e": 3267,
"s": 3260,
"text": "Repeat"
},
{
"code": null,
"e": 3300,
"s": 3267,
"text": "Let’s go through each in detail."
},
{
"code": null,
"e": 3326,
"s": 3300,
"text": "1. Initialize the weights"
},
{
"code": null,
"e": 3372,
"s": 3326,
"text": "To start, we’ll initialize the weight vector."
},
{
"code": null,
"e": 3511,
"s": 3372,
"text": "The number of weights needs to match the number of features. Assuming we have three features, here’s what the weight vector will look like"
},
{
"code": null,
"e": 3613,
"s": 3511,
"text": "The weight vector is usually initialized with zeros, so I’m going to stick with that for the example."
},
{
"code": null,
"e": 3692,
"s": 3613,
"text": "Next, we’re going to multiply the weights by the inputs, and then sum them up."
},
{
"code": null,
"e": 3803,
"s": 3692,
"text": "To make it easier to follow along, I’ve colored the weights and their corresponding features in the first row."
},
{
"code": null,
"e": 3905,
"s": 3803,
"text": "After we multiply the weights by the features, we sum them up. This is also known as the dot product."
},
{
"code": null,
"e": 3980,
"s": 3905,
"text": "The final result is 0. I’m going to refer to this temporary result as “f”."
},
{
"code": null,
"e": 4063,
"s": 3980,
"text": "After we’ve calculated the dot product, we need to compare it against a threshold."
},
{
"code": null,
"e": 4167,
"s": 4063,
"text": "I’ve chosen to use 0 as my threshold, but you can play around with this and try some different numbers."
},
{
"code": null,
"e": 4286,
"s": 4167,
"text": "Since the dot product “f” that we calculated (0) is not greater than our threshold (0), our estimate is equal to zero."
},
{
"code": null,
"e": 4506,
"s": 4286,
"text": "I’ve denoted the estimate as a y with a hat (aka, “y hat”), with a 0 subscript to correspond with the first row. You could have used a 1 for the first row instead, it doesn’t really matter. I just chose to start with 0."
},
{
"code": null,
"e": 4636,
"s": 4506,
"text": "If we compare this result with the actual value, we can see that our current weights did not correctly predict the actual output."
},
{
"code": null,
"e": 4733,
"s": 4636,
"text": "Since our prediction was wrong, we need to update the weights, which brings us to the next step."
},
{
"code": null,
"e": 4819,
"s": 4733,
"text": "Next, we’re going to update the weights. Here’s the equation that we’re going to use:"
},
{
"code": null,
"e": 4953,
"s": 4819,
"text": "The basic idea is that we adjust the current weight at iteration “n” so that we get a new weight to use in the next iteration, “n+1”."
},
{
"code": null,
"e": 5052,
"s": 4953,
"text": "To adjust the weight, we need to set a “learning rate”. This is denoted by the Greek letter “eta”."
},
{
"code": null,
"e": 5176,
"s": 5052,
"text": "I’ve chosen to use 0.1 for the learning rate, but you can play around with different numbers, just like with the threshold."
},
{
"code": null,
"e": 5223,
"s": 5176,
"text": "Here’s a quick summary of what we have so far:"
},
{
"code": null,
"e": 5291,
"s": 5223,
"text": "Now let’s go ahead and calculate the new weights for iteration n=2."
},
{
"code": null,
"e": 5369,
"s": 5291,
"text": "We’ve successfully completed the first iteration of the Perceptron algorithm."
},
{
"code": null,
"e": 5445,
"s": 5369,
"text": "Since our algorithm didn’t compute the right output, we need to keep going."
},
{
"code": null,
"e": 5565,
"s": 5445,
"text": "Typically we’ll need numerous iterations. Looping through each row in the data set, we’ll update the weights each time."
},
{
"code": null,
"e": 5629,
"s": 5565,
"text": "One complete sweep through the data set is known as an “epoch.”"
},
{
"code": null,
"e": 5714,
"s": 5629,
"text": "Since our data set has 3 rows, it will take us three iterations to complete 1 epoch."
},
{
"code": null,
"e": 5866,
"s": 5714,
"text": "We could either set a total number of iterations or epochs to continue performing the algorithm. Maybe we want to specify 30 iterations (or 10 epochs)."
},
{
"code": null,
"e": 5974,
"s": 5866,
"text": "As with the threshold and learning rate, the number of epochs is a parameter that you can play around with."
},
{
"code": null,
"e": 6039,
"s": 5974,
"text": "In the next iteration, we move on to the second row of features."
},
{
"code": null,
"e": 6128,
"s": 6039,
"text": "I won’t go through every step again, but here’s the next calculation of the dot product:"
},
{
"code": null,
"e": 6320,
"s": 6128,
"text": "Next we would compare the dot product with the threshold to calculate a new estimate, update the weights, and then keep going. If our data is linearly separable, the Perceptron will converge."
},
{
"code": null,
"e": 6421,
"s": 6320,
"text": "Now that we’ve broken the algorithm into chunks by hand, it’s time to start implementing it in code."
},
{
"code": null,
"e": 6501,
"s": 6421,
"text": "To keep things simple, I always like to start with a very small “toy data set.”"
},
{
"code": null,
"e": 6641,
"s": 6501,
"text": "A nice small, linearly separable data set for this type of problem is a NAND gate. This is a common logic gate used in digital electronics."
},
{
"code": null,
"e": 6724,
"s": 6641,
"text": "Since this is a fairly small data set, we can just manually enter it in to Python."
},
{
"code": null,
"e": 6850,
"s": 6724,
"text": "I’m going to add in a dummy feature “x0” which is a column of 1’s. I did this so that our model will calculate the bias term."
},
{
"code": null,
"e": 6959,
"s": 6850,
"text": "You can think of the bias as the intercept term that correctly allows our model to separate the two classes."
},
{
"code": null,
"e": 7001,
"s": 6959,
"text": "Here’s the code for entering in the data:"
},
{
"code": null,
"e": 7198,
"s": 7001,
"text": "# Importing libraries# NAND Gate# Note: x0 is a dummy variable for the bias term# x0 x1 x2x = [[1., 0., 0.], [1., 0., 1.], [1., 1., 0.], [1., 1., 1.]]y =[1., 1., 1., 0.]"
},
{
"code": null,
"e": 7309,
"s": 7198,
"text": "As with the previous section, I’ll step through the algorithm in chunks, writing code and testing it as we go."
},
{
"code": null,
"e": 7354,
"s": 7309,
"text": "The first step is to initialize the weights."
},
{
"code": null,
"e": 7437,
"s": 7354,
"text": "# Initialize the weightsimport numpy as npw = np.zeros(len(x[0]))Out:[ 0. 0. 0.]"
},
{
"code": null,
"e": 7572,
"s": 7437,
"text": "Keep in mind that the length of the weight vector needs to match the number of features. For this NAND gate example, that length is 3."
},
{
"code": null,
"e": 7651,
"s": 7572,
"text": "Next, we’re going to multiply the weights by the inputs, and then sum them up."
},
{
"code": null,
"e": 7695,
"s": 7651,
"text": "Another name for this is the “dot product.”"
},
{
"code": null,
"e": 7785,
"s": 7695,
"text": "Again, we can use Numpy to easily perform this operation. The method we’ll use is .dot()."
},
{
"code": null,
"e": 7875,
"s": 7785,
"text": "Let’s start by taking the dot product of the weight vector and the first row of features."
},
{
"code": null,
"e": 7922,
"s": 7875,
"text": "# Dot Productf = np.dot(w, x[0])print fOut:0.0"
},
{
"code": null,
"e": 7952,
"s": 7922,
"text": "As expected, the result is 0."
},
{
"code": null,
"e": 8059,
"s": 7952,
"text": "To stay consistent with our notes in the previous section, I assigned the dot product to the variable “f”."
},
{
"code": null,
"e": 8191,
"s": 8059,
"text": "After we’ve computed the dot product, we’re ready to compare the result against the threshold to make our prediction of the output."
},
{
"code": null,
"e": 8267,
"s": 8191,
"text": "Again, I’m going to stay consistent with our notes in the previous section."
},
{
"code": null,
"e": 8411,
"s": 8267,
"text": "I’m going to make the threshold “z” equal to 0. If the dot product “f” is greater than 0, our prediction will be 1. Otherwise, it will be zero."
},
{
"code": null,
"e": 8564,
"s": 8411,
"text": "Keep in mind that the prediction is usually denoted with a carat over the top, also know as a “hat”. The variable I’ll assign the prediction to is yhat."
},
{
"code": null,
"e": 8654,
"s": 8564,
"text": "# Activation Functionz = 0.0if f > z: yhat = 1.else: yhat = 0. print yhatOut:0.0"
},
{
"code": null,
"e": 8688,
"s": 8654,
"text": "As expected, the prediction is 0."
},
{
"code": null,
"e": 8833,
"s": 8688,
"text": "You’ll notice that in the note above the code I’ve called this the “Activation function”. This is a more formal description of what we’re doing."
},
{
"code": null,
"e": 9002,
"s": 8833,
"text": "Taking a look at the first row of the NAND output, we can see that the actual value is 1. Since our prediction was wrong, we’ll need to go ahead and update the weights."
},
{
"code": null,
"e": 9073,
"s": 9002,
"text": "Now that we’ve made our prediction, we’re ready to update the weights."
},
{
"code": null,
"e": 9226,
"s": 9073,
"text": "We’ll need to set a learning rate before we can do that. To be consistent with our previous example, I’ll assign the learning rate “eta” a value of 0.1."
},
{
"code": null,
"e": 9307,
"s": 9226,
"text": "I’m going to hard code the update for each weight to make things easier to read."
},
{
"code": null,
"e": 9481,
"s": 9307,
"text": "# Update the weightseta = 0.1w[0] = w[0] + eta*(y[0] - yhat)*x[0][0]w[1] = w[1] + eta*(y[0] - yhat)*x[0][1]w[2] = w[2] + eta*(y[0] - yhat)*x[0][2]print wOut:[ 0.1 0. 0. ]"
},
{
"code": null,
"e": 9562,
"s": 9481,
"text": "We can see that our weights have now been updated, so we’re ready to keep going."
},
{
"code": null,
"e": 9641,
"s": 9562,
"text": "Now that we’ve worked through each step, it’s time to put everything together."
},
{
"code": null,
"e": 9809,
"s": 9641,
"text": "The one final piece we haven’t discussed is our loss function. This is the function we’re trying to minimize, which in our case will be the sum-of-squared (SSE) error."
},
{
"code": null,
"e": 9893,
"s": 9809,
"text": "This is what we’ll use to calculate our error, and see how the model is performing."
},
{
"code": null,
"e": 9958,
"s": 9893,
"text": "Tying it all together, here’s what the full function looks like:"
},
{
"code": null,
"e": 11283,
"s": 9958,
"text": "import numpy as np# Perceptron functiondef perceptron(x, y, z, eta, t): ''' Input Parameters: x: data set of input features y: actual outputs z: activation function threshold eta: learning rate t: number of iterations ''' # initializing the weights w = np.zeros(len(x[0])) n = 0 # initializing additional parameters to compute sum-of-squared errors yhat_vec = np.ones(len(y)) # vector for predictions errors = np.ones(len(y)) # vector for errors (actual - predictions) J = [] # vector for the SSE cost function while n < t: for i in xrange(0, len(x)): # dot product f = np.dot(x[i], w) # activation function if f >= z: yhat = 1. else: yhat = 0. yhat_vec[i] = yhat # updating the weights for j in xrange(0, len(w)): w[j] = w[j] + eta*(y[i]-yhat)*x[i][j] n += 1 # computing the sum-of-squared errors for i in xrange(0,len(y)): errors[i] = (y[i]-yhat_vec[i])**2 J.append(0.5*np.sum(errors)) return w, J"
},
{
"code": null,
"e": 11352,
"s": 11283,
"text": "Now that we’ve coded the full Perceptron, let’s go ahead and run it:"
},
{
"code": null,
"e": 11911,
"s": 11352,
"text": "# x0 x1 x2x = [[1., 0., 0.], [1., 0., 1.], [1., 1., 0.], [1., 1., 1.]]y =[1., 1., 1., 0.]z = 0.0eta = 0.1t = 50print \"The weights are:\"print perceptron(x, y, z, eta, t)[0]print \"The errors are:\"print perceptron(x, y, z, eta, t)[0]Out:The weights are:[ 0.2 -0.2 -0.1]The errors are:[0.5, 1.5, 1.5, 1.0, 0.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]"
},
{
"code": null,
"e": 12055,
"s": 11911,
"text": "Taking a look at the errors we can see that the error went to 0 around the 6th iteration. For the remainder of the iterations it remained at 0."
},
{
"code": null,
"e": 12213,
"s": 12055,
"text": "When the error goes to 0 and stays there, we know that our model has converged. This tells us that our model has correctly “learned” the appropriate weights."
},
{
"code": null,
"e": 12307,
"s": 12213,
"text": "In the next section we’ll use our calculated weights on a larger dataset to make predictions."
},
{
"code": null,
"e": 12449,
"s": 12307,
"text": "Up to this point we’ve found different learning resources, worked through the algorithm by hand, and tested it in code with a simple example."
},
{
"code": null,
"e": 12577,
"s": 12449,
"text": "Now it’s time to compare our results with a trusted implementation. For comparison, we’ll use the Perceptron from scikit-learn."
},
{
"code": null,
"e": 12639,
"s": 12577,
"text": "We’ll work through this comparison using the following steps:"
},
{
"code": null,
"e": 12769,
"s": 12639,
"text": "Import the dataSplit the data into train/test setsTrain our PerceptronTest the PerceptronCompare with the scikit-learn Perceptron"
},
{
"code": null,
"e": 12785,
"s": 12769,
"text": "Import the data"
},
{
"code": null,
"e": 12821,
"s": 12785,
"text": "Split the data into train/test sets"
},
{
"code": null,
"e": 12842,
"s": 12821,
"text": "Train our Perceptron"
},
{
"code": null,
"e": 12862,
"s": 12842,
"text": "Test the Perceptron"
},
{
"code": null,
"e": 12903,
"s": 12862,
"text": "Compare with the scikit-learn Perceptron"
},
{
"code": null,
"e": 12977,
"s": 12903,
"text": "Lets start by importing the data. You can get a copy of the dataset here."
},
{
"code": null,
"e": 13125,
"s": 12977,
"text": "This is a linearly separable dataset that I created to make sure that the Perceptron would work. Just to confirm, let’s go ahead and plot the data."
},
{
"code": null,
"e": 13292,
"s": 13125,
"text": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltdf = pd.read_csv(\"dataset.csv\")plt.scatter(df.values[:,1], df.values[:,2], c = df['3'], alpha=0.8)"
},
{
"code": null,
"e": 13395,
"s": 13292,
"text": "Taking a look at the plot it’s pretty easy to see that we can separate this data with a straight line."
},
{
"code": null,
"e": 13451,
"s": 13395,
"text": "Before we move on, I’ll explain my plotting code above."
},
{
"code": null,
"e": 13534,
"s": 13451,
"text": "I used Pandas to import the csv, which automatically puts the data in a dataframe."
},
{
"code": null,
"e": 13639,
"s": 13534,
"text": "To plot the data I had to pull the values out of the dataframe, so that’s why i used the .values method."
},
{
"code": null,
"e": 13903,
"s": 13639,
"text": "The features are in columns 1 and 2, so that’s why I used those in the scatterplot function. Column 0 is a dummy feature of 1’s that I included so that the intercept is calculated. This should be familiar to what we did with the NAND gate in the previous section."
},
{
"code": null,
"e": 14109,
"s": 13903,
"text": "Finally, I colored the two classes using c = df['3'], alpha = 0.8 in the scatterplot function. The output is the data in column 3 (0 or 1), so I told the function to color the two classes using column ‘3’."
},
{
"code": null,
"e": 14175,
"s": 14109,
"text": "You can find more info on Matplotlib’s scatterplot function here."
},
{
"code": null,
"e": 14265,
"s": 14175,
"text": "Now that we’ve confirmed the data can be separated linearly, it’s time to split the data."
},
{
"code": null,
"e": 14389,
"s": 14265,
"text": "It’s always good practice to train a model on a separate dataset from the one you test on. This helps to avoid overfitting."
},
{
"code": null,
"e": 14502,
"s": 14389,
"text": "There’s different methods for doing this, but to keep things simple I’ll just use a training set and a test set."
},
{
"code": null,
"e": 14774,
"s": 14502,
"text": "I’ll start by shuffling up my data. If you take a look at the original file you’ll see that the data is grouped by rows with 0 in the output (third column) and then followed by all of the 1’s. I want to shake things up and add some randomness, so I’m going to shuffle it."
},
{
"code": null,
"e": 14845,
"s": 14774,
"text": "df = df.values np.random.seed(5)np.random.shuffle(df)"
},
{
"code": null,
"e": 15021,
"s": 14845,
"text": "I started by changing the data from a dataframe to a numpy array. This is going to make it easier to work with a lot of the numpy functions I’m going to use, such as .shuffle."
},
{
"code": null,
"e": 15170,
"s": 15021,
"text": "To make the results reproducible for you I set a random seed (5). After we’ve finished, try changing the random seed and see how the results change."
},
{
"code": null,
"e": 15252,
"s": 15170,
"text": "Next I’m going split 70% of my data into a training set, and 30% into a test set."
},
{
"code": null,
"e": 15323,
"s": 15252,
"text": "train = df[0:int(0.7*len(df))]test = df[int(0.7*len(df)):int(len(df))]"
},
{
"code": null,
"e": 15418,
"s": 15323,
"text": "The final step is to separate out the features and the outputs for the training and test sets."
},
{
"code": null,
"e": 15503,
"s": 15418,
"text": "x_train = train[:, 0:3]y_train = train[:, 3]x_test = test[:, 0:3]y_test = test[:, 3]"
},
{
"code": null,
"e": 15658,
"s": 15503,
"text": "I chose 70%/30% for my train/test sets just for the sake of this example, but I encourage you to look into other methods, such as k-fold cross validation."
},
{
"code": null,
"e": 15692,
"s": 15658,
"text": "Next, we’ll train our Perceptron."
},
{
"code": null,
"e": 15798,
"s": 15692,
"text": "This is pretty straightforward, we’re just going to reuse the code that we build in the previous section."
},
{
"code": null,
"e": 17266,
"s": 15798,
"text": "def perceptron_train(x, y, z, eta, t): ''' Input Parameters: x: data set of input features y: actual outputs z: activation function threshold eta: learning rate t: number of iterations ''' # initializing the weights w = np.zeros(len(x[0])) n = 0 # initializing additional parameters to compute sum-of-squared errors yhat_vec = np.ones(len(y)) # vector for predictions errors = np.ones(len(y)) # vector for errors (actual - predictions) J = [] # vector for the SSE cost function while n < t: for i in xrange(0, len(x)): # dot product f = np.dot(x[i], w) # activation function if f >= z: yhat = 1. else: yhat = 0. yhat_vec[i] = yhat # updating the weights for j in xrange(0, len(w)): w[j] = w[j] + eta*(y[i]-yhat)*x[i][j] n += 1 # computing the sum-of-squared errors for i in xrange(0,len(y)): errors[i] = (y[i]-yhat_vec[i])**2 J.append(0.5*np.sum(errors)) return w, Jz = 0.0eta = 0.1t = 50perceptron_train(x_train, y_train, z, eta, t)"
},
{
"code": null,
"e": 17342,
"s": 17266,
"text": "Let’s go ahead and take a look at the weights and the sum-of-squared error."
},
{
"code": null,
"e": 17752,
"s": 17342,
"text": "w = perceptron_train(x_train, y_train, z, eta, t)[0]J = perceptron_train(x_train, y_train, z, eta, t)[1]print wprint JOut:[-0.5 -0.29850122 0.35054929][4.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]"
},
{
"code": null,
"e": 17944,
"s": 17752,
"text": "The weights don’t mean much to us right now, but we’ll use those numbers in the next section to test our Perceptron. We’ll also use the weights to compare our model to the scikit-learn model."
},
{
"code": null,
"e": 18088,
"s": 17944,
"text": "Taking a look at the sum-of-squared error we can see that our Perceptron has converged, which we’d expect since the data is linearly separable."
},
{
"code": null,
"e": 18183,
"s": 18088,
"text": "Now it’s time to test our Perceptron. To do that we’ll build a small perceptron_test function."
},
{
"code": null,
"e": 18408,
"s": 18183,
"text": "This is very similar to what we’ve already seen. This function takes the dot product of the weights we calculated using the perceptron_train function and the features, along with the activation function, to make predictions."
},
{
"code": null,
"e": 18553,
"s": 18408,
"text": "The only piece we haven’t seen is the accuracy_score. This is an evaluation metric function from scikit-learn. You can learn more about it here."
},
{
"code": null,
"e": 18616,
"s": 18553,
"text": "Putting all of this together, here’s what the code looks like:"
},
{
"code": null,
"e": 19207,
"s": 18616,
"text": "from sklearn.metrics import accuracy_scorew = perceptron_train(x_train, y_train, z, eta, t)[0]def perceptron_test(x, w, z, eta, t): y_pred = [] for i in xrange(0, len(x-1)): f = np.dot(x[i], w) # activation function if f > z: yhat = 1 else: yhat = 0 y_pred.append(yhat) return y_predy_pred = perceptron_test(x_test, w, z, eta, t)print \"The accuracy score is:\"print accuracy_score(y_test, y_pred)Out:The accuracy score is:1.0"
},
{
"code": null,
"e": 19362,
"s": 19207,
"text": "A score of 1.0 indicates that our model correctly made predictions on all of the test data. This dataset is clearly separable, so we’d expect this result."
},
{
"code": null,
"e": 19475,
"s": 19362,
"text": "The final step is to compare our results with the Perceptron from scikit-learn. Here’s the code from that model:"
},
{
"code": null,
"e": 19689,
"s": 19475,
"text": "from sklearn.linear_model import Perceptron# training the sklearn Perceptronclf = Perceptron(random_state=None, eta0=0.1, shuffle=False, fit_intercept=False)clf.fit(x_train, y_train)y_predict = clf.predict(x_test)"
},
{
"code": null,
"e": 19790,
"s": 19689,
"text": "Now that we’ve trained the model, lets compare the weights to the weights that our model calculated."
},
{
"code": null,
"e": 19907,
"s": 19790,
"text": "Out:sklearn weights:[-0.5 -0.29850122 0.35054929]my perceptron weights:[-0.5 -0.29850122 0.35054929]"
},
{
"code": null,
"e": 20046,
"s": 19907,
"text": "The weights from the scikit-learn model are identical to our weights. This means that our model is working correctly, which is great news."
},
{
"code": null,
"e": 20286,
"s": 20046,
"text": "There’s a few minor points to go over before we wrap up. In the scikit-learn model we had to set the random state to ‘None’ and turn off the shuffling. We already set a random seed and shuffled the data, so we didn’t need to do this again."
},
{
"code": null,
"e": 20367,
"s": 20286,
"text": "We also had to set the learning rate ‘eta0’ to 0.1 to be identical to our model."
},
{
"code": null,
"e": 20562,
"s": 20367,
"text": "The final point is the intercept. Since we already include a dummy feature column of 1s we were fitting intercept automatically, so we didn’t need to turn this on in the scikit-learn Perceptron."
},
{
"code": null,
"e": 20689,
"s": 20562,
"text": "These all seem like minor details, but if we didn’t set these, we wouldn’t be able to reproduce the same results as our model."
},
{
"code": null,
"e": 20839,
"s": 20689,
"text": "This is an important point. Before using a model, it’s very important to read the documentation and understand what all of the different settings do."
},
{
"code": null,
"e": 20901,
"s": 20839,
"text": "This last step in the process is probably the most important."
},
{
"code": null,
"e": 21092,
"s": 20901,
"text": "You’ve just gone through all the work of learning, taking notes, writing the algorithm from scratch, and comparing it with a trusted implementation. Don’t let all that good work go to waste!"
},
{
"code": null,
"e": 21145,
"s": 21092,
"text": "Writing up the process is important for two reasons:"
},
{
"code": null,
"e": 21240,
"s": 21145,
"text": "You’ll gain an even deeper understanding because you’re teaching others what you just learned."
},
{
"code": null,
"e": 21284,
"s": 21240,
"text": "You can showcase it to potential employers."
},
{
"code": null,
"e": 21453,
"s": 21284,
"text": "It’s one thing to show that you can implement an algorithm from a machine learning library, but it’s even more impressive if you can implement it yourself from scratch."
},
{
"code": null,
"e": 21521,
"s": 21453,
"text": "A great way to showcase your work is with a GitHub Pages portfolio."
},
{
"code": null,
"e": 21591,
"s": 21521,
"text": "In this post we learned how to implement the Perceptron from scratch."
},
{
"code": null,
"e": 21702,
"s": 21591,
"text": "More importantly, we learned how to find useful learning resources, and how to break an algorithm into chunks."
},
{
"code": null,
"e": 21786,
"s": 21702,
"text": "We then learned how to implement and test an algorithm in code using a toy dataset."
},
{
"code": null,
"e": 21879,
"s": 21786,
"text": "Finally, we finished up by comparing the results from our model to a trusted implementation."
},
{
"code": null,
"e": 21986,
"s": 21879,
"text": "This is a great methodology to learn an algorithm on a deeper level so that you can implement it yourself."
}
] |
How will you travel from child to parent with xpath in Selenium with python?
|
We can identify a parent from its children in DOM with the help of xpath. There are situations where we have dynamic attributes for the parent node in html but the child nodes have unique static attributes for identification.
This can be achieved with the help of relative xpath along with the parent xpath axe. Method.
driver. find_element_by_xpath("//input[@id='job']/parent::div")
Code Implementation for child to parent traversal.
from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke #actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/tutor_connect/index.php")
#to refresh the browser
driver.refresh()
# identifying the edit box with the help of xpath parent
atb=driver.find_element_by_xpath ("//input[@id='txtSearchText']/parent::div")
#prints the class attribute value in console
val = atb.get_attribute("class")
print(val)
driver.close()
|
[
{
"code": null,
"e": 1288,
"s": 1062,
"text": "We can identify a parent from its children in DOM with the help of xpath. There are situations where we have dynamic attributes for the parent node in html but the child nodes have unique static attributes for identification."
},
{
"code": null,
"e": 1382,
"s": 1288,
"text": "This can be achieved with the help of relative xpath along with the parent xpath axe. Method."
},
{
"code": null,
"e": 1446,
"s": 1382,
"text": "driver. find_element_by_xpath(\"//input[@id='job']/parent::div\")"
},
{
"code": null,
"e": 1497,
"s": 1446,
"text": "Code Implementation for child to parent traversal."
},
{
"code": null,
"e": 2165,
"s": 1497,
"text": "from selenium import webdriver\n#browser exposes an executable file\n#Through Selenium test we will invoke the executable file which will then #invoke #actual browser\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\n# to maximize the browser window\ndriver.maximize_window()\n#get method to launch the URL\ndriver.get(\"https://www.tutorialspoint.com/tutor_connect/index.php\")\n#to refresh the browser\ndriver.refresh()\n# identifying the edit box with the help of xpath parent\natb=driver.find_element_by_xpath (\"//input[@id='txtSearchText']/parent::div\")\n#prints the class attribute value in console\nval = atb.get_attribute(\"class\")\nprint(val)\ndriver.close()"
}
] |
Text Generation Using Recurrent Neural Networks | by Donald Dong | Towards Data Science
|
Text generation is a popular problem in Data Science and Machine Learning, and it is a suitable task for Recurrent Neural Nets. This report uses TensorFlow to build an RNN text generator and builds a high-level API in Python3. The report is inspired by @karpathy ( min-char-rnn) and Aurélien Géron ( Hands-On Machine Learning with Scikit-Learn and TensorFlow ). This is a class project in CST463 — Advanced Machine Learning at Cal State Monterey Bay, instructed by Dr. Glenn Bruns.
Dataset, RNNTextGenerator, and ModelSelector are the three main modules. For the documentation please check out this project on Github.
Defined in src/dataset.py
Creates a text dataset contains the one-hot encoded text data. It produces batches of sequences of encoded labels. We split the text data into batches are used to train the RNN, and we sample a random chuck of the text (with given length) to evaluate the performance of our model.
Defined in src/text_generator.py
Creates a recurrent neural network with a TensorFlow RNN cell (which performs dynamic unrolling of the inputs). It has an output projection layer which produces the final probability for each character class. It generates the text by sampling the next character based on the probability distribution of the last character of the current sequence.
We use Alice in Wonderland as the text.
We can see the accuracy and loss have not converged. Each fit call will run one epoch (we passed epoch=1 to the constructor).
We want to continue fitting the model with more epochs for 30 more seconds, and we’re interested in how the model improves over time.
test acc: 0.535040020942688, test loss: 1.592130422592163Yes, but much towe this NOT, aft open') said 'Letger comimpie hone,'U VERY up in aborious, it with the adge,-----------------------test acc: 0.5360000133514404, test loss: 1.5756181478500366Yes, but the Habembood cacs must, was the lang donant as perpen my his huril about harriered me shreep), whre-----------------------test acc: 0.5430399775505066, test loss: 1.5500394105911255Yes, but to Alice.So thenhep datee went orling,' said Alice,' said had geined,' she you not!' said thenil-----------------------test acc: 0.5302400588989258, test loss: 1.6037070751190186Yes, but the could mould cobl over howner? Now that oplo-thing to her orverewn.''Why, toherself!The Qu-e-----------------------test acc: 0.539199948310852, test loss: 1.6024020910263062Yes, but the Queen home way the at the placsarnd of the sat a it,' the QUED INK Affece herge how eacushing ov-----------------------test acc: 0.5388799905776978, test loss: 1.538255214691162Yes, but did they rossan that may the sing,' sayeing, round queer thatled thing's she went on, I'm she can wa-----------------------test acc: 0.5424000024795532, test loss: 1.5805484056472778Yes, but first's word.' She was byself, if our it was en!' seemes you seleasions of the doous rige out oldes-----------------------test acc: 0.5455999970436096, test loss: 1.5576822757720947Yes, but the other-- Whereet heam who her notone and it didn't knowling e s-----------------------
We can see the generated text does become better over time. There are more actual words in the sentence. The test accuracy and loss are still improving.
Now, we will try different hyperparameters.
Defined in src/model_selector.py
Performs randomized search and rank the models by accuracy. It selects the best ranking models and allows lengthy searching (for hours/days).
We define a large search space for the model selector and give it 24 hours to search. We hope it would discover an excellent model for the Alice in Wonderland text.
The best model the selector has seen uses a GRU Cell with 320 neurons and leaky_relu as the activation function. It uses an AdamOptimizer with a learning rate of 0.006. It's trained in 45 epochs, with 91 sequences per batch (batch_size). It has an average accuracy of 0.6245 and loss of 1.25 over 5 randomly sampled test sequences.
Yes, but to talk about this of ketched him in the puppy juging said to the tell messave off, things very unfusts, and that put on hesserriely I’ll make the pu
We consider epoch as a hyperparameter of the model since a big number of epochs can allow the neural net to overfit and perform poorly on the test sequences. Thus, the best model from the selector is the final model we will use.
The best text generator is deployed as a simple web application (https://www.ddong.me/alice-text-gen) for educational purposes.
|
[
{
"code": null,
"e": 656,
"s": 172,
"text": "Text generation is a popular problem in Data Science and Machine Learning, and it is a suitable task for Recurrent Neural Nets. This report uses TensorFlow to build an RNN text generator and builds a high-level API in Python3. The report is inspired by @karpathy ( min-char-rnn) and Aurélien Géron ( Hands-On Machine Learning with Scikit-Learn and TensorFlow ). This is a class project in CST463 — Advanced Machine Learning at Cal State Monterey Bay, instructed by Dr. Glenn Bruns."
},
{
"code": null,
"e": 792,
"s": 656,
"text": "Dataset, RNNTextGenerator, and ModelSelector are the three main modules. For the documentation please check out this project on Github."
},
{
"code": null,
"e": 818,
"s": 792,
"text": "Defined in src/dataset.py"
},
{
"code": null,
"e": 1099,
"s": 818,
"text": "Creates a text dataset contains the one-hot encoded text data. It produces batches of sequences of encoded labels. We split the text data into batches are used to train the RNN, and we sample a random chuck of the text (with given length) to evaluate the performance of our model."
},
{
"code": null,
"e": 1132,
"s": 1099,
"text": "Defined in src/text_generator.py"
},
{
"code": null,
"e": 1479,
"s": 1132,
"text": "Creates a recurrent neural network with a TensorFlow RNN cell (which performs dynamic unrolling of the inputs). It has an output projection layer which produces the final probability for each character class. It generates the text by sampling the next character based on the probability distribution of the last character of the current sequence."
},
{
"code": null,
"e": 1519,
"s": 1479,
"text": "We use Alice in Wonderland as the text."
},
{
"code": null,
"e": 1645,
"s": 1519,
"text": "We can see the accuracy and loss have not converged. Each fit call will run one epoch (we passed epoch=1 to the constructor)."
},
{
"code": null,
"e": 1779,
"s": 1645,
"text": "We want to continue fitting the model with more epochs for 30 more seconds, and we’re interested in how the model improves over time."
},
{
"code": null,
"e": 3259,
"s": 1779,
"text": "test acc: 0.535040020942688, test loss: 1.592130422592163Yes, but much towe this NOT, aft open') said 'Letger comimpie hone,'U VERY up in aborious, it with the adge,-----------------------test acc: 0.5360000133514404, test loss: 1.5756181478500366Yes, but the Habembood cacs must, was the lang donant as perpen my his huril about harriered me shreep), whre-----------------------test acc: 0.5430399775505066, test loss: 1.5500394105911255Yes, but to Alice.So thenhep datee went orling,' said Alice,' said had geined,' she you not!' said thenil-----------------------test acc: 0.5302400588989258, test loss: 1.6037070751190186Yes, but the could mould cobl over howner? Now that oplo-thing to her orverewn.''Why, toherself!The Qu-e-----------------------test acc: 0.539199948310852, test loss: 1.6024020910263062Yes, but the Queen home way the at the placsarnd of the sat a it,' the QUED INK Affece herge how eacushing ov-----------------------test acc: 0.5388799905776978, test loss: 1.538255214691162Yes, but did they rossan that may the sing,' sayeing, round queer thatled thing's she went on, I'm she can wa-----------------------test acc: 0.5424000024795532, test loss: 1.5805484056472778Yes, but first's word.' She was byself, if our it was en!' seemes you seleasions of the doous rige out oldes-----------------------test acc: 0.5455999970436096, test loss: 1.5576822757720947Yes, but the other-- Whereet heam who her notone and it didn't knowling e s-----------------------"
},
{
"code": null,
"e": 3412,
"s": 3259,
"text": "We can see the generated text does become better over time. There are more actual words in the sentence. The test accuracy and loss are still improving."
},
{
"code": null,
"e": 3456,
"s": 3412,
"text": "Now, we will try different hyperparameters."
},
{
"code": null,
"e": 3489,
"s": 3456,
"text": "Defined in src/model_selector.py"
},
{
"code": null,
"e": 3631,
"s": 3489,
"text": "Performs randomized search and rank the models by accuracy. It selects the best ranking models and allows lengthy searching (for hours/days)."
},
{
"code": null,
"e": 3796,
"s": 3631,
"text": "We define a large search space for the model selector and give it 24 hours to search. We hope it would discover an excellent model for the Alice in Wonderland text."
},
{
"code": null,
"e": 4128,
"s": 3796,
"text": "The best model the selector has seen uses a GRU Cell with 320 neurons and leaky_relu as the activation function. It uses an AdamOptimizer with a learning rate of 0.006. It's trained in 45 epochs, with 91 sequences per batch (batch_size). It has an average accuracy of 0.6245 and loss of 1.25 over 5 randomly sampled test sequences."
},
{
"code": null,
"e": 4287,
"s": 4128,
"text": "Yes, but to talk about this of ketched him in the puppy juging said to the tell messave off, things very unfusts, and that put on hesserriely I’ll make the pu"
},
{
"code": null,
"e": 4516,
"s": 4287,
"text": "We consider epoch as a hyperparameter of the model since a big number of epochs can allow the neural net to overfit and perform poorly on the test sequences. Thus, the best model from the selector is the final model we will use."
}
] |
\circledR - Tex Command
|
\circledR - Used to draw circled R.
{ \circledR }
\circledR command draws circled R.
\circledR
®
\circledR
®
\circledR
14 Lectures
52 mins
Ashraf Said
11 Lectures
1 hours
Ashraf Said
9 Lectures
1 hours
Emenwa Global, Ejike IfeanyiChukwu
29 Lectures
2.5 hours
Mohammad Nauman
14 Lectures
1 hours
Daniel Stern
15 Lectures
47 mins
Nishant Kumar
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 8022,
"s": 7986,
"text": "\\circledR - Used to draw circled R."
},
{
"code": null,
"e": 8036,
"s": 8022,
"text": "{ \\circledR }"
},
{
"code": null,
"e": 8071,
"s": 8036,
"text": "\\circledR command draws circled R."
},
{
"code": null,
"e": 8088,
"s": 8071,
"text": "\n\\circledR\n\n®\n\n\n"
},
{
"code": null,
"e": 8103,
"s": 8088,
"text": "\\circledR\n\n®\n\n"
},
{
"code": null,
"e": 8113,
"s": 8103,
"text": "\\circledR"
},
{
"code": null,
"e": 8145,
"s": 8113,
"text": "\n 14 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 8158,
"s": 8145,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8191,
"s": 8158,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8204,
"s": 8191,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8236,
"s": 8204,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8272,
"s": 8236,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8307,
"s": 8272,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8324,
"s": 8307,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 8357,
"s": 8324,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8371,
"s": 8357,
"text": " Daniel Stern"
},
{
"code": null,
"e": 8403,
"s": 8371,
"text": "\n 15 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 8418,
"s": 8403,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 8425,
"s": 8418,
"text": " Print"
},
{
"code": null,
"e": 8436,
"s": 8425,
"text": " Add Notes"
}
] |
Overlapping Y-axis tick label and X-axis tick label in Matplotlib
|
To reduce the chances of overlapping between x and y tick labels in matplotlib, we can take the following steps −
Create x and y data points using numpy.
Create x and y data points using numpy.
Add a subplot to the current figure at index 1 (nrows=1 and ncols=2).
Add a subplot to the current figure at index 1 (nrows=1 and ncols=2).
Set x and y margins to 0.
Set x and y margins to 0.
Plot x and y data points and add a title to this subplot, i.e., "Overlapping".
Plot x and y data points and add a title to this subplot, i.e., "Overlapping".
Add a subplot to the current figure at index 2 (nrows=1 and ncols=2).
Add a subplot to the current figure at index 2 (nrows=1 and ncols=2).
Set x and y margins to 0.
Set x and y margins to 0.
Plot x and y data points and add a title to this subplot, i.e., "Non Overlapping".
Plot x and y data points and add a title to this subplot, i.e., "Non Overlapping".
The objective of MaxNLocator and prune ="lower" is that the smallest tick will be removed.
The objective of MaxNLocator and prune ="lower" is that the smallest tick will be removed.
To display the figure, use show() method.
To display the figure, use show() method.
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
import numpy as np
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
xs = np.linspace(0, 5, 10)
ys = np.linspace(0, 5, 10)
plt.subplot(121)
plt.margins(x=0, y=0)
plt.plot(xs, ys)
plt.title("Overlapping")
plt.subplot(122)
plt.margins(x=0, y=0)
plt.plot(xs, ys)
plt.title("Non overlapping")
plt.gca().xaxis.set_major_locator(MaxNLocator(prune='lower'))
plt.gca().yaxis.set_major_locator(MaxNLocator(prune='lower'))
plt.show()
|
[
{
"code": null,
"e": 1176,
"s": 1062,
"text": "To reduce the chances of overlapping between x and y tick labels in matplotlib, we can take the following steps −"
},
{
"code": null,
"e": 1216,
"s": 1176,
"text": "Create x and y data points using numpy."
},
{
"code": null,
"e": 1256,
"s": 1216,
"text": "Create x and y data points using numpy."
},
{
"code": null,
"e": 1326,
"s": 1256,
"text": "Add a subplot to the current figure at index 1 (nrows=1 and ncols=2)."
},
{
"code": null,
"e": 1396,
"s": 1326,
"text": "Add a subplot to the current figure at index 1 (nrows=1 and ncols=2)."
},
{
"code": null,
"e": 1422,
"s": 1396,
"text": "Set x and y margins to 0."
},
{
"code": null,
"e": 1448,
"s": 1422,
"text": "Set x and y margins to 0."
},
{
"code": null,
"e": 1527,
"s": 1448,
"text": "Plot x and y data points and add a title to this subplot, i.e., \"Overlapping\"."
},
{
"code": null,
"e": 1606,
"s": 1527,
"text": "Plot x and y data points and add a title to this subplot, i.e., \"Overlapping\"."
},
{
"code": null,
"e": 1676,
"s": 1606,
"text": "Add a subplot to the current figure at index 2 (nrows=1 and ncols=2)."
},
{
"code": null,
"e": 1746,
"s": 1676,
"text": "Add a subplot to the current figure at index 2 (nrows=1 and ncols=2)."
},
{
"code": null,
"e": 1772,
"s": 1746,
"text": "Set x and y margins to 0."
},
{
"code": null,
"e": 1798,
"s": 1772,
"text": "Set x and y margins to 0."
},
{
"code": null,
"e": 1881,
"s": 1798,
"text": "Plot x and y data points and add a title to this subplot, i.e., \"Non Overlapping\"."
},
{
"code": null,
"e": 1964,
"s": 1881,
"text": "Plot x and y data points and add a title to this subplot, i.e., \"Non Overlapping\"."
},
{
"code": null,
"e": 2055,
"s": 1964,
"text": "The objective of MaxNLocator and prune =\"lower\" is that the smallest tick will be removed."
},
{
"code": null,
"e": 2146,
"s": 2055,
"text": "The objective of MaxNLocator and prune =\"lower\" is that the smallest tick will be removed."
},
{
"code": null,
"e": 2188,
"s": 2146,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 2230,
"s": 2188,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 2765,
"s": 2230,
"text": "import matplotlib.pyplot as plt\nfrom matplotlib.ticker import MaxNLocator\nimport numpy as np\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nxs = np.linspace(0, 5, 10)\nys = np.linspace(0, 5, 10)\nplt.subplot(121)\nplt.margins(x=0, y=0)\nplt.plot(xs, ys)\nplt.title(\"Overlapping\")\nplt.subplot(122)\nplt.margins(x=0, y=0)\nplt.plot(xs, ys)\nplt.title(\"Non overlapping\")\nplt.gca().xaxis.set_major_locator(MaxNLocator(prune='lower'))\nplt.gca().yaxis.set_major_locator(MaxNLocator(prune='lower'))\nplt.show()"
}
] |
Python Program for Binary Insertion Sort - GeeksforGeeks
|
25 Feb, 2022
We can use binary search to reduce the number of comparisons in normal insertion sort. Binary Insertion Sort find use binary search to find the proper location to insert the selected item at each iteration.In normal insertion, sort it takes O(i) (at ith iteration) in worst case. we can reduce it to O(logi) by using binary search.
# Python Program implementation # of binary insertion sort def binary_search(arr, val, start, end): # we need to distinguish whether we should insert # before or after the left boundary. # imagine [0] is the last step of the binary search # and we need to decide where to insert -1 if start == end: if arr[start] > val: return start else: return start+1 # this occurs if we are moving beyond left\'s boundary # meaning the left boundary is the least position to # find a number greater than val if start > end: return start mid = (start+end)/2 if arr[mid] < val: return binary_search(arr, val, mid+1, end) elif arr[mid] > val: return binary_search(arr, val, start, mid-1) else: return mid def insertion_sort(arr): for i in xrange(1, len(arr)): val = arr[i] j = binary_search(arr, val, 0, i-1) arr = arr[:j] + [val] + arr[j:i] + arr[i+1:] return arr print("Sorted array:")print insertion_sort([37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54]) # Code contributed by Mohit Gupta_OMG
Please refer complete article on Binary Insertion Sort for more details!
surinderdawra388
Insertion Sort
python sorting-exercises
Python Programs
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Appending to list in Python dictionary
Python program to interchange first and last elements in a list
Python Program for QuickSort
How to inverse a matrix using NumPy
Differences and Applications of List, Tuple, Set and Dictionary in Python
|
[
{
"code": null,
"e": 24557,
"s": 24529,
"text": "\n25 Feb, 2022"
},
{
"code": null,
"e": 24889,
"s": 24557,
"text": "We can use binary search to reduce the number of comparisons in normal insertion sort. Binary Insertion Sort find use binary search to find the proper location to insert the selected item at each iteration.In normal insertion, sort it takes O(i) (at ith iteration) in worst case. we can reduce it to O(logi) by using binary search."
},
{
"code": "# Python Program implementation # of binary insertion sort def binary_search(arr, val, start, end): # we need to distinguish whether we should insert # before or after the left boundary. # imagine [0] is the last step of the binary search # and we need to decide where to insert -1 if start == end: if arr[start] > val: return start else: return start+1 # this occurs if we are moving beyond left\\'s boundary # meaning the left boundary is the least position to # find a number greater than val if start > end: return start mid = (start+end)/2 if arr[mid] < val: return binary_search(arr, val, mid+1, end) elif arr[mid] > val: return binary_search(arr, val, start, mid-1) else: return mid def insertion_sort(arr): for i in xrange(1, len(arr)): val = arr[i] j = binary_search(arr, val, 0, i-1) arr = arr[:j] + [val] + arr[j:i] + arr[i+1:] return arr print(\"Sorted array:\")print insertion_sort([37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54]) # Code contributed by Mohit Gupta_OMG ",
"e": 26028,
"s": 24889,
"text": null
},
{
"code": null,
"e": 26101,
"s": 26028,
"text": "Please refer complete article on Binary Insertion Sort for more details!"
},
{
"code": null,
"e": 26118,
"s": 26101,
"text": "surinderdawra388"
},
{
"code": null,
"e": 26133,
"s": 26118,
"text": "Insertion Sort"
},
{
"code": null,
"e": 26158,
"s": 26133,
"text": "python sorting-exercises"
},
{
"code": null,
"e": 26174,
"s": 26158,
"text": "Python Programs"
},
{
"code": null,
"e": 26182,
"s": 26174,
"text": "Sorting"
},
{
"code": null,
"e": 26190,
"s": 26182,
"text": "Sorting"
},
{
"code": null,
"e": 26288,
"s": 26190,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26297,
"s": 26288,
"text": "Comments"
},
{
"code": null,
"e": 26310,
"s": 26297,
"text": "Old Comments"
},
{
"code": null,
"e": 26349,
"s": 26310,
"text": "Appending to list in Python dictionary"
},
{
"code": null,
"e": 26413,
"s": 26349,
"text": "Python program to interchange first and last elements in a list"
},
{
"code": null,
"e": 26442,
"s": 26413,
"text": "Python Program for QuickSort"
},
{
"code": null,
"e": 26478,
"s": 26442,
"text": "How to inverse a matrix using NumPy"
}
] |
CSS - Bounce out Effect
|
Bounce Animation effect is used to move the element quick up, back, or away from a surface after hitting it.
@keyframes bounceOut {
0% {
transform: scale(1);
}
25% {
transform: scale(.95);
}
50% {
opacity: 1;
transform: scale(1.1);
}
100% {
opacity: 0;
transform: scale(.3);
}
}
Transform − Transform applies to 2d and 3d transformation to an element.
Transform − Transform applies to 2d and 3d transformation to an element.
Opacity − Opacity applies to an element to make translucence.
Opacity − Opacity applies to an element to make translucence.
<html>
<head>
<style>
.animated {
background-image: url(/css/images/logo.png);
background-repeat: no-repeat;
background-position: left top;
padding-top:95px;
margin-bottom:60px;
-webkit-animation-duration: 10s;
animation-duration: 10s;
-webkit-animation-fill-mode: both;
animation-fill-mode: both;
}
@-webkit-keyframes bounceOut {
0% {
-webkit-transform: scale(1);
}
25% {
-webkit-transform: scale(.95);
}
50% {
opacity: 1;
-webkit-transform: scale(1.1);
}
100% {
opacity: 0;
-webkit-transform: scale(.3);
}
}
@keyframes bounceOut {
0% {
transform: scale(1);
}
25% {
transform: scale(.95);
}
50% {
opacity: 1;
transform: scale(1.1);
}
100% {
opacity: 0;
transform: scale(.3);
}
}
.bounceOut {
-webkit-animation-name: bounceOut;
animation-name: bounceOut;
}
</style>
</head>
<body>
<div id = "animated-example" class = "animated bounceOut"></div>
<button onclick = "myFunction()">Reload page</button>
<script>
function myFunction() {
location.reload();
}
</script>
</body>
</html>
It will produce the following result −
Academic Tutorials
Big Data & Analytics
Computer Programming
Computer Science
Databases
DevOps
Digital Marketing
Engineering Tutorials
Exams Syllabus
Famous Monuments
GATE Exams Tutorials
Latest Technologies
Machine Learning
Mainframe Development
Management Tutorials
Mathematics Tutorials
Microsoft Technologies
Misc tutorials
Mobile Development
Java Technologies
Python Technologies
SAP Tutorials
Programming Scripts
Selected Reading
Software Quality
Soft Skills
Telecom Tutorials
UPSC IAS Exams
Web Development
Sports Tutorials
XML Technologies
Multi-Language
Interview Questions
Academic Tutorials
Big Data & Analytics
Computer Programming
Computer Science
Databases
DevOps
Digital Marketing
Engineering Tutorials
Exams Syllabus
Famous Monuments
GATE Exams Tutorials
Latest Technologies
Machine Learning
Mainframe Development
Management Tutorials
Mathematics Tutorials
Microsoft Technologies
Misc tutorials
Mobile Development
Java Technologies
Python Technologies
SAP Tutorials
Programming Scripts
Selected Reading
Software Quality
Soft Skills
Telecom Tutorials
UPSC IAS Exams
Web Development
Sports Tutorials
XML Technologies
Multi-Language
Interview Questions
Selected Reading
UPSC IAS Exams Notes
Developer's Best Practices
Questions and Answers
Effective Resume Writing
HR Interview Questions
Computer Glossary
Who is Who
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2735,
"s": 2626,
"text": "Bounce Animation effect is used to move the element quick up, back, or away from a surface after hitting it."
},
{
"code": null,
"e": 2966,
"s": 2735,
"text": "@keyframes bounceOut {\n 0% {\n transform: scale(1);\n }\n 25% {\n transform: scale(.95);\n }\n 50% {\n opacity: 1;\n transform: scale(1.1);\n }\n 100% {\n opacity: 0;\n transform: scale(.3);\n }\n} "
},
{
"code": null,
"e": 3039,
"s": 2966,
"text": "Transform − Transform applies to 2d and 3d transformation to an element."
},
{
"code": null,
"e": 3112,
"s": 3039,
"text": "Transform − Transform applies to 2d and 3d transformation to an element."
},
{
"code": null,
"e": 3174,
"s": 3112,
"text": "Opacity − Opacity applies to an element to make translucence."
},
{
"code": null,
"e": 3236,
"s": 3174,
"text": "Opacity − Opacity applies to an element to make translucence."
},
{
"code": null,
"e": 4915,
"s": 3236,
"text": "<html>\n <head>\n <style>\n .animated {\n background-image: url(/css/images/logo.png);\n background-repeat: no-repeat;\n background-position: left top;\n padding-top:95px;\n margin-bottom:60px;\n -webkit-animation-duration: 10s; \n animation-duration: 10s; \n -webkit-animation-fill-mode: both;\n animation-fill-mode: both;\n }\n \n @-webkit-keyframes bounceOut {\n 0% {\n -webkit-transform: scale(1);\n }\n 25% {\n -webkit-transform: scale(.95);\n }\n 50% {\n opacity: 1;\n -webkit-transform: scale(1.1);\n }\n 100% {\n opacity: 0;\n -webkit-transform: scale(.3);\n }\n }\n \n @keyframes bounceOut {\n 0% {\n transform: scale(1);\n }\n 25% {\n transform: scale(.95);\n }\n 50% {\n opacity: 1;\n transform: scale(1.1);\n }\n 100% {\n opacity: 0;\n transform: scale(.3);\n }\n }\n \n .bounceOut {\n -webkit-animation-name: bounceOut;\n animation-name: bounceOut;\n }\n </style>\n </head>\n\n <body>\n \n <div id = \"animated-example\" class = \"animated bounceOut\"></div>\n <button onclick = \"myFunction()\">Reload page</button>\n \n <script>\n function myFunction() {\n location.reload();\n }\n </script>\n\n </body>\n</html>"
},
{
"code": null,
"e": 4954,
"s": 4915,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 5601,
"s": 4954,
"text": "\n\n Academic Tutorials\n Big Data & Analytics \n Computer Programming \n Computer Science \n Databases \n DevOps \n Digital Marketing \n Engineering Tutorials \n Exams Syllabus \n Famous Monuments \n GATE Exams Tutorials\n Latest Technologies \n Machine Learning \n Mainframe Development \n Management Tutorials \n Mathematics Tutorials\n Microsoft Technologies \n Misc tutorials \n Mobile Development \n Java Technologies \n Python Technologies \n SAP Tutorials \nProgramming Scripts \n Selected Reading \n Software Quality \n Soft Skills \n Telecom Tutorials \n UPSC IAS Exams \n Web Development \n Sports Tutorials \n XML Technologies \n Multi-Language\n Interview Questions\n\n"
},
{
"code": null,
"e": 5621,
"s": 5601,
"text": " Academic Tutorials"
},
{
"code": null,
"e": 5644,
"s": 5621,
"text": " Big Data & Analytics "
},
{
"code": null,
"e": 5667,
"s": 5644,
"text": " Computer Programming "
},
{
"code": null,
"e": 5686,
"s": 5667,
"text": " Computer Science "
},
{
"code": null,
"e": 5698,
"s": 5686,
"text": " Databases "
},
{
"code": null,
"e": 5707,
"s": 5698,
"text": " DevOps "
},
{
"code": null,
"e": 5727,
"s": 5707,
"text": " Digital Marketing "
},
{
"code": null,
"e": 5751,
"s": 5727,
"text": " Engineering Tutorials "
},
{
"code": null,
"e": 5768,
"s": 5751,
"text": " Exams Syllabus "
},
{
"code": null,
"e": 5787,
"s": 5768,
"text": " Famous Monuments "
},
{
"code": null,
"e": 5809,
"s": 5787,
"text": " GATE Exams Tutorials"
},
{
"code": null,
"e": 5831,
"s": 5809,
"text": " Latest Technologies "
},
{
"code": null,
"e": 5850,
"s": 5831,
"text": " Machine Learning "
},
{
"code": null,
"e": 5874,
"s": 5850,
"text": " Mainframe Development "
},
{
"code": null,
"e": 5897,
"s": 5874,
"text": " Management Tutorials "
},
{
"code": null,
"e": 5920,
"s": 5897,
"text": " Mathematics Tutorials"
},
{
"code": null,
"e": 5945,
"s": 5920,
"text": " Microsoft Technologies "
},
{
"code": null,
"e": 5962,
"s": 5945,
"text": " Misc tutorials "
},
{
"code": null,
"e": 5983,
"s": 5962,
"text": " Mobile Development "
},
{
"code": null,
"e": 6003,
"s": 5983,
"text": " Java Technologies "
},
{
"code": null,
"e": 6025,
"s": 6003,
"text": " Python Technologies "
},
{
"code": null,
"e": 6041,
"s": 6025,
"text": " SAP Tutorials "
},
{
"code": null,
"e": 6062,
"s": 6041,
"text": "Programming Scripts "
},
{
"code": null,
"e": 6081,
"s": 6062,
"text": " Selected Reading "
},
{
"code": null,
"e": 6100,
"s": 6081,
"text": " Software Quality "
},
{
"code": null,
"e": 6114,
"s": 6100,
"text": " Soft Skills "
},
{
"code": null,
"e": 6134,
"s": 6114,
"text": " Telecom Tutorials "
},
{
"code": null,
"e": 6151,
"s": 6134,
"text": " UPSC IAS Exams "
},
{
"code": null,
"e": 6169,
"s": 6151,
"text": " Web Development "
},
{
"code": null,
"e": 6188,
"s": 6169,
"text": " Sports Tutorials "
},
{
"code": null,
"e": 6207,
"s": 6188,
"text": " XML Technologies "
},
{
"code": null,
"e": 6223,
"s": 6207,
"text": " Multi-Language"
},
{
"code": null,
"e": 6244,
"s": 6223,
"text": " Interview Questions"
},
{
"code": null,
"e": 6261,
"s": 6244,
"text": "Selected Reading"
},
{
"code": null,
"e": 6282,
"s": 6261,
"text": "UPSC IAS Exams Notes"
},
{
"code": null,
"e": 6309,
"s": 6282,
"text": "Developer's Best Practices"
},
{
"code": null,
"e": 6331,
"s": 6309,
"text": "Questions and Answers"
},
{
"code": null,
"e": 6356,
"s": 6331,
"text": "Effective Resume Writing"
},
{
"code": null,
"e": 6379,
"s": 6356,
"text": "HR Interview Questions"
},
{
"code": null,
"e": 6397,
"s": 6379,
"text": "Computer Glossary"
},
{
"code": null,
"e": 6408,
"s": 6397,
"text": "Who is Who"
},
{
"code": null,
"e": 6415,
"s": 6408,
"text": " Print"
},
{
"code": null,
"e": 6426,
"s": 6415,
"text": " Add Notes"
}
] |
Named Entity Recognition - GeeksforGeeks
|
15 Feb, 2022
The named entity recognition (NER) is one of the most data preprocessing task. It involves the identification of key information in the text and classification into a set of predefined categories. An entity is basically the thing that is consistently talked about or refer to in the text.
NER is the form of NLP.
At its core, NLP is just a two-step process, below are the two steps that are involved:
Detecting the entities from the text
Classifying them into different categories
Some of the categories that are the most important architecture in NER such that:
Person
Organization
Place/ location
Other common tasks include classifying of the following:
date/time.
expression
Numeral measurement (money, percent, weight, etc)
E-mail address
Ambiguity in NE
For a person, the category definition is intuitively quite clear, but for computers, there is some ambiguity in classification. Let’s look at some ambiguous example:England (Organisation) won the 2019 world cup vs The 2019 world cup happened in England(Location).Washington(Location) is the capital of the US vs The first president of the US was Washington(Person).
England (Organisation) won the 2019 world cup vs The 2019 world cup happened in England(Location).
Washington(Location) is the capital of the US vs The first president of the US was Washington(Person).
Methods of NER
One way is to train the model for multi-class classification using different machine learning algorithms, but it requires a lot of labelling. In addition to labelling the model also requires a deep understanding of context to deal with the ambiguity of the sentences. This makes it a challenging task for simple machine learning /
Another way is that Conditional random field that is implemented by both NLP Speech Tagger and NLTK. It is a probabilistic model that can be used to model sequential data such as words. The CRF can capture a deep understanding of the context of the sentence. In this model, the input
Deep Learning Based NER: deep learning NER is much more accurate than previous method, as it is capable to assemble words. This is due to the fact that it used a method called word embedding, that is capable of understanding the semantic and syntactic relationship between various words. It is also able to learn analyzes topic-specific as well as high level words automatically. This makes deep learning NER applicable for performing multiple tasks. Deep learning can do most of the repetitive work itself, hence researchers for example can use their time more efficiently.
Implementation
In this implementation, we will perform Named Entity Recognition using two different frameworks: Spacy and NLTK. This code can be run on colab, however for visualization purpose. I recommend the local environment. We can install the following frameworks using pip install
First, we performed Named Entity recognition using Spacy.
Python3
# command to run before code! pip install spacy! pip install nltk! python -m spacy download en_core_web_sm # imports and load spacy english language packageimport spacyfrom spacy import displacyfrom spacy import tokenizernlp = spacy.load('en_core_web_sm') #Load the text and process it# I copied the text from python wikitext =("Python is an interpreted, high-level and general-purpose programming language "Pythons design philosophy emphasizes code readability with" "its notable use of significant indentation." "Its language constructs and object-oriented approach aim to" "help programmers write clear and" "logical code for small and large-scale projects")# text2 = # copy the paragraphs from https://www.python.org/doc/essays/ doc = nlp(text)#doc2 = nlp(text2)sentences = list(doc.sents)print(sentences)# tokenizationfor token in doc: print(token.text)# print entitiesents = [(e.text, e.start_char, e.end_char, e.label_) for e in doc.ents]print(ents)# now we use displaycy function on doc2displacy.render(doc, style='ent', jupyter=True)
[Python is an interpreted, high-level and general-purpose programming language.,
Pythons design philosophy emphasizes code readability with its notable use of significant indentation.,
Its language constructs and object-oriented approachaim to help programmers write clear, logical code for small and large-scale projects]
# tokens
Python
is
an
interpreted
,
high
-
level
and
general
-
purpose
programming
language
.
Pythons
design
philosophy
emphasizes
code
readability
with
its
notable
use
of
significant
indentation
.
Its
language
constructs
and
object
-
oriented
approachaim
to
help
programmers
write
clear
,
logical
code
for
small
and
large
-
scale
projects
# named entity
[('Python', 0, 6, 'ORG')]
#here ORG stands for Organization
Spacy entity tags on doc2
Below is a list and their meaning of spacy entity tags:
Spacy Named Entity recognition Tags
Now we performed the named entity recognition task on NLTK.
Python3
# import modules and download packagesimport nltknltk.download('words')nltk.download('punkt')nltk.download('maxent_ne_chunker')nltk.download('averaged_perceptron_tagger')nltk.download('state_union')from nltk.corpus import state_unionfrom nltk.tokenize import PunktSentenceTokenizer # process the text and print Named entities# tokenizationtrain_text = state_union.raw() sample_text = state_union.raw("2006-GWBush.txt")custom_sent_tokenizer = PunktSentenceTokenizer(train_text)tokenized = custom_sent_tokenizer.tokenize(sample_text)# function def get_named _entity(): try: for i in tokenized: words = nltk.word_tokenize(i) tagged = nltk.pos_tag(words) namedEnt = nltk.ne_chunk(tagged, binary=False) namedEnt.draw() except: passget_named_entity()
A sentence Example of NER
simmytarika5
Natural-language-processing
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
Intuition of Adam Optimizer
CNN | Introduction to Pooling Layer
Convolutional Neural Network (CNN) in Machine Learning
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 25613,
"s": 25585,
"text": "\n15 Feb, 2022"
},
{
"code": null,
"e": 25902,
"s": 25613,
"text": "The named entity recognition (NER) is one of the most data preprocessing task. It involves the identification of key information in the text and classification into a set of predefined categories. An entity is basically the thing that is consistently talked about or refer to in the text."
},
{
"code": null,
"e": 25926,
"s": 25902,
"text": "NER is the form of NLP."
},
{
"code": null,
"e": 26014,
"s": 25926,
"text": "At its core, NLP is just a two-step process, below are the two steps that are involved:"
},
{
"code": null,
"e": 26051,
"s": 26014,
"text": "Detecting the entities from the text"
},
{
"code": null,
"e": 26094,
"s": 26051,
"text": "Classifying them into different categories"
},
{
"code": null,
"e": 26176,
"s": 26094,
"text": "Some of the categories that are the most important architecture in NER such that:"
},
{
"code": null,
"e": 26183,
"s": 26176,
"text": "Person"
},
{
"code": null,
"e": 26196,
"s": 26183,
"text": "Organization"
},
{
"code": null,
"e": 26212,
"s": 26196,
"text": "Place/ location"
},
{
"code": null,
"e": 26269,
"s": 26212,
"text": "Other common tasks include classifying of the following:"
},
{
"code": null,
"e": 26280,
"s": 26269,
"text": "date/time."
},
{
"code": null,
"e": 26291,
"s": 26280,
"text": "expression"
},
{
"code": null,
"e": 26341,
"s": 26291,
"text": "Numeral measurement (money, percent, weight, etc)"
},
{
"code": null,
"e": 26356,
"s": 26341,
"text": "E-mail address"
},
{
"code": null,
"e": 26372,
"s": 26356,
"text": "Ambiguity in NE"
},
{
"code": null,
"e": 26738,
"s": 26372,
"text": "For a person, the category definition is intuitively quite clear, but for computers, there is some ambiguity in classification. Let’s look at some ambiguous example:England (Organisation) won the 2019 world cup vs The 2019 world cup happened in England(Location).Washington(Location) is the capital of the US vs The first president of the US was Washington(Person)."
},
{
"code": null,
"e": 26837,
"s": 26738,
"text": "England (Organisation) won the 2019 world cup vs The 2019 world cup happened in England(Location)."
},
{
"code": null,
"e": 26940,
"s": 26837,
"text": "Washington(Location) is the capital of the US vs The first president of the US was Washington(Person)."
},
{
"code": null,
"e": 26955,
"s": 26940,
"text": "Methods of NER"
},
{
"code": null,
"e": 27286,
"s": 26955,
"text": "One way is to train the model for multi-class classification using different machine learning algorithms, but it requires a lot of labelling. In addition to labelling the model also requires a deep understanding of context to deal with the ambiguity of the sentences. This makes it a challenging task for simple machine learning /"
},
{
"code": null,
"e": 27572,
"s": 27286,
"text": "Another way is that Conditional random field that is implemented by both NLP Speech Tagger and NLTK. It is a probabilistic model that can be used to model sequential data such as words. The CRF can capture a deep understanding of the context of the sentence. In this model, the input "
},
{
"code": null,
"e": 28147,
"s": 27572,
"text": "Deep Learning Based NER: deep learning NER is much more accurate than previous method, as it is capable to assemble words. This is due to the fact that it used a method called word embedding, that is capable of understanding the semantic and syntactic relationship between various words. It is also able to learn analyzes topic-specific as well as high level words automatically. This makes deep learning NER applicable for performing multiple tasks. Deep learning can do most of the repetitive work itself, hence researchers for example can use their time more efficiently."
},
{
"code": null,
"e": 28162,
"s": 28147,
"text": "Implementation"
},
{
"code": null,
"e": 28434,
"s": 28162,
"text": "In this implementation, we will perform Named Entity Recognition using two different frameworks: Spacy and NLTK. This code can be run on colab, however for visualization purpose. I recommend the local environment. We can install the following frameworks using pip install"
},
{
"code": null,
"e": 28492,
"s": 28434,
"text": "First, we performed Named Entity recognition using Spacy."
},
{
"code": null,
"e": 28500,
"s": 28492,
"text": "Python3"
},
{
"code": "# command to run before code! pip install spacy! pip install nltk! python -m spacy download en_core_web_sm # imports and load spacy english language packageimport spacyfrom spacy import displacyfrom spacy import tokenizernlp = spacy.load('en_core_web_sm') #Load the text and process it# I copied the text from python wikitext =(\"Python is an interpreted, high-level and general-purpose programming language \"Pythons design philosophy emphasizes code readability with\" \"its notable use of significant indentation.\" \"Its language constructs and object-oriented approach aim to\" \"help programmers write clear and\" \"logical code for small and large-scale projects\")# text2 = # copy the paragraphs from https://www.python.org/doc/essays/ doc = nlp(text)#doc2 = nlp(text2)sentences = list(doc.sents)print(sentences)# tokenizationfor token in doc: print(token.text)# print entitiesents = [(e.text, e.start_char, e.end_char, e.label_) for e in doc.ents]print(ents)# now we use displaycy function on doc2displacy.render(doc, style='ent', jupyter=True)",
"e": 29581,
"s": 28500,
"text": null
},
{
"code": null,
"e": 30324,
"s": 29581,
"text": "[Python is an interpreted, high-level and general-purpose programming language.,\n Pythons design philosophy emphasizes code readability with its notable use of significant indentation.,\n Its language constructs and object-oriented approachaim to help programmers write clear, logical code for small and large-scale projects]\n # tokens\n Python\nis\nan\ninterpreted\n,\nhigh\n-\nlevel\nand\ngeneral\n-\npurpose\nprogramming\nlanguage\n.\nPythons\ndesign\nphilosophy\nemphasizes\ncode\nreadability\nwith\nits\nnotable\nuse\nof\nsignificant\nindentation\n.\nIts\nlanguage\nconstructs\nand\nobject\n-\noriented\napproachaim\nto\nhelp\nprogrammers\nwrite\nclear\n,\nlogical\ncode\nfor\nsmall\nand\nlarge\n-\nscale\nprojects\n# named entity\n[('Python', 0, 6, 'ORG')]\n\n#here ORG stands for Organization"
},
{
"code": null,
"e": 30350,
"s": 30324,
"text": "Spacy entity tags on doc2"
},
{
"code": null,
"e": 30406,
"s": 30350,
"text": "Below is a list and their meaning of spacy entity tags:"
},
{
"code": null,
"e": 30442,
"s": 30406,
"text": "Spacy Named Entity recognition Tags"
},
{
"code": null,
"e": 30502,
"s": 30442,
"text": "Now we performed the named entity recognition task on NLTK."
},
{
"code": null,
"e": 30510,
"s": 30502,
"text": "Python3"
},
{
"code": "# import modules and download packagesimport nltknltk.download('words')nltk.download('punkt')nltk.download('maxent_ne_chunker')nltk.download('averaged_perceptron_tagger')nltk.download('state_union')from nltk.corpus import state_unionfrom nltk.tokenize import PunktSentenceTokenizer # process the text and print Named entities# tokenizationtrain_text = state_union.raw() sample_text = state_union.raw(\"2006-GWBush.txt\")custom_sent_tokenizer = PunktSentenceTokenizer(train_text)tokenized = custom_sent_tokenizer.tokenize(sample_text)# function def get_named _entity(): try: for i in tokenized: words = nltk.word_tokenize(i) tagged = nltk.pos_tag(words) namedEnt = nltk.ne_chunk(tagged, binary=False) namedEnt.draw() except: passget_named_entity()",
"e": 31321,
"s": 30510,
"text": null
},
{
"code": null,
"e": 31347,
"s": 31321,
"text": "A sentence Example of NER"
},
{
"code": null,
"e": 31360,
"s": 31347,
"text": "simmytarika5"
},
{
"code": null,
"e": 31388,
"s": 31360,
"text": "Natural-language-processing"
},
{
"code": null,
"e": 31405,
"s": 31388,
"text": "Machine Learning"
},
{
"code": null,
"e": 31412,
"s": 31405,
"text": "Python"
},
{
"code": null,
"e": 31429,
"s": 31412,
"text": "Machine Learning"
},
{
"code": null,
"e": 31527,
"s": 31429,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31568,
"s": 31527,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 31601,
"s": 31568,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 31629,
"s": 31601,
"text": "Intuition of Adam Optimizer"
},
{
"code": null,
"e": 31665,
"s": 31629,
"text": "CNN | Introduction to Pooling Layer"
},
{
"code": null,
"e": 31720,
"s": 31665,
"text": "Convolutional Neural Network (CNN) in Machine Learning"
},
{
"code": null,
"e": 31748,
"s": 31720,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 31798,
"s": 31748,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 31820,
"s": 31798,
"text": "Python map() function"
}
] |
Count numbers which are divisible by all the numbers from 2 to 10 - GeeksforGeeks
|
12 Jul, 2021
Given an integer N, the task is to find the count of numbers from 1 to N which are divisible by all the numbers from 2 to 10.
Examples:
Input: N = 3000 Output: 1 2520 is the only number below 3000 which is divisible by all the numbers from 2 to 10.
Input: N = 2000 Output: 0
Approach: Let’s factorize numbers from 2 to 10.
2 = 2 3 = 3 4 = 22 5 = 5 6 = 2 * 3 7 = 7 8 = 23 9 = 32 10 = 2 * 5
If a number is divisible by all the numbers from 2 to 10, its factorization should contain 2 at least in the power of 3, 3 at least in the power of 2, 5 and 7 at least in the power of 1. So it can be written as:
x * 23 * 32 * 5 * 7 i.e. x * 2520.
So any number divisible by 2520 is divisible by all the numbers from 2 to 10. So, the count of such numbers is N / 2520.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of numbers// from 1 to n which are divisible by// all the numbers from 2 to 10int countNumbers(int n){ return (n / 2520);} // Driver codeint main(){ int n = 3000; cout << countNumbers(n); return 0;}
// Java implementation of the approachclass GFG{ // Function to return the count of numbers// from 1 to n which are divisible by// all the numbers from 2 to 10static int countNumbers(int n){ return (n / 2520);} // Driver codepublic static void main(String args[]){ int n = 3000; System.out.println(countNumbers(n));}} // This code is contributed by Arnab Kundu
# Python3 implementation of the approach # Function to return the count of numbers# from 1 to n which are divisible by# all the numbers from 2 to 10 def countNumbers(n): return n // 2520 # Driver coden = 3000print(countNumbers(n)) # This code is contributed# by Shrikant13
// C# implementation of the approachusing System; class GFG{ // Function to return the count of numbers// from 1 to n which are divisible by// all the numbers from 2 to 10static int countNumbers(int n){ return (n / 2520);} // Driver codepublic static void Main(String []args){ int n = 3000; Console.WriteLine(countNumbers(n));}} // This code is contributed by Arnab Kundu
<?php// PHP implementation of the approach // Function to return the count of numbers// from 1 to n which are divisible by// all the numbers from 2 to 10function countNumbers($n){ return (int)($n / 2520);} // Driver code$n = 3000;echo(countNumbers($n)); // This code is contributed// by Code_Mech.?>
<script> // Javascript implementation of the approach // Function to return the count of numbers// from 1 to n which are divisible by// all the numbers from 2 to 10function countNumbers(n){ return (n / 2520);} // Driver codevar n = 3000; // Function calldocument.write(Math.round(countNumbers(n))); // This code is contributed by Ankita saini </script>
1
Time Complexity: O(1)Auxiliary Space: O(1)
andrew1234
shrikanth13
Code_Mech
ankita_saini
manikarora059
divisibility
Competitive Programming
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multistage Graph (Shortest Path)
Breadth First Traversal ( BFS ) on a 2D array
Shortest path in a directed graph by Dijkstra’s algorithm
Check whether bitwise AND of a number with any subset of an array is zero or not
5 Best Books for Competitive Programming
Program for Fibonacci numbers
Write a program to print all permutations of a given string
Set in C++ Standard Template Library (STL)
C++ Data Types
Coin Change | DP-7
|
[
{
"code": null,
"e": 26357,
"s": 26329,
"text": "\n12 Jul, 2021"
},
{
"code": null,
"e": 26483,
"s": 26357,
"text": "Given an integer N, the task is to find the count of numbers from 1 to N which are divisible by all the numbers from 2 to 10."
},
{
"code": null,
"e": 26495,
"s": 26483,
"text": "Examples: "
},
{
"code": null,
"e": 26608,
"s": 26495,
"text": "Input: N = 3000 Output: 1 2520 is the only number below 3000 which is divisible by all the numbers from 2 to 10."
},
{
"code": null,
"e": 26636,
"s": 26608,
"text": "Input: N = 2000 Output: 0 "
},
{
"code": null,
"e": 26685,
"s": 26636,
"text": "Approach: Let’s factorize numbers from 2 to 10. "
},
{
"code": null,
"e": 26753,
"s": 26685,
"text": "2 = 2 3 = 3 4 = 22 5 = 5 6 = 2 * 3 7 = 7 8 = 23 9 = 32 10 = 2 * 5 "
},
{
"code": null,
"e": 26966,
"s": 26753,
"text": "If a number is divisible by all the numbers from 2 to 10, its factorization should contain 2 at least in the power of 3, 3 at least in the power of 2, 5 and 7 at least in the power of 1. So it can be written as: "
},
{
"code": null,
"e": 27003,
"s": 26966,
"text": "x * 23 * 32 * 5 * 7 i.e. x * 2520. "
},
{
"code": null,
"e": 27124,
"s": 27003,
"text": "So any number divisible by 2520 is divisible by all the numbers from 2 to 10. So, the count of such numbers is N / 2520."
},
{
"code": null,
"e": 27176,
"s": 27124,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27180,
"s": 27176,
"text": "C++"
},
{
"code": null,
"e": 27185,
"s": 27180,
"text": "Java"
},
{
"code": null,
"e": 27193,
"s": 27185,
"text": "Python3"
},
{
"code": null,
"e": 27196,
"s": 27193,
"text": "C#"
},
{
"code": null,
"e": 27200,
"s": 27196,
"text": "PHP"
},
{
"code": null,
"e": 27211,
"s": 27200,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of numbers// from 1 to n which are divisible by// all the numbers from 2 to 10int countNumbers(int n){ return (n / 2520);} // Driver codeint main(){ int n = 3000; cout << countNumbers(n); return 0;}",
"e": 27537,
"s": 27211,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ // Function to return the count of numbers// from 1 to n which are divisible by// all the numbers from 2 to 10static int countNumbers(int n){ return (n / 2520);} // Driver codepublic static void main(String args[]){ int n = 3000; System.out.println(countNumbers(n));}} // This code is contributed by Arnab Kundu",
"e": 27907,
"s": 27537,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the count of numbers# from 1 to n which are divisible by# all the numbers from 2 to 10 def countNumbers(n): return n // 2520 # Driver coden = 3000print(countNumbers(n)) # This code is contributed# by Shrikant13",
"e": 28183,
"s": 27907,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to return the count of numbers// from 1 to n which are divisible by// all the numbers from 2 to 10static int countNumbers(int n){ return (n / 2520);} // Driver codepublic static void Main(String []args){ int n = 3000; Console.WriteLine(countNumbers(n));}} // This code is contributed by Arnab Kundu",
"e": 28564,
"s": 28183,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Function to return the count of numbers// from 1 to n which are divisible by// all the numbers from 2 to 10function countNumbers($n){ return (int)($n / 2520);} // Driver code$n = 3000;echo(countNumbers($n)); // This code is contributed// by Code_Mech.?>",
"e": 28867,
"s": 28564,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to return the count of numbers// from 1 to n which are divisible by// all the numbers from 2 to 10function countNumbers(n){ return (n / 2520);} // Driver codevar n = 3000; // Function calldocument.write(Math.round(countNumbers(n))); // This code is contributed by Ankita saini </script>",
"e": 29231,
"s": 28867,
"text": null
},
{
"code": null,
"e": 29233,
"s": 29231,
"text": "1"
},
{
"code": null,
"e": 29278,
"s": 29235,
"text": "Time Complexity: O(1)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 29289,
"s": 29278,
"text": "andrew1234"
},
{
"code": null,
"e": 29301,
"s": 29289,
"text": "shrikanth13"
},
{
"code": null,
"e": 29311,
"s": 29301,
"text": "Code_Mech"
},
{
"code": null,
"e": 29324,
"s": 29311,
"text": "ankita_saini"
},
{
"code": null,
"e": 29338,
"s": 29324,
"text": "manikarora059"
},
{
"code": null,
"e": 29351,
"s": 29338,
"text": "divisibility"
},
{
"code": null,
"e": 29375,
"s": 29351,
"text": "Competitive Programming"
},
{
"code": null,
"e": 29388,
"s": 29375,
"text": "Mathematical"
},
{
"code": null,
"e": 29401,
"s": 29388,
"text": "Mathematical"
},
{
"code": null,
"e": 29499,
"s": 29401,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29532,
"s": 29499,
"text": "Multistage Graph (Shortest Path)"
},
{
"code": null,
"e": 29578,
"s": 29532,
"text": "Breadth First Traversal ( BFS ) on a 2D array"
},
{
"code": null,
"e": 29636,
"s": 29578,
"text": "Shortest path in a directed graph by Dijkstra’s algorithm"
},
{
"code": null,
"e": 29717,
"s": 29636,
"text": "Check whether bitwise AND of a number with any subset of an array is zero or not"
},
{
"code": null,
"e": 29758,
"s": 29717,
"text": "5 Best Books for Competitive Programming"
},
{
"code": null,
"e": 29788,
"s": 29758,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 29848,
"s": 29788,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 29891,
"s": 29848,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 29906,
"s": 29891,
"text": "C++ Data Types"
}
] |
Pandas Profiling in Python - GeeksforGeeks
|
22 Jun, 2020
The pandas_profiling library in Python include a method named as ProfileReport() which generate a basic report on the input DataFrame.
The report consist of the following:
DataFrame overview,
Each attribute on which DataFrame is defined,
Correlations between attributes (Pearson Correlation and Spearman Correlation), and
A sample of DataFrame.
Syntax :
pandas_profiling.ProfileReport(df, **kwargs)
Example:
Python3
# importing packagesimport pandas as pdimport pandas_profiling as pp # dictionary of datadct = {'ID': {0: 23, 1: 43, 2: 12, 3: 13, 4: 67, 5: 89, 6: 90, 7: 56, 8: 34}, 'Name': {0: 'Ram', 1: 'Deep', 2: 'Yash', 3: 'Aman', 4: 'Arjun', 5: 'Aditya', 6: 'Divya', 7: 'Chalsea', 8: 'Akash' }, 'Marks': {0: 89, 1: 97, 2: 45, 3: 78, 4: 56, 5: 76, 6: 100, 7: 87, 8: 81}, 'Grade': {0: 'B', 1: 'A', 2: 'F', 3: 'C', 4: 'E', 5: 'C', 6: 'A', 7: 'B', 8: 'B'} } # forming dataframe and printingdata = pd.DataFrame(dct)print(data) # forming ProfileReport and save# as output.html fileprofile = pp.ProfileReport(data)profile.to_file("output.html")
Output:
DataFrame
The html file named as output.html is as follows :
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 25871,
"s": 25843,
"text": "\n22 Jun, 2020"
},
{
"code": null,
"e": 26007,
"s": 25871,
"text": "The pandas_profiling library in Python include a method named as ProfileReport() which generate a basic report on the input DataFrame. "
},
{
"code": null,
"e": 26044,
"s": 26007,
"text": "The report consist of the following:"
},
{
"code": null,
"e": 26064,
"s": 26044,
"text": "DataFrame overview,"
},
{
"code": null,
"e": 26110,
"s": 26064,
"text": "Each attribute on which DataFrame is defined,"
},
{
"code": null,
"e": 26194,
"s": 26110,
"text": "Correlations between attributes (Pearson Correlation and Spearman Correlation), and"
},
{
"code": null,
"e": 26217,
"s": 26194,
"text": "A sample of DataFrame."
},
{
"code": null,
"e": 26226,
"s": 26217,
"text": "Syntax :"
},
{
"code": null,
"e": 26271,
"s": 26226,
"text": "pandas_profiling.ProfileReport(df, **kwargs)"
},
{
"code": null,
"e": 26280,
"s": 26271,
"text": "Example:"
},
{
"code": null,
"e": 26288,
"s": 26280,
"text": "Python3"
},
{
"code": "# importing packagesimport pandas as pdimport pandas_profiling as pp # dictionary of datadct = {'ID': {0: 23, 1: 43, 2: 12, 3: 13, 4: 67, 5: 89, 6: 90, 7: 56, 8: 34}, 'Name': {0: 'Ram', 1: 'Deep', 2: 'Yash', 3: 'Aman', 4: 'Arjun', 5: 'Aditya', 6: 'Divya', 7: 'Chalsea', 8: 'Akash' }, 'Marks': {0: 89, 1: 97, 2: 45, 3: 78, 4: 56, 5: 76, 6: 100, 7: 87, 8: 81}, 'Grade': {0: 'B', 1: 'A', 2: 'F', 3: 'C', 4: 'E', 5: 'C', 6: 'A', 7: 'B', 8: 'B'} } # forming dataframe and printingdata = pd.DataFrame(dct)print(data) # forming ProfileReport and save# as output.html fileprofile = pp.ProfileReport(data)profile.to_file(\"output.html\")",
"e": 27083,
"s": 26288,
"text": null
},
{
"code": null,
"e": 27091,
"s": 27083,
"text": "Output:"
},
{
"code": null,
"e": 27101,
"s": 27091,
"text": "DataFrame"
},
{
"code": null,
"e": 27152,
"s": 27101,
"text": "The html file named as output.html is as follows :"
},
{
"code": null,
"e": 27166,
"s": 27152,
"text": "Python-pandas"
},
{
"code": null,
"e": 27173,
"s": 27166,
"text": "Python"
},
{
"code": null,
"e": 27271,
"s": 27173,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27289,
"s": 27271,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27324,
"s": 27289,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27356,
"s": 27324,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27378,
"s": 27356,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27420,
"s": 27378,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27450,
"s": 27420,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27476,
"s": 27450,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27505,
"s": 27476,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27549,
"s": 27505,
"text": "Reading and Writing to text files in Python"
}
] |
How to Remove rows in Numpy array that contains non-numeric values? - GeeksforGeeks
|
25 Oct, 2020
Many times we have non-numeric values in NumPy array. These values need to be removed, so that array will be free from all these unnecessary values and look more decent. It is possible to remove all rows containing Nan values using the Bitwise NOT operator and np.isnan() function.
Example 1:
Python3
# Importing Numpy moduleimport numpy as np # Creating 2X3 2-D Numpy arrayn_arr = np.array([[10.5, 22.5, 3.8], [41, np.nan, np.nan]]) print("Given array:")print(n_arr) print("\nRemove all rows containing non-numeric elements")print(n_arr[~np.isnan(n_arr).any(axis=1)])
Output:
In the above example, we remove row containing non-numeric values from the 2X3 Numpy array.
Example 2:
Python3
# Importing Numpy module import numpy as np # Creating 3X3 2-D Numpy arrayn_arr = np.array([[10.5, 22.5, 3.8], [23.45, 50, 78.7], [41, np.nan, np.nan]]) print("Given array:")print(n_arr) print("\nRemove all rows containing non-numeric elements")print(n_arr[~np.isnan(n_arr).any(axis=1)])
Output:
In the above example, we remove row containing non-numeric values from the 3X3 Numpy array.
Example 3:
Python3
# Importing Numpy moduleimport numpy as np # Creating 5X4 2-D Numpy arrayn_arr = np.array([[10.5, 22.5, 3.8, 5], [23.45, 50, 78.7, 3.5], [41, np.nan, np.nan, 0], [20, 50.20, np.nan, 2.5], [18.8, 50.60, 8.8, 58.6]]) print("Given array:")print(n_arr) print("\nRemove all rows containing non-numeric elements")print(n_arr[~np.isnan(n_arr).any(axis=1)])
Output:
In the above example, we remove rows containing non-numeric values from the 5X4 Numpy array.
Python numpy-Logic Functions
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n25 Oct, 2020"
},
{
"code": null,
"e": 25819,
"s": 25537,
"text": "Many times we have non-numeric values in NumPy array. These values need to be removed, so that array will be free from all these unnecessary values and look more decent. It is possible to remove all rows containing Nan values using the Bitwise NOT operator and np.isnan() function."
},
{
"code": null,
"e": 25830,
"s": 25819,
"text": "Example 1:"
},
{
"code": null,
"e": 25838,
"s": 25830,
"text": "Python3"
},
{
"code": "# Importing Numpy moduleimport numpy as np # Creating 2X3 2-D Numpy arrayn_arr = np.array([[10.5, 22.5, 3.8], [41, np.nan, np.nan]]) print(\"Given array:\")print(n_arr) print(\"\\nRemove all rows containing non-numeric elements\")print(n_arr[~np.isnan(n_arr).any(axis=1)])",
"e": 26126,
"s": 25838,
"text": null
},
{
"code": null,
"e": 26134,
"s": 26126,
"text": "Output:"
},
{
"code": null,
"e": 26226,
"s": 26134,
"text": "In the above example, we remove row containing non-numeric values from the 2X3 Numpy array."
},
{
"code": null,
"e": 26237,
"s": 26226,
"text": "Example 2:"
},
{
"code": null,
"e": 26245,
"s": 26237,
"text": "Python3"
},
{
"code": "# Importing Numpy module import numpy as np # Creating 3X3 2-D Numpy arrayn_arr = np.array([[10.5, 22.5, 3.8], [23.45, 50, 78.7], [41, np.nan, np.nan]]) print(\"Given array:\")print(n_arr) print(\"\\nRemove all rows containing non-numeric elements\")print(n_arr[~np.isnan(n_arr).any(axis=1)])",
"e": 26571,
"s": 26245,
"text": null
},
{
"code": null,
"e": 26579,
"s": 26571,
"text": "Output:"
},
{
"code": null,
"e": 26671,
"s": 26579,
"text": "In the above example, we remove row containing non-numeric values from the 3X3 Numpy array."
},
{
"code": null,
"e": 26682,
"s": 26671,
"text": "Example 3:"
},
{
"code": null,
"e": 26690,
"s": 26682,
"text": "Python3"
},
{
"code": "# Importing Numpy moduleimport numpy as np # Creating 5X4 2-D Numpy arrayn_arr = np.array([[10.5, 22.5, 3.8, 5], [23.45, 50, 78.7, 3.5], [41, np.nan, np.nan, 0], [20, 50.20, np.nan, 2.5], [18.8, 50.60, 8.8, 58.6]]) print(\"Given array:\")print(n_arr) print(\"\\nRemove all rows containing non-numeric elements\")print(n_arr[~np.isnan(n_arr).any(axis=1)])",
"e": 27111,
"s": 26690,
"text": null
},
{
"code": null,
"e": 27119,
"s": 27111,
"text": "Output:"
},
{
"code": null,
"e": 27212,
"s": 27119,
"text": "In the above example, we remove rows containing non-numeric values from the 5X4 Numpy array."
},
{
"code": null,
"e": 27241,
"s": 27212,
"text": "Python numpy-Logic Functions"
},
{
"code": null,
"e": 27254,
"s": 27241,
"text": "Python-numpy"
},
{
"code": null,
"e": 27261,
"s": 27254,
"text": "Python"
},
{
"code": null,
"e": 27359,
"s": 27261,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27391,
"s": 27359,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27433,
"s": 27391,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27475,
"s": 27433,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27531,
"s": 27475,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27558,
"s": 27531,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27589,
"s": 27558,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27628,
"s": 27589,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27657,
"s": 27628,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 27679,
"s": 27657,
"text": "Defaultdict in Python"
}
] |
Job Sequencing Problem | Set 2 (Using Disjoint Set) - GeeksforGeeks
|
25 Jan, 2021
Given a set of n jobs where each job i has a deadline di >=1 and profit pi>=0. Only one job can be scheduled at a time. Each job takes 1 unit of time to complete. We earn the profit if and only if the job is completed by its deadline. The task is to find the subset of jobs that maximizes profit.
Examples:
Input: Four Jobs with following deadlines and profits
JobID Deadline Profit
a 4 20
b 1 10
c 1 40
d 1 30
Output: Following is maximum profit sequence of jobs:
c, a
Input: Five Jobs with following deadlines and profits
JobID Deadline Profit
a 2 100
b 1 19
c 2 27
d 1 25
e 3 15
Output: Following is maximum profit sequence of jobs:
c, a, e
A greedy solution of time complexity O(n2) is already discussed here. Below is the simple Greedy Algorithm.
Sort all jobs in decreasing order of profit.Initialize the result sequence as first job in sorted jobs.Do following for remaining n-1 jobs If the current job can fit in the current result sequence without missing the deadline, add current job to the result. Else ignore the current job.
Sort all jobs in decreasing order of profit.
Initialize the result sequence as first job in sorted jobs.
Do following for remaining n-1 jobs If the current job can fit in the current result sequence without missing the deadline, add current job to the result. Else ignore the current job.
If the current job can fit in the current result sequence without missing the deadline, add current job to the result. Else ignore the current job.
The costly operation in the Greedy solution is to assign a free slot for a job. We were traversing each and every slot for a job and assigning the greatest possible time slot(<deadline) which was available.What does greatest time slot means? Suppose that a job J1 has a deadline of time t = 5. We assign the greatest time slot which is free and less than the deadline i.e 4-5 for this job. Now another job J2 with deadline of 5 comes in, so the time slot allotted will be 3-4 since 4-5 has already been allotted to job J1.Why to assign greatest time slot(free) to a job? Now we assign the greatest possible time slot since if we assign a time slot even lesser than the available one than there might be some other job which will miss its deadline.
Example: J1 with deadline d1 = 5, profit 40 J2 with deadline d2 = 1, profit 20 Suppose that for job J1 we assigned time slot of 0-1. Now job J2 cannot be performed since we will perform Job J1 during that time slot.Using Disjoint Set for Job Sequencing All time slots are individual sets initially. We first find the maximum deadline of all jobs. Let the max deadline be m. We create m+1 individual sets. If a job is assigned a time slot of t where t >= 0, then the job is scheduled during [t-1, t]. So a set with value X represents the time slot [X-1, X]. We need to keep track of the greatest time slot available which can be allotted to a given job having deadline. We use the parent array of Disjoint Set Data structures for this purpose. The root of the tree is always the latest available slot. If for a deadline d, there is no slot available, then root would be 0. Below are detailed steps.Initialize Disjoint Set: Creates initial disjoint sets.
// m is maximum deadline of a job
parent = new int[m + 1];
// Every node is a parent of itself
for (int i = 0; i ≤ m; i++)
parent[i] = i;
Find : Finds the latest time slot available.
// Returns the maximum available time slot
find(s)
{
// Base case
if (s == parent[s])
return s;
// Recursive call with path compression
return parent[s] = find(parent[s]);
}
Union :
Merges two sets.
// Makes u as parent of v.
union(u, v)
{
// update the greatest available
// free slot to u
parent[v] = u;
}
How come find returns the latest available time slot? Initially all time slots are individual slots. So the time slot returned is always maximum. When we assign a time slot ‘t’ to a job, we do union of ‘t’ with ‘t-1’ in a way that ‘t-1’ becomes parent of ‘t’. To do this we call union(t-1, t). This means that all future queries for time slot t would now return the latest time slot available for set represented by t-1.
Implementation : The following is the implementation of above algorithm.
C++
Java
Python3
// C++ Program to find the maximum profit job sequence// from a given array of jobs with deadlines and profits#include<bits/stdc++.h>using namespace std; // A structure to represent various attributes of a Jobstruct Job{ // Each job has id, deadline and profit char id; int deadLine, profit;}; // A Simple Disjoint Set Data Structurestruct DisjointSet{ int *parent; // Constructor DisjointSet(int n) { parent = new int[n+1]; // Every node is a parent of itself for (int i = 0; i <= n; i++) parent[i] = i; } // Path Compression int find(int s) { /* Make the parent of the nodes in the path from u--> parent[u] point to parent[u] */ if (s == parent[s]) return s; return parent[s] = find(parent[s]); } // Makes u as parent of v. void merge(int u, int v) { //update the greatest available //free slot to u parent[v] = u; }}; // Used to sort in descending order on the basis// of profit for each jobbool cmp(Job a, Job b){ return (a.profit > b.profit);} // Functions returns the maximum deadline from the set// of jobsint findMaxDeadline(struct Job arr[], int n){ int ans = INT_MIN; for (int i = 0; i < n; i++) ans = max(ans, arr[i].deadLine); return ans;} int printJobScheduling(Job arr[], int n){ // Sort Jobs in descending order on the basis // of their profit sort(arr, arr + n, cmp); // Find the maximum deadline among all jobs and // create a disjoint set data structure with // maxDeadline disjoint sets initially. int maxDeadline = findMaxDeadline(arr, n); DisjointSet ds(maxDeadline); // Traverse through all the jobs for (int i = 0; i < n; i++) { // Find the maximum available free slot for // this job (corresponding to its deadline) int availableSlot = ds.find(arr[i].deadLine); // If maximum available free slot is greater // than 0, then free slot available if (availableSlot > 0) { // This slot is taken by this job 'i' // so we need to update the greatest // free slot. Note that, in merge, we // make first parameter as parent of // second parameter. So future queries // for availableSlot will return maximum // available slot in set of // "availableSlot - 1" ds.merge(ds.find(availableSlot - 1), availableSlot); cout << arr[i].id << " "; } }} // Driver codeint main(){ Job arr[] = { { 'a', 2, 100 }, { 'b', 1, 19 }, { 'c', 2, 27 }, { 'd', 1, 25 }, { 'e', 3, 15 } }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Following jobs need to be " << "executed for maximum profit\n"; printJobScheduling(arr, n); return 0;}
// Java program to find the maximum profit job sequence// from a given array of jobs with deadlines and profitsimport java.util.*; // A Simple Disjoint Set Data Structureclass DisjointSet{ int parent[]; // Constructor DisjointSet(int n) { parent = new int[n + 1]; // Every node is a parent of itself for (int i = 0; i <= n; i++) parent[i] = i; } // Path Compression int find(int s) { /* Make the parent of the nodes in the path from u--> parent[u] point to parent[u] */ if (s == parent[s]) return s; return parent[s] = find(parent[s]); } // Makes u as parent of v. void merge(int u, int v) { //update the greatest available //free slot to u parent[v] = u; }} class Job implements Comparator<Job>{ // Each job has a unique-id, profit and deadline char id; int deadline, profit; // Constructors public Job() { } public Job(char id,int deadline,int profit) { this.id = id; this.deadline = deadline; this.profit = profit; } // Returns the maximum deadline from the set of jobs public static int findMaxDeadline(ArrayList<Job> arr) { int ans = Integer.MIN_VALUE; for (Job temp : arr) ans = Math.max(temp.deadline, ans); return ans; } // Prints optimal job sequence public static void printJobScheduling(ArrayList<Job> arr) { // Sort Jobs in descending order on the basis // of their profit Collections.sort(arr, new Job()); // Find the maximum deadline among all jobs and // create a disjoint set data structure with // maxDeadline disjoint sets initially. int maxDeadline = findMaxDeadline(arr); DisjointSet dsu = new DisjointSet(maxDeadline); // Traverse through all the jobs for (Job temp : arr) { // Find the maximum available free slot for // this job (corresponding to its deadline) int availableSlot = dsu.find(temp.deadline); // If maximum available free slot is greater // than 0, then free slot available if (availableSlot > 0) { // This slot is taken by this job 'i' // so we need to update the greatest free // slot. Note that, in merge, we make // first parameter as parent of second // parameter. So future queries for // availableSlot will return maximum slot // from set of "availableSlot - 1" dsu.merge(dsu.find(availableSlot - 1), availableSlot); System.out.print(temp.id + " "); } } System.out.println(); } // Used to sort in descending order on the basis // of profit for each job public int compare(Job j1, Job j2) { return j1.profit > j2.profit? -1: 1; }} // Driver codeclass Main{ public static void main(String args[]) { ArrayList<Job> arr=new ArrayList<Job>(); arr.add(new Job('a',2,100)); arr.add(new Job('b',1,19)); arr.add(new Job('c',2,27)); arr.add(new Job('d',1,25)); arr.add(new Job('e',3,15)); System.out.println("Following jobs need to be "+ "executed for maximum profit"); Job.printJobScheduling(arr); }}
# Python3 program to find the maximum profit# job sequence from a given array of jobs# with deadlines and profitsimport sys class DisjointSet: def __init__(self, n): self.parent = [i for i in range(n + 1)] def find(self, s): # Make the parent of nodes in the path from # u --> parent[u] point to parent[u] if s == self.parent[s]: return s self.parent[s] = self.find(self.parent[s]) return self.parent[s] # Make us as parent of v def merge(self, u, v): # Update the greatest available # free slot to u self.parent[v] = u def cmp(a): return a['profit'] def findmaxdeadline(arr, n): """ :param arr: Job array :param n: length of array :return: maximum deadline from the set of jobs """ ans = - sys.maxsize - 1 for i in range(n): ans = max(ans, arr[i]['deadline']) return ans def printjobscheduling(arr, n): # Sort jobs in descending order on # basis of their profit arr = sorted(arr, key = cmp, reverse = True) """ Find the maximum deadline among all jobs and create a disjoint set data structure with max_deadline disjoint sets initially """ max_deadline = findmaxdeadline(arr, n) ds = DisjointSet(max_deadline) for i in range(n): # find maximum available free slot for # this job (corresponding to its deadline) available_slot = ds.find(arr[i]['deadline']) if available_slot > 0: # This slot is taken by this job 'i' # so we need to update the greatest free slot. # Note: In merge, we make first parameter # as parent of second parameter. # So future queries for available_slot will # return maximum available slot in set of # "available_slot - 1" ds.merge(ds.find(available_slot - 1), available_slot) print(arr[i]['id'], end = " ") # Driver Codeif __name__ == "__main__": arr = [{'id': 'a', 'deadline': 2, 'profit': 100}, {'id': 'b', 'deadline': 1, 'profit': 19}, {'id': 'c', 'deadline': 2, 'profit': 27}, {'id': 'd', 'deadline': 1, 'profit': 25}, {'id': 'e', 'deadline': 3, 'profit': 15}] n = len(arr) print("Following jobs need to be", "executed for maximum profit") printjobscheduling(arr, n) # This code is contributed by Rajat Srivastava
Following jobs need to be executed for maximum profit
a c e
This article is contributed by Chirag Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
rajatsri94
sadhu2gourish
anubhavjangra123
Accolite
union-find
Greedy
Accolite
Greedy
union-find
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Huffman Coding | Greedy Algo-3
Coin Change | DP-7
Fractional Knapsack Problem
Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)
Difference between Prim's and Kruskal's algorithm for MST
Program for Least Recently Used (LRU) Page Replacement algorithm
Shortest Remaining Time First (Preemptive SJF) Scheduling Algorithm
Minimum Number of Platforms Required for a Railway/Bus Station
Graph Coloring | Set 2 (Greedy Algorithm)
Program for Page Replacement Algorithms | Set 2 (FIFO)
|
[
{
"code": null,
"e": 26379,
"s": 26351,
"text": "\n25 Jan, 2021"
},
{
"code": null,
"e": 26676,
"s": 26379,
"text": "Given a set of n jobs where each job i has a deadline di >=1 and profit pi>=0. Only one job can be scheduled at a time. Each job takes 1 unit of time to complete. We earn the profit if and only if the job is completed by its deadline. The task is to find the subset of jobs that maximizes profit."
},
{
"code": null,
"e": 26687,
"s": 26676,
"text": "Examples: "
},
{
"code": null,
"e": 27156,
"s": 26687,
"text": "Input: Four Jobs with following deadlines and profits\nJobID Deadline Profit\n a 4 20\n b 1 10\n c 1 40\n d 1 30\nOutput: Following is maximum profit sequence of jobs:\n c, a\n\nInput: Five Jobs with following deadlines and profits\nJobID Deadline Profit\n a 2 100\n b 1 19\n c 2 27\n d 1 25\n e 3 15\nOutput: Following is maximum profit sequence of jobs:\n c, a, e"
},
{
"code": null,
"e": 27264,
"s": 27156,
"text": "A greedy solution of time complexity O(n2) is already discussed here. Below is the simple Greedy Algorithm."
},
{
"code": null,
"e": 27551,
"s": 27264,
"text": "Sort all jobs in decreasing order of profit.Initialize the result sequence as first job in sorted jobs.Do following for remaining n-1 jobs If the current job can fit in the current result sequence without missing the deadline, add current job to the result. Else ignore the current job."
},
{
"code": null,
"e": 27596,
"s": 27551,
"text": "Sort all jobs in decreasing order of profit."
},
{
"code": null,
"e": 27656,
"s": 27596,
"text": "Initialize the result sequence as first job in sorted jobs."
},
{
"code": null,
"e": 27840,
"s": 27656,
"text": "Do following for remaining n-1 jobs If the current job can fit in the current result sequence without missing the deadline, add current job to the result. Else ignore the current job."
},
{
"code": null,
"e": 27988,
"s": 27840,
"text": "If the current job can fit in the current result sequence without missing the deadline, add current job to the result. Else ignore the current job."
},
{
"code": null,
"e": 28737,
"s": 27988,
"text": "The costly operation in the Greedy solution is to assign a free slot for a job. We were traversing each and every slot for a job and assigning the greatest possible time slot(<deadline) which was available.What does greatest time slot means? Suppose that a job J1 has a deadline of time t = 5. We assign the greatest time slot which is free and less than the deadline i.e 4-5 for this job. Now another job J2 with deadline of 5 comes in, so the time slot allotted will be 3-4 since 4-5 has already been allotted to job J1.Why to assign greatest time slot(free) to a job? Now we assign the greatest possible time slot since if we assign a time slot even lesser than the available one than there might be some other job which will miss its deadline. "
},
{
"code": null,
"e": 29690,
"s": 28737,
"text": "Example: J1 with deadline d1 = 5, profit 40 J2 with deadline d2 = 1, profit 20 Suppose that for job J1 we assigned time slot of 0-1. Now job J2 cannot be performed since we will perform Job J1 during that time slot.Using Disjoint Set for Job Sequencing All time slots are individual sets initially. We first find the maximum deadline of all jobs. Let the max deadline be m. We create m+1 individual sets. If a job is assigned a time slot of t where t >= 0, then the job is scheduled during [t-1, t]. So a set with value X represents the time slot [X-1, X]. We need to keep track of the greatest time slot available which can be allotted to a given job having deadline. We use the parent array of Disjoint Set Data structures for this purpose. The root of the tree is always the latest available slot. If for a deadline d, there is no slot available, then root would be 0. Below are detailed steps.Initialize Disjoint Set: Creates initial disjoint sets."
},
{
"code": null,
"e": 29833,
"s": 29690,
"text": "// m is maximum deadline of a job\nparent = new int[m + 1];\n\n// Every node is a parent of itself\nfor (int i = 0; i ≤ m; i++)\n parent[i] = i;"
},
{
"code": null,
"e": 29879,
"s": 29833,
"text": "Find : Finds the latest time slot available. "
},
{
"code": null,
"e": 30078,
"s": 29879,
"text": "// Returns the maximum available time slot\nfind(s)\n{\n // Base case\n if (s == parent[s])\n return s;\n\n // Recursive call with path compression\n return parent[s] = find(parent[s]);\n} "
},
{
"code": null,
"e": 30087,
"s": 30078,
"text": "Union : "
},
{
"code": null,
"e": 30226,
"s": 30087,
"text": " Merges two sets. \n// Makes u as parent of v.\nunion(u, v)\n{\n // update the greatest available\n // free slot to u\n parent[v] = u;\n} "
},
{
"code": null,
"e": 30647,
"s": 30226,
"text": "How come find returns the latest available time slot? Initially all time slots are individual slots. So the time slot returned is always maximum. When we assign a time slot ‘t’ to a job, we do union of ‘t’ with ‘t-1’ in a way that ‘t-1’ becomes parent of ‘t’. To do this we call union(t-1, t). This means that all future queries for time slot t would now return the latest time slot available for set represented by t-1."
},
{
"code": null,
"e": 30720,
"s": 30647,
"text": "Implementation : The following is the implementation of above algorithm."
},
{
"code": null,
"e": 30724,
"s": 30720,
"text": "C++"
},
{
"code": null,
"e": 30729,
"s": 30724,
"text": "Java"
},
{
"code": null,
"e": 30737,
"s": 30729,
"text": "Python3"
},
{
"code": "// C++ Program to find the maximum profit job sequence// from a given array of jobs with deadlines and profits#include<bits/stdc++.h>using namespace std; // A structure to represent various attributes of a Jobstruct Job{ // Each job has id, deadline and profit char id; int deadLine, profit;}; // A Simple Disjoint Set Data Structurestruct DisjointSet{ int *parent; // Constructor DisjointSet(int n) { parent = new int[n+1]; // Every node is a parent of itself for (int i = 0; i <= n; i++) parent[i] = i; } // Path Compression int find(int s) { /* Make the parent of the nodes in the path from u--> parent[u] point to parent[u] */ if (s == parent[s]) return s; return parent[s] = find(parent[s]); } // Makes u as parent of v. void merge(int u, int v) { //update the greatest available //free slot to u parent[v] = u; }}; // Used to sort in descending order on the basis// of profit for each jobbool cmp(Job a, Job b){ return (a.profit > b.profit);} // Functions returns the maximum deadline from the set// of jobsint findMaxDeadline(struct Job arr[], int n){ int ans = INT_MIN; for (int i = 0; i < n; i++) ans = max(ans, arr[i].deadLine); return ans;} int printJobScheduling(Job arr[], int n){ // Sort Jobs in descending order on the basis // of their profit sort(arr, arr + n, cmp); // Find the maximum deadline among all jobs and // create a disjoint set data structure with // maxDeadline disjoint sets initially. int maxDeadline = findMaxDeadline(arr, n); DisjointSet ds(maxDeadline); // Traverse through all the jobs for (int i = 0; i < n; i++) { // Find the maximum available free slot for // this job (corresponding to its deadline) int availableSlot = ds.find(arr[i].deadLine); // If maximum available free slot is greater // than 0, then free slot available if (availableSlot > 0) { // This slot is taken by this job 'i' // so we need to update the greatest // free slot. Note that, in merge, we // make first parameter as parent of // second parameter. So future queries // for availableSlot will return maximum // available slot in set of // \"availableSlot - 1\" ds.merge(ds.find(availableSlot - 1), availableSlot); cout << arr[i].id << \" \"; } }} // Driver codeint main(){ Job arr[] = { { 'a', 2, 100 }, { 'b', 1, 19 }, { 'c', 2, 27 }, { 'd', 1, 25 }, { 'e', 3, 15 } }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Following jobs need to be \" << \"executed for maximum profit\\n\"; printJobScheduling(arr, n); return 0;}",
"e": 33628,
"s": 30737,
"text": null
},
{
"code": "// Java program to find the maximum profit job sequence// from a given array of jobs with deadlines and profitsimport java.util.*; // A Simple Disjoint Set Data Structureclass DisjointSet{ int parent[]; // Constructor DisjointSet(int n) { parent = new int[n + 1]; // Every node is a parent of itself for (int i = 0; i <= n; i++) parent[i] = i; } // Path Compression int find(int s) { /* Make the parent of the nodes in the path from u--> parent[u] point to parent[u] */ if (s == parent[s]) return s; return parent[s] = find(parent[s]); } // Makes u as parent of v. void merge(int u, int v) { //update the greatest available //free slot to u parent[v] = u; }} class Job implements Comparator<Job>{ // Each job has a unique-id, profit and deadline char id; int deadline, profit; // Constructors public Job() { } public Job(char id,int deadline,int profit) { this.id = id; this.deadline = deadline; this.profit = profit; } // Returns the maximum deadline from the set of jobs public static int findMaxDeadline(ArrayList<Job> arr) { int ans = Integer.MIN_VALUE; for (Job temp : arr) ans = Math.max(temp.deadline, ans); return ans; } // Prints optimal job sequence public static void printJobScheduling(ArrayList<Job> arr) { // Sort Jobs in descending order on the basis // of their profit Collections.sort(arr, new Job()); // Find the maximum deadline among all jobs and // create a disjoint set data structure with // maxDeadline disjoint sets initially. int maxDeadline = findMaxDeadline(arr); DisjointSet dsu = new DisjointSet(maxDeadline); // Traverse through all the jobs for (Job temp : arr) { // Find the maximum available free slot for // this job (corresponding to its deadline) int availableSlot = dsu.find(temp.deadline); // If maximum available free slot is greater // than 0, then free slot available if (availableSlot > 0) { // This slot is taken by this job 'i' // so we need to update the greatest free // slot. Note that, in merge, we make // first parameter as parent of second // parameter. So future queries for // availableSlot will return maximum slot // from set of \"availableSlot - 1\" dsu.merge(dsu.find(availableSlot - 1), availableSlot); System.out.print(temp.id + \" \"); } } System.out.println(); } // Used to sort in descending order on the basis // of profit for each job public int compare(Job j1, Job j2) { return j1.profit > j2.profit? -1: 1; }} // Driver codeclass Main{ public static void main(String args[]) { ArrayList<Job> arr=new ArrayList<Job>(); arr.add(new Job('a',2,100)); arr.add(new Job('b',1,19)); arr.add(new Job('c',2,27)); arr.add(new Job('d',1,25)); arr.add(new Job('e',3,15)); System.out.println(\"Following jobs need to be \"+ \"executed for maximum profit\"); Job.printJobScheduling(arr); }}",
"e": 37072,
"s": 33628,
"text": null
},
{
"code": "# Python3 program to find the maximum profit# job sequence from a given array of jobs# with deadlines and profitsimport sys class DisjointSet: def __init__(self, n): self.parent = [i for i in range(n + 1)] def find(self, s): # Make the parent of nodes in the path from # u --> parent[u] point to parent[u] if s == self.parent[s]: return s self.parent[s] = self.find(self.parent[s]) return self.parent[s] # Make us as parent of v def merge(self, u, v): # Update the greatest available # free slot to u self.parent[v] = u def cmp(a): return a['profit'] def findmaxdeadline(arr, n): \"\"\" :param arr: Job array :param n: length of array :return: maximum deadline from the set of jobs \"\"\" ans = - sys.maxsize - 1 for i in range(n): ans = max(ans, arr[i]['deadline']) return ans def printjobscheduling(arr, n): # Sort jobs in descending order on # basis of their profit arr = sorted(arr, key = cmp, reverse = True) \"\"\" Find the maximum deadline among all jobs and create a disjoint set data structure with max_deadline disjoint sets initially \"\"\" max_deadline = findmaxdeadline(arr, n) ds = DisjointSet(max_deadline) for i in range(n): # find maximum available free slot for # this job (corresponding to its deadline) available_slot = ds.find(arr[i]['deadline']) if available_slot > 0: # This slot is taken by this job 'i' # so we need to update the greatest free slot. # Note: In merge, we make first parameter # as parent of second parameter. # So future queries for available_slot will # return maximum available slot in set of # \"available_slot - 1\" ds.merge(ds.find(available_slot - 1), available_slot) print(arr[i]['id'], end = \" \") # Driver Codeif __name__ == \"__main__\": arr = [{'id': 'a', 'deadline': 2, 'profit': 100}, {'id': 'b', 'deadline': 1, 'profit': 19}, {'id': 'c', 'deadline': 2, 'profit': 27}, {'id': 'd', 'deadline': 1, 'profit': 25}, {'id': 'e', 'deadline': 3, 'profit': 15}] n = len(arr) print(\"Following jobs need to be\", \"executed for maximum profit\") printjobscheduling(arr, n) # This code is contributed by Rajat Srivastava",
"e": 39509,
"s": 37072,
"text": null
},
{
"code": null,
"e": 39570,
"s": 39509,
"text": "Following jobs need to be executed for maximum profit\na c e "
},
{
"code": null,
"e": 39963,
"s": 39570,
"text": "This article is contributed by Chirag Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 39974,
"s": 39963,
"text": "rajatsri94"
},
{
"code": null,
"e": 39988,
"s": 39974,
"text": "sadhu2gourish"
},
{
"code": null,
"e": 40005,
"s": 39988,
"text": "anubhavjangra123"
},
{
"code": null,
"e": 40014,
"s": 40005,
"text": "Accolite"
},
{
"code": null,
"e": 40025,
"s": 40014,
"text": "union-find"
},
{
"code": null,
"e": 40032,
"s": 40025,
"text": "Greedy"
},
{
"code": null,
"e": 40041,
"s": 40032,
"text": "Accolite"
},
{
"code": null,
"e": 40048,
"s": 40041,
"text": "Greedy"
},
{
"code": null,
"e": 40059,
"s": 40048,
"text": "union-find"
},
{
"code": null,
"e": 40157,
"s": 40059,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40188,
"s": 40157,
"text": "Huffman Coding | Greedy Algo-3"
},
{
"code": null,
"e": 40207,
"s": 40188,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 40235,
"s": 40207,
"text": "Fractional Knapsack Problem"
},
{
"code": null,
"e": 40316,
"s": 40235,
"text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)"
},
{
"code": null,
"e": 40374,
"s": 40316,
"text": "Difference between Prim's and Kruskal's algorithm for MST"
},
{
"code": null,
"e": 40439,
"s": 40374,
"text": "Program for Least Recently Used (LRU) Page Replacement algorithm"
},
{
"code": null,
"e": 40507,
"s": 40439,
"text": "Shortest Remaining Time First (Preemptive SJF) Scheduling Algorithm"
},
{
"code": null,
"e": 40570,
"s": 40507,
"text": "Minimum Number of Platforms Required for a Railway/Bus Station"
},
{
"code": null,
"e": 40612,
"s": 40570,
"text": "Graph Coloring | Set 2 (Greedy Algorithm)"
}
] |
jQWidgets jqxGrid cellbeginedit Event - GeeksforGeeks
|
03 Nov, 2021
jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful, optimized, platform-independent, and widely supported framework. The jqxGrid is used to illustrate a jQuery widget that shows data in tabular form. Moreover, it renders full support for connecting with data, as well as paging, grouping, sorting, filtering, and editing.
The cellbeginedit event is activated whenever the editor of a cell of a displayed jqxGrid is shown.
Syntax:
$("#Selector").on('cellbeginedit', function (event) {
// Arguments of the event
var args = event.args;
// Data field of the column
var dataField = event.args.datafield;
// Bound index of the row
var rowBoundIndex = event.args.rowindex;
// Value of the cell
var value = args.value;
// Data of the row
var rowData = args.row;
});
Linked Files: Download jQWidgets from the given link. In the HTML file, locate the script files in the downloaded folder.
<link rel=”stylesheet” href=”jqwidgets/styles/jqx.base.css” type=”text/css” /><script type=”text/javascript” src=”scripts/jquery-1.11.1.min.js”></script><script type=”text/javascript” src=”jqwidgets/jqxcore.js”></script><script type=”text/javascript” src=”jqwidgets/jqx-all.js”></script><script type=”text/javascript” src=”jqwidgets/jqxdata.js”></script><script type=”text/javascript” src=”jqwidgets/jqxbuttons.js”></script><script type=”text/javascript” src=”jqwidgets/jqxscrollbar.js”></script><script type=”text/javascript” src=”jqwidgets/jqxmenu.js”></script><script type=”text/javascript” src=”jqwidgets/jqxgrid.js”></script><script type=”text/javascript” src=”jqwidgets/jqxgrid.selection.js”></script>
Example: The below example illustrates the jqxGrid cellbeginedit event in jQWidgets.
HTML
<!DOCTYPE html><html lang="en"> <head> <link rel="stylesheet" href= "jqwidgets/styles/jqx.base.css" type="text/css" /> <script type="text/javascript" src="scripts/jquery-1.11.1.min.js"></script> <script type="text/javascript" src="jqwidgets/jqxcore.js"></script> <script type="text/javascript" src="jqwidgets/jqx-all.js"></script> <script type="text/javascript" src="jqwidgets/jqxdata.js"></script> <script type="text/javascript" src="jqwidgets/jqxbuttons.js"></script> <script type="text/javascript" src="jqwidgets/jqxscrollbar.js"></script> <script type="text/javascript" src="jqwidgets/jqxmenu.js"></script> <script type="text/javascript" src="jqwidgets/jqxgrid.js"></script> <script type="text/javascript" src="jqwidgets/jqxgrid.selection.js"></script></head> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <h3>jQWidgets jqxGrid cellbeginedit Event </h3> <br/> <div id="jqxg"></div> <br/> <div id="log"></div> </center> <script type="text/javascript"> $(document).ready(function () { var d = new Array(); var subjectNames = ["C++", "Scala", "Java", "C", "R", "JavaScript"]; var pageNumber = ["7", "8", "12", "11", "10", "19"]; for (var j = 0; j < 50; j++) { var r = {}; r["subjectnames"] = subjectNames[Math.floor( Math.random() * subjectNames.length) ]; r["pagenumber"] = pageNumber[Math.floor( Math.random() * pageNumber.length) ]; d[j] = r; } var src = { localdata: d, datatype: "array", }; var data_Adapter = new $.jqx.dataAdapter(src); $("#jqxg").jqxGrid({ source: data_Adapter, editable: true, selectionmode: 'singlecell', theme: 'energyblue', height: "260px", width: "240px", columns: [ { text: "Subject Name", datafield: "subjectnames", width: "120px", }, { text: "Page No.", datafield: "pagenumber", width: "120px", }, ], }); $("#jqxg").on("cellbeginedit", function (event) { $('#log').html( "Index of row to be eidted: " + event.args.rowindex ); }); }); </script></body> </html>
Output:
Reference: https://www.jqwidgets.com/jquery-widgets-documentation/documentation/jqxgrid/jquery-grid-api.htm?search=
jQuery-jQWidgets
jQWidgets-jqxGrid
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to change the background color after clicking the button in JavaScript ?
How to fetch data from JSON file and display in HTML table using jQuery ?
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": 89964,
"s": 89936,
"text": "\n03 Nov, 2021"
},
{
"code": null,
"e": 90354,
"s": 89964,
"text": "jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful, optimized, platform-independent, and widely supported framework. The jqxGrid is used to illustrate a jQuery widget that shows data in tabular form. Moreover, it renders full support for connecting with data, as well as paging, grouping, sorting, filtering, and editing."
},
{
"code": null,
"e": 90454,
"s": 90354,
"text": "The cellbeginedit event is activated whenever the editor of a cell of a displayed jqxGrid is shown."
},
{
"code": null,
"e": 90462,
"s": 90454,
"text": "Syntax:"
},
{
"code": null,
"e": 90833,
"s": 90462,
"text": "$(\"#Selector\").on('cellbeginedit', function (event) {\n // Arguments of the event\n var args = event.args;\n \n // Data field of the column\n var dataField = event.args.datafield;\n \n // Bound index of the row\n var rowBoundIndex = event.args.rowindex;\n \n // Value of the cell\n var value = args.value;\n \n // Data of the row\n var rowData = args.row;\n});"
},
{
"code": null,
"e": 90955,
"s": 90833,
"text": "Linked Files: Download jQWidgets from the given link. In the HTML file, locate the script files in the downloaded folder."
},
{
"code": null,
"e": 91663,
"s": 90955,
"text": "<link rel=”stylesheet” href=”jqwidgets/styles/jqx.base.css” type=”text/css” /><script type=”text/javascript” src=”scripts/jquery-1.11.1.min.js”></script><script type=”text/javascript” src=”jqwidgets/jqxcore.js”></script><script type=”text/javascript” src=”jqwidgets/jqx-all.js”></script><script type=”text/javascript” src=”jqwidgets/jqxdata.js”></script><script type=”text/javascript” src=”jqwidgets/jqxbuttons.js”></script><script type=”text/javascript” src=”jqwidgets/jqxscrollbar.js”></script><script type=”text/javascript” src=”jqwidgets/jqxmenu.js”></script><script type=”text/javascript” src=”jqwidgets/jqxgrid.js”></script><script type=”text/javascript” src=”jqwidgets/jqxgrid.selection.js”></script>"
},
{
"code": null,
"e": 91748,
"s": 91663,
"text": "Example: The below example illustrates the jqxGrid cellbeginedit event in jQWidgets."
},
{
"code": null,
"e": 91753,
"s": 91748,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <link rel=\"stylesheet\" href= \"jqwidgets/styles/jqx.base.css\" type=\"text/css\" /> <script type=\"text/javascript\" src=\"scripts/jquery-1.11.1.min.js\"></script> <script type=\"text/javascript\" src=\"jqwidgets/jqxcore.js\"></script> <script type=\"text/javascript\" src=\"jqwidgets/jqx-all.js\"></script> <script type=\"text/javascript\" src=\"jqwidgets/jqxdata.js\"></script> <script type=\"text/javascript\" src=\"jqwidgets/jqxbuttons.js\"></script> <script type=\"text/javascript\" src=\"jqwidgets/jqxscrollbar.js\"></script> <script type=\"text/javascript\" src=\"jqwidgets/jqxmenu.js\"></script> <script type=\"text/javascript\" src=\"jqwidgets/jqxgrid.js\"></script> <script type=\"text/javascript\" src=\"jqwidgets/jqxgrid.selection.js\"></script></head> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <h3>jQWidgets jqxGrid cellbeginedit Event </h3> <br/> <div id=\"jqxg\"></div> <br/> <div id=\"log\"></div> </center> <script type=\"text/javascript\"> $(document).ready(function () { var d = new Array(); var subjectNames = [\"C++\", \"Scala\", \"Java\", \"C\", \"R\", \"JavaScript\"]; var pageNumber = [\"7\", \"8\", \"12\", \"11\", \"10\", \"19\"]; for (var j = 0; j < 50; j++) { var r = {}; r[\"subjectnames\"] = subjectNames[Math.floor( Math.random() * subjectNames.length) ]; r[\"pagenumber\"] = pageNumber[Math.floor( Math.random() * pageNumber.length) ]; d[j] = r; } var src = { localdata: d, datatype: \"array\", }; var data_Adapter = new $.jqx.dataAdapter(src); $(\"#jqxg\").jqxGrid({ source: data_Adapter, editable: true, selectionmode: 'singlecell', theme: 'energyblue', height: \"260px\", width: \"240px\", columns: [ { text: \"Subject Name\", datafield: \"subjectnames\", width: \"120px\", }, { text: \"Page No.\", datafield: \"pagenumber\", width: \"120px\", }, ], }); $(\"#jqxg\").on(\"cellbeginedit\", function (event) { $('#log').html( \"Index of row to be eidted: \" + event.args.rowindex ); }); }); </script></body> </html>",
"e": 94679,
"s": 91753,
"text": null
},
{
"code": null,
"e": 94687,
"s": 94679,
"text": "Output:"
},
{
"code": null,
"e": 94803,
"s": 94687,
"text": "Reference: https://www.jqwidgets.com/jquery-widgets-documentation/documentation/jqxgrid/jquery-grid-api.htm?search="
},
{
"code": null,
"e": 94820,
"s": 94803,
"text": "jQuery-jQWidgets"
},
{
"code": null,
"e": 94838,
"s": 94820,
"text": "jQWidgets-jqxGrid"
},
{
"code": null,
"e": 94845,
"s": 94838,
"text": "JQuery"
},
{
"code": null,
"e": 94862,
"s": 94845,
"text": "Web Technologies"
},
{
"code": null,
"e": 94960,
"s": 94862,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 95006,
"s": 94960,
"text": "JQuery | Set the value of an input text field"
},
{
"code": null,
"e": 95035,
"s": 95006,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 95098,
"s": 95035,
"text": "How to change selected value of a drop-down list using jQuery?"
},
{
"code": null,
"e": 95175,
"s": 95098,
"text": "How to change the background color after clicking the button in JavaScript ?"
},
{
"code": null,
"e": 95249,
"s": 95175,
"text": "How to fetch data from JSON file and display in HTML table using jQuery ?"
},
{
"code": null,
"e": 95289,
"s": 95249,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 95322,
"s": 95289,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 95367,
"s": 95322,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 95410,
"s": 95367,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Construct Pushdown Automata for all length palindrome - GeeksforGeeks
|
17 Apr, 2018
A Pushdown Automaton (PDA) is like an epsilon Non deterministic Finite Automata (NFA) with infinite stack. PDA is a way to implement context free languages. Hence, it is important to learn, how to draw PDA.
Here, take the example of odd length palindrome:Que-1: Construct a PDA for language L = {wcw’ | w={0, 1}*} where w’ is the reverse of w.
Approach used in this PDA –Keep on pushing 0’s and 1’s no matter whatever is on the top of stack until reach the middle element. When middle element ‘c’ is scanned then process it without making any changes in stack. Now if scanned symbol is ‘1’ and top of stack also contain ‘1’ then pop the element from top of stack or if scanned symbol is ‘0’ and top of stack also contain ‘0’ then pop the element from top of stack. If string becomes empty or scanned symbol is ‘$’ and stack becomes empty, then reach to final state else move to dead state.
Step 1: On receiving 0 or 1, keep on pushing it on top of stack without going to next state.
Step 2: On receiving an element ‘c’, move to next state without making any change in stack.
Step 3: On receiving an element, check if symbol scanned is ‘1’ and top of stack also contain ‘1’ or if symbol scanned is ‘0’ and top of stack also contain ‘0’ then pop the element from top of stack else move to dead state. Keep on repeating step 3 until string becomes empty.
Step 4: Check if symbol scanned is ‘$’ and stack does not contain any element then move to final state else move to dead state.
Examples:
Input : 1 0 1 0 1 0 1 0 1
Output :ACCEPTED
Input : 1 0 1 0 1 1 1 1 0
Output :NOT ACCEPTED
Now, take the example of even length palindrome:Que-2: Construct a PDA for language L = {ww’ | w={0, 1}*} where w’ is the reverse of w.
Approach used in this PDA –For construction of even length palindrome, user has to use Non Deterministic Pushdown Automata (NPDA). A NPDA is basically an NFA with a stack added to it.The NPDA for this language is identical to the previous one except for epsilon transition. However, there is a significant difference, that this PDA must guess when to stop pushing symbols, jump to the final state and start matching off of the stack. Therefore this machine is decidedly non-deterministic.Keep on pushing 0’s and 1’s no matter whatever is on the top of stack and at the same time keep a check on the input string, whether reach to the second half of input string or not. If reach to last element of first half of the input string then after processing the last element of first half of input string make an epsilon move and move to next state. Now if scanned symbol is ‘1’ and top of stack also contain ‘1’ then pop the element from top of stack or if scanned symbol is ‘0’ and top of stack also contain ‘0’ then pop the element from top of stack. If string becomes empty or scanned symbol is ‘$’ and stack becomes empty, then reach to final state else move to dead state.
Step 1: On receiving 0 or 1, keep on pushing it on top of stack and at a same time keep on checking whether reach to second half of input string or not.
Step 2: If reach to last element of first half of input string, then push that element on top of stack and then make an epsilon move to next state.
Step 3: On receiving an element, check if symbol scanned is ‘1’ and top of stack also contain ‘1’ or if symbol scanned is ‘0’ and top of stack also contain ‘0’ then pop the element from top of stack else move to dead state. Keep on repeating step 3 until string becomes empty.
Step 4: Check if symbol scanned is ‘$’ and stack does not contain any element then move to final state else move to dead state.
Examples:
Input : 1 0 0 1 1 1 1 0 0 1
Output :ACCEPTED
Input : 1 0 0 1 1 1
Output :NOT ACCEPTED
Now, take the example of all length palindrome, i.e. a PDA which can accept both odd length palindrome and even length palindrome:Que-3: Construct a PDA for language L = {ww’ | wcw’, w={0, 1}*} where w’ is the reverse of w.
Approach used in this PDA –For construction of all length palindrome, user has to use NPDA.The approach is similar to above example, except now along with epsilon move now user has to show one more transition move of symbol ‘c’ i.e. if string is of odd length and if reach to middle element ‘c’ then just process it and move to next state without making any change in stack.
Step 1: On receiving 0 or 1, keep on pushing it on top of stack and at a same time keep on checking, if input string is of even length then whether reach to second half of input string or not, however if the input string is of odd length then keep on checking whether reach to middle element or not.
Step 2: If input string is of even length and reach to last element of first half of input string, then push that element on top of stack and then make an epsilon move to next state or if the input string is of odd length then on receiving an element ‘c’, move to next state without making any change in stack.
Step 3: On receiving an element, check if symbol scanned is ‘1’ and top of stack also contain ‘1’ or if symbol scanned is ‘0’ and top of stack also contain ‘0’ then pop the element from top of stack else move to dead state. Keep on repeating step 3 until string becomes empty.
Step 4: Check if symbol scanned is ‘$’ and stack does not contain any element then move to final state else move to dead state.
Examples:
Input : 1 1 0 0 1 1 1 1 0 0 1 1
Output :ACCEPTED
Input : 1 0 1 0 1 0 1
Output :ACCEPTED
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Normal Forms in DBMS
Difference between DFA and NFA
Regular expression to ∈-NFA
NPDA for accepting the language L = {wwR | w ∈ (a,b)*}
Closure properties of Regular languages
Design 101 sequence detector (Mealy machine)
|
[
{
"code": null,
"e": 31081,
"s": 31053,
"text": "\n17 Apr, 2018"
},
{
"code": null,
"e": 31288,
"s": 31081,
"text": "A Pushdown Automaton (PDA) is like an epsilon Non deterministic Finite Automata (NFA) with infinite stack. PDA is a way to implement context free languages. Hence, it is important to learn, how to draw PDA."
},
{
"code": null,
"e": 31425,
"s": 31288,
"text": "Here, take the example of odd length palindrome:Que-1: Construct a PDA for language L = {wcw’ | w={0, 1}*} where w’ is the reverse of w."
},
{
"code": null,
"e": 31971,
"s": 31425,
"text": "Approach used in this PDA –Keep on pushing 0’s and 1’s no matter whatever is on the top of stack until reach the middle element. When middle element ‘c’ is scanned then process it without making any changes in stack. Now if scanned symbol is ‘1’ and top of stack also contain ‘1’ then pop the element from top of stack or if scanned symbol is ‘0’ and top of stack also contain ‘0’ then pop the element from top of stack. If string becomes empty or scanned symbol is ‘$’ and stack becomes empty, then reach to final state else move to dead state."
},
{
"code": null,
"e": 32064,
"s": 31971,
"text": "Step 1: On receiving 0 or 1, keep on pushing it on top of stack without going to next state."
},
{
"code": null,
"e": 32156,
"s": 32064,
"text": "Step 2: On receiving an element ‘c’, move to next state without making any change in stack."
},
{
"code": null,
"e": 32433,
"s": 32156,
"text": "Step 3: On receiving an element, check if symbol scanned is ‘1’ and top of stack also contain ‘1’ or if symbol scanned is ‘0’ and top of stack also contain ‘0’ then pop the element from top of stack else move to dead state. Keep on repeating step 3 until string becomes empty."
},
{
"code": null,
"e": 32561,
"s": 32433,
"text": "Step 4: Check if symbol scanned is ‘$’ and stack does not contain any element then move to final state else move to dead state."
},
{
"code": null,
"e": 32571,
"s": 32561,
"text": "Examples:"
},
{
"code": null,
"e": 32663,
"s": 32571,
"text": "Input : 1 0 1 0 1 0 1 0 1\nOutput :ACCEPTED\n\nInput : 1 0 1 0 1 1 1 1 0\nOutput :NOT ACCEPTED\n"
},
{
"code": null,
"e": 32799,
"s": 32663,
"text": "Now, take the example of even length palindrome:Que-2: Construct a PDA for language L = {ww’ | w={0, 1}*} where w’ is the reverse of w."
},
{
"code": null,
"e": 33971,
"s": 32799,
"text": "Approach used in this PDA –For construction of even length palindrome, user has to use Non Deterministic Pushdown Automata (NPDA). A NPDA is basically an NFA with a stack added to it.The NPDA for this language is identical to the previous one except for epsilon transition. However, there is a significant difference, that this PDA must guess when to stop pushing symbols, jump to the final state and start matching off of the stack. Therefore this machine is decidedly non-deterministic.Keep on pushing 0’s and 1’s no matter whatever is on the top of stack and at the same time keep a check on the input string, whether reach to the second half of input string or not. If reach to last element of first half of the input string then after processing the last element of first half of input string make an epsilon move and move to next state. Now if scanned symbol is ‘1’ and top of stack also contain ‘1’ then pop the element from top of stack or if scanned symbol is ‘0’ and top of stack also contain ‘0’ then pop the element from top of stack. If string becomes empty or scanned symbol is ‘$’ and stack becomes empty, then reach to final state else move to dead state."
},
{
"code": null,
"e": 34124,
"s": 33971,
"text": "Step 1: On receiving 0 or 1, keep on pushing it on top of stack and at a same time keep on checking whether reach to second half of input string or not."
},
{
"code": null,
"e": 34272,
"s": 34124,
"text": "Step 2: If reach to last element of first half of input string, then push that element on top of stack and then make an epsilon move to next state."
},
{
"code": null,
"e": 34549,
"s": 34272,
"text": "Step 3: On receiving an element, check if symbol scanned is ‘1’ and top of stack also contain ‘1’ or if symbol scanned is ‘0’ and top of stack also contain ‘0’ then pop the element from top of stack else move to dead state. Keep on repeating step 3 until string becomes empty."
},
{
"code": null,
"e": 34677,
"s": 34549,
"text": "Step 4: Check if symbol scanned is ‘$’ and stack does not contain any element then move to final state else move to dead state."
},
{
"code": null,
"e": 34687,
"s": 34677,
"text": "Examples:"
},
{
"code": null,
"e": 34775,
"s": 34687,
"text": "Input : 1 0 0 1 1 1 1 0 0 1\nOutput :ACCEPTED\n\nInput : 1 0 0 1 1 1\nOutput :NOT ACCEPTED\n"
},
{
"code": null,
"e": 34999,
"s": 34775,
"text": "Now, take the example of all length palindrome, i.e. a PDA which can accept both odd length palindrome and even length palindrome:Que-3: Construct a PDA for language L = {ww’ | wcw’, w={0, 1}*} where w’ is the reverse of w."
},
{
"code": null,
"e": 35374,
"s": 34999,
"text": "Approach used in this PDA –For construction of all length palindrome, user has to use NPDA.The approach is similar to above example, except now along with epsilon move now user has to show one more transition move of symbol ‘c’ i.e. if string is of odd length and if reach to middle element ‘c’ then just process it and move to next state without making any change in stack."
},
{
"code": null,
"e": 35674,
"s": 35374,
"text": "Step 1: On receiving 0 or 1, keep on pushing it on top of stack and at a same time keep on checking, if input string is of even length then whether reach to second half of input string or not, however if the input string is of odd length then keep on checking whether reach to middle element or not."
},
{
"code": null,
"e": 35985,
"s": 35674,
"text": "Step 2: If input string is of even length and reach to last element of first half of input string, then push that element on top of stack and then make an epsilon move to next state or if the input string is of odd length then on receiving an element ‘c’, move to next state without making any change in stack."
},
{
"code": null,
"e": 36262,
"s": 35985,
"text": "Step 3: On receiving an element, check if symbol scanned is ‘1’ and top of stack also contain ‘1’ or if symbol scanned is ‘0’ and top of stack also contain ‘0’ then pop the element from top of stack else move to dead state. Keep on repeating step 3 until string becomes empty."
},
{
"code": null,
"e": 36390,
"s": 36262,
"text": "Step 4: Check if symbol scanned is ‘$’ and stack does not contain any element then move to final state else move to dead state."
},
{
"code": null,
"e": 36400,
"s": 36390,
"text": "Examples:"
},
{
"code": null,
"e": 36490,
"s": 36400,
"text": "Input : 1 1 0 0 1 1 1 1 0 0 1 1\nOutput :ACCEPTED\n\nInput : 1 0 1 0 1 0 1\nOutput :ACCEPTED\n"
},
{
"code": null,
"e": 36498,
"s": 36490,
"text": "GATE CS"
},
{
"code": null,
"e": 36531,
"s": 36498,
"text": "Theory of Computation & Automata"
},
{
"code": null,
"e": 36629,
"s": 36531,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36649,
"s": 36629,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 36673,
"s": 36649,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 36686,
"s": 36673,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 36713,
"s": 36686,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 36734,
"s": 36713,
"text": "Normal Forms in DBMS"
},
{
"code": null,
"e": 36765,
"s": 36734,
"text": "Difference between DFA and NFA"
},
{
"code": null,
"e": 36793,
"s": 36765,
"text": "Regular expression to ∈-NFA"
},
{
"code": null,
"e": 36848,
"s": 36793,
"text": "NPDA for accepting the language L = {wwR | w ∈ (a,b)*}"
},
{
"code": null,
"e": 36888,
"s": 36848,
"text": "Closure properties of Regular languages"
}
] |
Python | shutil.copy() method - GeeksforGeeks
|
20 Jun, 2021
Python3
# Python program to explain shutil.copy() method # importing shutil moduleimport shutil # Source pathsource = "/home/User/Documents/file.txt" # Destination pathdestination = "/home/User/Documents/file.txt" # Copy the content of# source to destination try: shutil.copy(source, destination) print("File copied successfully.") # If source and destination are sameexcept shutil.SameFileError: print("Source and destination represents the same file.") # If there is any permission issueexcept PermissionError: print("Permission denied.") # For other errorsexcept: print("Error occurred while copying file.")
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories.shutil.copy() method in Python is used to copy the content of source file to destination file or directory. It also preserves the file’s permission mode but other metadata of the file like the file’s creation and modification times is not preserved. Source must represent a file but destination can be a file or a directory. If the destination is a directory then the file will be copied into destination using the base filename from source. Also, destination must be writable. If destination is a file and already exists then it will be replaced with the source file otherwise a new file will be created.
Syntax: shutil.copy(source, destination, *, follow_symlinks = True)Parameter: source: A string representing the path of the source file. destination: A string representing the path of the destination file or directory. follow_symlinks (optional) : The default value of this parameter is True. If it is False and source represents a symbolic link then destination will be created as a symbolic link.Note: The ‘*’ in parameter list indicates that all following parameters (Here in our case ‘follow_symlinks’) are keyword-only parameters and they can be provided using their name, not as positional parameter.Return Type: This method returns a string which represents the path of newly created file.
Code #1: Use of shutil.copy() method to copy file from source to destination
Python3
# Python program to explain shutil.copy() method # importing os moduleimport os # importing shutil moduleimport shutil # pathpath = '/home/User/Documents' # List files and directories# in '/home/User/Documents'print("Before copying file:")print(os.listdir(path)) # Source pathsource = "/home/User/Documents/file.txt" # Print file permission# of the sourceperm = os.stat(source).st_modeprint("File Permission mode:", perm, "\n") # Destination pathdestination = "/home/User/Documents/file(copy).txt" # Copy the content of# source to destinationdest = shutil.copy(source, destination) # List files and directories# in "/home / User / Documents"print("After copying file:")print(os.listdir(path)) # Print file permission# of the destinationperm = os.stat(destination).st_modeprint("File Permission mode:", perm) # Print path of newly# created fileprint("Destination path:", dest)
Before copying file:
['hrithik.png', 'test.py', 'sample.txt', 'file.text', 'copy.cpp']
File permission mode: 33188
After copying file:
['hrithik.png', 'test.py', 'sample.txt', 'file.text', 'file(copy).txt', 'copy.cpp']
File permission mode: 33188
Destination path: /home/User/Documents/file(copy).txt
Code #2: If destination is a directory
Python3
# Python program to explain shutil.copy() method # importing os moduleimport os # importing shutil moduleimport shutil # Source pathsource = "/home/User/Documents/file.txt" # Destination pathdestination = "/home/User/Desktop/" # Copy the content of# source to destinationdest = shutil.copy(source, destination) # List files and directories# in "/home / User / Desktop"print("After copying file:")print(os.listdir(destination)) # Print path of newly# created fileprint("Destination path:", dest)
After copying file:
['input.txt', 'GeeksForGeeks', 'output.txt', 'file.txt', 'web.py', 'tree.cpp']
Destination path: /home/User/Desktop/file.txt
Code #3: Possible errors while using shutil.copy() method
Python3
# Python program to explain shutil.copy() method # importing shutil moduleimport shutil # If the source and destination# represents the same file# 'SameFileError' exception# will be raised # If the destination is# not writable# 'PermissionError' exception# will be raised # Source pathsource = "/home/User/Documents/file.txt" # Destination pathdestination = "/home/User/Documents/file.txt" # Copy the content of# source to destinationshutil.copy(source, destination)
Traceback (most recent call last):
File "try.py", line 26, in
dest = shutil.copy(source, destination)
File "/usr/lib/python3.6/shutil.py", line 241, in copy
copyfile(src, dst, follow_symlinks=follow_symlinks)
File "/usr/lib/python3.6/shutil.py", line 104, in copyfile
raise SameFileError("{!r} and {!r} are the same file".format(src, dst))
shutil.SameFileError: '/home/User/Desktop/file.txt' and '/home/User/Desktop/file.txt'
are the same file
Code #4: Handling errors while using shutil.copy() method
Python3
# Python program to explain shutil.copy() method # importing shutil moduleimport shutil # Source pathsource = "/home/User/Documents/file.txt" # Destination pathdestination = "/home/User/Documents/file.txt" # Copy the content of# source to destination try: shutil.copy(source, destination) print("File copied successfully.") # If source and destination are sameexcept shutil.SameFileError: print("Source and destination represents the same file.") # If there is any permission issueexcept PermissionError: print("Permission denied.") # For other errorsexcept: print("Error occurred while copying file.")
Source and destination represents the same file.
Reference: https://docs.python.org/3/library/shutil.html
surindertarika1234
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
sum() function in Python
How To Convert Python Dictionary To JSON?
isupper(), islower(), lower(), upper() in Python and their applications
|
[
{
"code": null,
"e": 25523,
"s": 25495,
"text": "\n20 Jun, 2021"
},
{
"code": null,
"e": 25531,
"s": 25523,
"text": "Python3"
},
{
"code": "# Python program to explain shutil.copy() method # importing shutil moduleimport shutil # Source pathsource = \"/home/User/Documents/file.txt\" # Destination pathdestination = \"/home/User/Documents/file.txt\" # Copy the content of# source to destination try: shutil.copy(source, destination) print(\"File copied successfully.\") # If source and destination are sameexcept shutil.SameFileError: print(\"Source and destination represents the same file.\") # If there is any permission issueexcept PermissionError: print(\"Permission denied.\") # For other errorsexcept: print(\"Error occurred while copying file.\")",
"e": 26151,
"s": 25531,
"text": null
},
{
"code": null,
"e": 27004,
"s": 26151,
"text": "Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories.shutil.copy() method in Python is used to copy the content of source file to destination file or directory. It also preserves the file’s permission mode but other metadata of the file like the file’s creation and modification times is not preserved. Source must represent a file but destination can be a file or a directory. If the destination is a directory then the file will be copied into destination using the base filename from source. Also, destination must be writable. If destination is a file and already exists then it will be replaced with the source file otherwise a new file will be created. "
},
{
"code": null,
"e": 27703,
"s": 27004,
"text": "Syntax: shutil.copy(source, destination, *, follow_symlinks = True)Parameter: source: A string representing the path of the source file. destination: A string representing the path of the destination file or directory. follow_symlinks (optional) : The default value of this parameter is True. If it is False and source represents a symbolic link then destination will be created as a symbolic link.Note: The ‘*’ in parameter list indicates that all following parameters (Here in our case ‘follow_symlinks’) are keyword-only parameters and they can be provided using their name, not as positional parameter.Return Type: This method returns a string which represents the path of newly created file. "
},
{
"code": null,
"e": 27782,
"s": 27703,
"text": "Code #1: Use of shutil.copy() method to copy file from source to destination "
},
{
"code": null,
"e": 27790,
"s": 27782,
"text": "Python3"
},
{
"code": "# Python program to explain shutil.copy() method # importing os moduleimport os # importing shutil moduleimport shutil # pathpath = '/home/User/Documents' # List files and directories# in '/home/User/Documents'print(\"Before copying file:\")print(os.listdir(path)) # Source pathsource = \"/home/User/Documents/file.txt\" # Print file permission# of the sourceperm = os.stat(source).st_modeprint(\"File Permission mode:\", perm, \"\\n\") # Destination pathdestination = \"/home/User/Documents/file(copy).txt\" # Copy the content of# source to destinationdest = shutil.copy(source, destination) # List files and directories# in \"/home / User / Documents\"print(\"After copying file:\")print(os.listdir(path)) # Print file permission# of the destinationperm = os.stat(destination).st_modeprint(\"File Permission mode:\", perm) # Print path of newly# created fileprint(\"Destination path:\", dest)",
"e": 28669,
"s": 27790,
"text": null
},
{
"code": null,
"e": 28972,
"s": 28669,
"text": "Before copying file:\n['hrithik.png', 'test.py', 'sample.txt', 'file.text', 'copy.cpp']\nFile permission mode: 33188\n\nAfter copying file:\n['hrithik.png', 'test.py', 'sample.txt', 'file.text', 'file(copy).txt', 'copy.cpp']\nFile permission mode: 33188 \nDestination path: /home/User/Documents/file(copy).txt"
},
{
"code": null,
"e": 29015,
"s": 28974,
"text": "Code #2: If destination is a directory "
},
{
"code": null,
"e": 29023,
"s": 29015,
"text": "Python3"
},
{
"code": "# Python program to explain shutil.copy() method # importing os moduleimport os # importing shutil moduleimport shutil # Source pathsource = \"/home/User/Documents/file.txt\" # Destination pathdestination = \"/home/User/Desktop/\" # Copy the content of# source to destinationdest = shutil.copy(source, destination) # List files and directories# in \"/home / User / Desktop\"print(\"After copying file:\")print(os.listdir(destination)) # Print path of newly# created fileprint(\"Destination path:\", dest)",
"e": 29521,
"s": 29023,
"text": null
},
{
"code": null,
"e": 29666,
"s": 29521,
"text": "After copying file:\n['input.txt', 'GeeksForGeeks', 'output.txt', 'file.txt', 'web.py', 'tree.cpp']\nDestination path: /home/User/Desktop/file.txt"
},
{
"code": null,
"e": 29728,
"s": 29668,
"text": "Code #3: Possible errors while using shutil.copy() method "
},
{
"code": null,
"e": 29736,
"s": 29728,
"text": "Python3"
},
{
"code": "# Python program to explain shutil.copy() method # importing shutil moduleimport shutil # If the source and destination# represents the same file# 'SameFileError' exception# will be raised # If the destination is# not writable# 'PermissionError' exception# will be raised # Source pathsource = \"/home/User/Documents/file.txt\" # Destination pathdestination = \"/home/User/Documents/file.txt\" # Copy the content of# source to destinationshutil.copy(source, destination)",
"e": 30207,
"s": 29736,
"text": null
},
{
"code": null,
"e": 30671,
"s": 30207,
"text": "Traceback (most recent call last):\n File \"try.py\", line 26, in \n dest = shutil.copy(source, destination)\n File \"/usr/lib/python3.6/shutil.py\", line 241, in copy\n copyfile(src, dst, follow_symlinks=follow_symlinks)\n File \"/usr/lib/python3.6/shutil.py\", line 104, in copyfile\n raise SameFileError(\"{!r} and {!r} are the same file\".format(src, dst))\nshutil.SameFileError: '/home/User/Desktop/file.txt' and '/home/User/Desktop/file.txt'\nare the same file"
},
{
"code": null,
"e": 30733,
"s": 30673,
"text": "Code #4: Handling errors while using shutil.copy() method "
},
{
"code": null,
"e": 30741,
"s": 30733,
"text": "Python3"
},
{
"code": "# Python program to explain shutil.copy() method # importing shutil moduleimport shutil # Source pathsource = \"/home/User/Documents/file.txt\" # Destination pathdestination = \"/home/User/Documents/file.txt\" # Copy the content of# source to destination try: shutil.copy(source, destination) print(\"File copied successfully.\") # If source and destination are sameexcept shutil.SameFileError: print(\"Source and destination represents the same file.\") # If there is any permission issueexcept PermissionError: print(\"Permission denied.\") # For other errorsexcept: print(\"Error occurred while copying file.\")",
"e": 31361,
"s": 30741,
"text": null
},
{
"code": null,
"e": 31410,
"s": 31361,
"text": "Source and destination represents the same file."
},
{
"code": null,
"e": 31470,
"s": 31412,
"text": "Reference: https://docs.python.org/3/library/shutil.html "
},
{
"code": null,
"e": 31489,
"s": 31470,
"text": "surindertarika1234"
},
{
"code": null,
"e": 31504,
"s": 31489,
"text": "python-utility"
},
{
"code": null,
"e": 31511,
"s": 31504,
"text": "Python"
},
{
"code": null,
"e": 31609,
"s": 31511,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31641,
"s": 31609,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 31663,
"s": 31641,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 31705,
"s": 31663,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 31734,
"s": 31705,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 31771,
"s": 31734,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 31807,
"s": 31771,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 31849,
"s": 31807,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 31874,
"s": 31849,
"text": "sum() function in Python"
},
{
"code": null,
"e": 31916,
"s": 31874,
"text": "How To Convert Python Dictionary To JSON?"
}
] |
How to create form validation by using only HTML ? - GeeksforGeeks
|
15 Apr, 2020
In Web Development, we often use JavaScript with HTML to validate the form, but we can also do the same via HTML in the following ways.
HTML <input> required Attribute
HTML <input> type Attribute
HTML <input> pattern Attribute
HTML <input> required Attribute: In input tag of HTML, we can specify via “required attribute”. It informs the browser (HTML5 supported) that the field can’t be left blank. Browsers vary in terms of this implementation, some browsers case a shadow to the box or some show a warning.
Example:<!DOCTYPE html><html lang="en"> <head> <title>Form</title></head> <body> <p>This is a form</p> <form> <p>Name:</p> <input type="text" required> <p>Email:</p> <input type="email" required> <p>Address:</p> <input type="text" required> <br> <button style="margin-top: 5px;"> Submit </button> </form> </body> </html>
<!DOCTYPE html><html lang="en"> <head> <title>Form</title></head> <body> <p>This is a form</p> <form> <p>Name:</p> <input type="text" required> <p>Email:</p> <input type="email" required> <p>Address:</p> <input type="text" required> <br> <button style="margin-top: 5px;"> Submit </button> </form> </body> </html>
Output:
HTML <input> type Attribute: In input tag, if we require for the user to input their email-id we can set the type attribute to email, the same is applicable to number, date or URL. Similar to the required attribute, different browsers have different implementations.
Example:<!DOCTYPE html><html lang="en"> <head> <title>Form</title></head> <body> <p>This is a form</p> <form> <p>URL:</p> <input type="url"> <p>Email:</p> <input type="email"> <p>Phone Number:</p> <input type="number"> <br> <button style="margin-top: 5px;"> Submit </button> </form> </body> </html>
<!DOCTYPE html><html lang="en"> <head> <title>Form</title></head> <body> <p>This is a form</p> <form> <p>URL:</p> <input type="url"> <p>Email:</p> <input type="email"> <p>Phone Number:</p> <input type="number"> <br> <button style="margin-top: 5px;"> Submit </button> </form> </body> </html>
Output:
HTML <input> pattern Attribute: We already know, apart from using default rules we can also set our rules as for the pattern of URL, date or price, etc.
Example:<!DOCTYPE html><html lang="en"> <head> <title>Form</title></head> <body> <p>This is a form</p> <form> <p>URL:</p> <input type="url" pattern="https?://.+"> <p>Date1:</p> <input type="date" pattern="\d{2, 1}/\d{2, 1}/\d{4}"> <br> <button style="margin-top: 5px;"> Submit </button> </form></body> </html>
<!DOCTYPE html><html lang="en"> <head> <title>Form</title></head> <body> <p>This is a form</p> <form> <p>URL:</p> <input type="url" pattern="https?://.+"> <p>Date1:</p> <input type="date" pattern="\d{2, 1}/\d{2, 1}/\d{4}"> <br> <button style="margin-top: 5px;"> Submit </button> </form></body> </html>
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-Misc
Picked
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
|
[
{
"code": null,
"e": 33028,
"s": 33000,
"text": "\n15 Apr, 2020"
},
{
"code": null,
"e": 33164,
"s": 33028,
"text": "In Web Development, we often use JavaScript with HTML to validate the form, but we can also do the same via HTML in the following ways."
},
{
"code": null,
"e": 33196,
"s": 33164,
"text": "HTML <input> required Attribute"
},
{
"code": null,
"e": 33224,
"s": 33196,
"text": "HTML <input> type Attribute"
},
{
"code": null,
"e": 33255,
"s": 33224,
"text": "HTML <input> pattern Attribute"
},
{
"code": null,
"e": 33538,
"s": 33255,
"text": "HTML <input> required Attribute: In input tag of HTML, we can specify via “required attribute”. It informs the browser (HTML5 supported) that the field can’t be left blank. Browsers vary in terms of this implementation, some browsers case a shadow to the box or some show a warning."
},
{
"code": null,
"e": 33947,
"s": 33538,
"text": "Example:<!DOCTYPE html><html lang=\"en\"> <head> <title>Form</title></head> <body> <p>This is a form</p> <form> <p>Name:</p> <input type=\"text\" required> <p>Email:</p> <input type=\"email\" required> <p>Address:</p> <input type=\"text\" required> <br> <button style=\"margin-top: 5px;\"> Submit </button> </form> </body> </html>"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Form</title></head> <body> <p>This is a form</p> <form> <p>Name:</p> <input type=\"text\" required> <p>Email:</p> <input type=\"email\" required> <p>Address:</p> <input type=\"text\" required> <br> <button style=\"margin-top: 5px;\"> Submit </button> </form> </body> </html>",
"e": 34348,
"s": 33947,
"text": null
},
{
"code": null,
"e": 34356,
"s": 34348,
"text": "Output:"
},
{
"code": null,
"e": 34623,
"s": 34356,
"text": "HTML <input> type Attribute: In input tag, if we require for the user to input their email-id we can set the type attribute to email, the same is applicable to number, date or URL. Similar to the required attribute, different browsers have different implementations."
},
{
"code": null,
"e": 35010,
"s": 34623,
"text": "Example:<!DOCTYPE html><html lang=\"en\"> <head> <title>Form</title></head> <body> <p>This is a form</p> <form> <p>URL:</p> <input type=\"url\"> <p>Email:</p> <input type=\"email\"> <p>Phone Number:</p> <input type=\"number\"> <br> <button style=\"margin-top: 5px;\"> Submit </button> </form> </body> </html>"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Form</title></head> <body> <p>This is a form</p> <form> <p>URL:</p> <input type=\"url\"> <p>Email:</p> <input type=\"email\"> <p>Phone Number:</p> <input type=\"number\"> <br> <button style=\"margin-top: 5px;\"> Submit </button> </form> </body> </html>",
"e": 35389,
"s": 35010,
"text": null
},
{
"code": null,
"e": 35397,
"s": 35389,
"text": "Output:"
},
{
"code": null,
"e": 35550,
"s": 35397,
"text": "HTML <input> pattern Attribute: We already know, apart from using default rules we can also set our rules as for the pattern of URL, date or price, etc."
},
{
"code": null,
"e": 35948,
"s": 35550,
"text": "Example:<!DOCTYPE html><html lang=\"en\"> <head> <title>Form</title></head> <body> <p>This is a form</p> <form> <p>URL:</p> <input type=\"url\" pattern=\"https?://.+\"> <p>Date1:</p> <input type=\"date\" pattern=\"\\d{2, 1}/\\d{2, 1}/\\d{4}\"> <br> <button style=\"margin-top: 5px;\"> Submit </button> </form></body> </html>"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Form</title></head> <body> <p>This is a form</p> <form> <p>URL:</p> <input type=\"url\" pattern=\"https?://.+\"> <p>Date1:</p> <input type=\"date\" pattern=\"\\d{2, 1}/\\d{2, 1}/\\d{4}\"> <br> <button style=\"margin-top: 5px;\"> Submit </button> </form></body> </html>",
"e": 36338,
"s": 35948,
"text": null
},
{
"code": null,
"e": 36475,
"s": 36338,
"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": 36491,
"s": 36475,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 36501,
"s": 36491,
"text": "HTML-Misc"
},
{
"code": null,
"e": 36508,
"s": 36501,
"text": "Picked"
},
{
"code": null,
"e": 36513,
"s": 36508,
"text": "HTML"
},
{
"code": null,
"e": 36530,
"s": 36513,
"text": "Web Technologies"
},
{
"code": null,
"e": 36557,
"s": 36530,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 36562,
"s": 36557,
"text": "HTML"
},
{
"code": null,
"e": 36660,
"s": 36562,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36722,
"s": 36660,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 36772,
"s": 36722,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 36820,
"s": 36772,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 36880,
"s": 36820,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 36933,
"s": 36880,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 36973,
"s": 36933,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 37006,
"s": 36973,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 37051,
"s": 37006,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 37094,
"s": 37051,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
setfillstyle() and floodfill() in C - GeeksforGeeks
|
25 Jan, 2018
The header file graphics.h contains setfillstyle() function which sets the current fill pattern and fill color. floodfill() function is used to fill an enclosed area. Current fill pattern and fill color is used to fill the area.
Syntax :
void setfillstyle(int pattern, int color)
void floodfill(int x, int y, int border_color)
Examples :
Input : pattern = HATCH_FILL, Color = RED
circle : x = 250, y = 250, radius = 100
floodfill : x = 250, y = 250, border color =15
Output :
Input : pattern = LTSLASH_FILL, Color = RED
rectangle : left = 200, top = 200, right = 450, bottom = 450
floodfill : x = 201, y = 201, border_color = 15
Output :
Below is the table showing INT VALUES corresponding to Colors :
COLOR INT VALUES
-------------------------------
BLACK 0
BLUE 1
GREEN 2
CYAN 3
RED 4
MAGENTA 5
BROWN 6
LIGHTGRAY 7
DARKGRAY 8
LIGHTBLUE 9
LIGHTGREEN 10
LIGHTCYAN 11
LIGHTRED 12
LIGHTMAGENTA 13
YELLOW 14
WHITE 15
Below is the table showing INT VALUES corresponding to Patterns :
PATTERN INT VALUES
-------------------------------
EMPTY_FILL 0
SOLID_FILL 1
LINE_FILL 2
LTSLASH_FILL 3
SLASH_FILL 4
BKSLASH_FILL 5
LTBKSLASH_FILL 6
HATCH_FILL 7
XHATCH_FILL 8
INTERLEAVE_FILL 9
WIDE_DOT_FILL 10
CLOSE_DOT_FILL 11
USER_FILL 12
Below is the implementation for setfillstyle() and floodfill() function :
// C Implementation for setfillstyle// and floodfill function#include <graphics.h> // driver codeint main(){ // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // "graphics.h" header file int gd = DETECT, gm; // initgraph initializes the // graphics system by loading // a graphics driver from disk initgraph(&gd, &gm, " "); // center and radius of circle int x_circle = 250; int y_circle = 250; int radius=100; // setting border color int border_color = WHITE; // set color and pattern setfillstyle(HATCH_FILL,RED); // x and y is a position and // radius is for radius of circle circle(x_circle,y_circle,radius); // fill the color at location // (x, y) with in border color floodfill(x_circle,y_circle,border_color); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system closegraph(); return 0;}
Output:
c-graphics
computer-graphics
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Converting Strings to Numbers in C/C++
Left Shift and Right Shift Operators in C/C++
Function Pointer in C
Core Dump (Segmentation fault) in C/C++
rand() and srand() in C/C++
std::string class in C++
fork() in C
Enumeration (or enum) in C
|
[
{
"code": null,
"e": 26027,
"s": 25999,
"text": "\n25 Jan, 2018"
},
{
"code": null,
"e": 26256,
"s": 26027,
"text": "The header file graphics.h contains setfillstyle() function which sets the current fill pattern and fill color. floodfill() function is used to fill an enclosed area. Current fill pattern and fill color is used to fill the area."
},
{
"code": null,
"e": 26265,
"s": 26256,
"text": "Syntax :"
},
{
"code": null,
"e": 26356,
"s": 26265,
"text": "void setfillstyle(int pattern, int color)\n\nvoid floodfill(int x, int y, int border_color)\n"
},
{
"code": null,
"e": 26367,
"s": 26356,
"text": "Examples :"
},
{
"code": null,
"e": 26704,
"s": 26367,
"text": "Input : pattern = HATCH_FILL, Color = RED \n circle : x = 250, y = 250, radius = 100 \n floodfill : x = 250, y = 250, border color =15\nOutput : \n\n\nInput : pattern = LTSLASH_FILL, Color = RED\n rectangle : left = 200, top = 200, right = 450, bottom = 450\n floodfill : x = 201, y = 201, border_color = 15\nOutput :\n\n"
},
{
"code": null,
"e": 26768,
"s": 26704,
"text": "Below is the table showing INT VALUES corresponding to Colors :"
},
{
"code": null,
"e": 27253,
"s": 26768,
"text": "COLOR INT VALUES\n-------------------------------\nBLACK 0\nBLUE 1\nGREEN 2\nCYAN 3 \nRED 4\nMAGENTA 5\nBROWN 6 \nLIGHTGRAY 7 \nDARKGRAY 8\nLIGHTBLUE 9\nLIGHTGREEN 10\nLIGHTCYAN 11\nLIGHTRED 12\nLIGHTMAGENTA 13\nYELLOW 14\nWHITE 15\n"
},
{
"code": null,
"e": 27319,
"s": 27253,
"text": "Below is the table showing INT VALUES corresponding to Patterns :"
},
{
"code": null,
"e": 27740,
"s": 27319,
"text": "PATTERN INT VALUES\n-------------------------------\nEMPTY_FILL 0\nSOLID_FILL 1\nLINE_FILL 2\nLTSLASH_FILL 3 \nSLASH_FILL 4\nBKSLASH_FILL 5\nLTBKSLASH_FILL 6 \nHATCH_FILL 7 \nXHATCH_FILL 8\nINTERLEAVE_FILL 9\nWIDE_DOT_FILL 10\nCLOSE_DOT_FILL 11\nUSER_FILL 12\n"
},
{
"code": null,
"e": 27814,
"s": 27740,
"text": "Below is the implementation for setfillstyle() and floodfill() function :"
},
{
"code": "// C Implementation for setfillstyle// and floodfill function#include <graphics.h> // driver codeint main(){ // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // \"graphics.h\" header file int gd = DETECT, gm; // initgraph initializes the // graphics system by loading // a graphics driver from disk initgraph(&gd, &gm, \" \"); // center and radius of circle int x_circle = 250; int y_circle = 250; int radius=100; // setting border color int border_color = WHITE; // set color and pattern setfillstyle(HATCH_FILL,RED); // x and y is a position and // radius is for radius of circle circle(x_circle,y_circle,radius); // fill the color at location // (x, y) with in border color floodfill(x_circle,y_circle,border_color); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system closegraph(); return 0;}",
"e": 28908,
"s": 27814,
"text": null
},
{
"code": null,
"e": 28916,
"s": 28908,
"text": "Output:"
},
{
"code": null,
"e": 28929,
"s": 28918,
"text": "c-graphics"
},
{
"code": null,
"e": 28947,
"s": 28929,
"text": "computer-graphics"
},
{
"code": null,
"e": 28958,
"s": 28947,
"text": "C Language"
},
{
"code": null,
"e": 29056,
"s": 28958,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29073,
"s": 29056,
"text": "Substring in C++"
},
{
"code": null,
"e": 29108,
"s": 29073,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 29147,
"s": 29108,
"text": "Converting Strings to Numbers in C/C++"
},
{
"code": null,
"e": 29193,
"s": 29147,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 29215,
"s": 29193,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 29255,
"s": 29215,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 29283,
"s": 29255,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 29308,
"s": 29283,
"text": "std::string class in C++"
},
{
"code": null,
"e": 29320,
"s": 29308,
"text": "fork() in C"
}
] |
How to Disable an datepicker in jQuery UI ? - GeeksforGeeks
|
27 Jan, 2021
To disable a datepicker in jQuery UI we will be using disable() method which is discussed below:
jQuery UI disable() method is used to disable the datepicker.
Syntax:
$( ".selector" ).datepicker( "disable" )
Parameters: This method does not accept any parameters.
Return values: This method returns an object value
Approach: First, add jQuery UI scripts needed for your project.
<<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <link href="https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet" /> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> <script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"> </script> <script> $(function() { $("#gfg").datepicker(); $("#gfg").datepicker("disable"); }); </script></head> <body> <p>Enter Date: <input type="text" id="gfg" /></p></body> </html>
Output:
jQuery-UI
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show and Hide div elements using radio buttons?
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
jQuery | removeAttr() with Examples
How to get the value in an input text box using jQuery ?
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": 27144,
"s": 27116,
"text": "\n27 Jan, 2021"
},
{
"code": null,
"e": 27241,
"s": 27144,
"text": "To disable a datepicker in jQuery UI we will be using disable() method which is discussed below:"
},
{
"code": null,
"e": 27303,
"s": 27241,
"text": "jQuery UI disable() method is used to disable the datepicker."
},
{
"code": null,
"e": 27311,
"s": 27303,
"text": "Syntax:"
},
{
"code": null,
"e": 27352,
"s": 27311,
"text": "$( \".selector\" ).datepicker( \"disable\" )"
},
{
"code": null,
"e": 27408,
"s": 27352,
"text": "Parameters: This method does not accept any parameters."
},
{
"code": null,
"e": 27459,
"s": 27408,
"text": "Return values: This method returns an object value"
},
{
"code": null,
"e": 27523,
"s": 27459,
"text": "Approach: First, add jQuery UI scripts needed for your project."
},
{
"code": null,
"e": 27767,
"s": 27523,
"text": "<<link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\" rel = \"stylesheet\">\n<script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n<script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>"
},
{
"code": null,
"e": 27776,
"s": 27767,
"text": "Example:"
},
{
"code": null,
"e": 27781,
"s": 27776,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <link href=\"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\" rel=\"stylesheet\" /> <script src=\"https://code.jquery.com/jquery-1.10.2.js\"></script> <script src=\"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"> </script> <script> $(function() { $(\"#gfg\").datepicker(); $(\"#gfg\").datepicker(\"disable\"); }); </script></head> <body> <p>Enter Date: <input type=\"text\" id=\"gfg\" /></p></body> </html>",
"e": 28335,
"s": 27781,
"text": null
},
{
"code": null,
"e": 28343,
"s": 28335,
"text": "Output:"
},
{
"code": null,
"e": 28353,
"s": 28343,
"text": "jQuery-UI"
},
{
"code": null,
"e": 28360,
"s": 28353,
"text": "JQuery"
},
{
"code": null,
"e": 28377,
"s": 28360,
"text": "Web Technologies"
},
{
"code": null,
"e": 28475,
"s": 28377,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28530,
"s": 28475,
"text": "How to Show and Hide div elements using radio buttons?"
},
{
"code": null,
"e": 28603,
"s": 28530,
"text": "How to prevent Body from scrolling when a modal is opened using jQuery ?"
},
{
"code": null,
"e": 28626,
"s": 28603,
"text": "jQuery | ajax() Method"
},
{
"code": null,
"e": 28662,
"s": 28626,
"text": "jQuery | removeAttr() with Examples"
},
{
"code": null,
"e": 28719,
"s": 28662,
"text": "How to get the value in an input text box using jQuery ?"
},
{
"code": null,
"e": 28759,
"s": 28719,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28792,
"s": 28759,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28837,
"s": 28792,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28880,
"s": 28837,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Spring Boot - Application Properties - GeeksforGeeks
|
15 Dec, 2021
As we already know Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because it’s a rapid production-ready environment that enables the developers to directly focus on the logic instead of struggling with the configuration and set-up. In Spring Boot, whenever you create a new Spring Boot Application in spring starter, or inside an IDE (Eclipse or STS) a file is located inside the src/main/resources folder named as application.properties file which is shown in the below image as shown below as follows:
Geeks, now you must be wondering what does this file do? What are the major roles of this file during development? So in a spring boot application, application.properties file is used to write the application-related property into that file. This file contains the different configuration which is required to run the application in a different environment, and each environment will have a different property defined by it. Inside the application properties file, we define every type of property like changing the port, database connectivity, connection to the eureka server, and many more. Now let’s see some examples for better understanding.
Example 1: To Change the Port Number
Sometimes when you run your spring application you may encounter the following type of error
The error is Port 8989 was already in use. So in this case you may kill that process that is running on this port number or you may change your port number and rerun your application. So where do you have to change your port number? e.g in the application.properties file.
So as given in the above screenshot you can change your port number by the following line
server.port=8989
Example 2: To define the name of our application
To define the name of our application you can write the properties like this
spring.application.name = userservice
So you can see this represents the property as key-value pair here, every key associated with a value also.
Example 3: Connecting with the MySQL Database
To connect with the MySQL Database you have to write a bunch of lines. You can write the properties like this
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_example
spring.datasource.username=springuser
spring.datasource.password=ThePassword
spring.datasource.driver-class-name =com.mysql.jdbc.Driver
Example 4: Connecting with the H2 Database
H2 is an embedded, open-source, and in-memory database. It is a relational database management system written in Java. It is a client/server application. It is generally used in unit testing. It stores data in memory, not persist the data on disk. To connect with the H2 Database you have to write a bunch of lines. You can write the properties like this
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:dcbapp
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
Example 5: Connecting with the MongoDB Database
To connect with the MongoDB Database you have to write a bunch of lines. You can write the properties like this
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=BookStore
Example 6: Connecting with the Eureka Server
Eureka Server is an application that holds information about all client-service applications. Every Microservice will register into the Eureka server and the Eureka server knows all the client applications running on each port and IP address. Eureka Server is also known as Discovery Server. You can write the properties like this
eureka.client.register-with-eureka=true
eureka.client.fetch-registry=true
eureka.client.service-url.defaultZone=http://localhost:9096/eureka/
eureka.instance.hostname=localhost
Note: The value written here is sample data. Please write the values as per your requirements. But the keys remain the same.
The application.properties file is not that readable. So most of the time developers choose application.yml file over application.properties file. YAML is a superset of JSON, and as such is a very convenient format for specifying hierarchical configuration data. YAML is more readable and it is good for the developers to read/write configuration files. For example, let’s pick some of the properties files that we have explained above, and let’s write them in YAML format.
Case 1: Let’s pick above example 3 where we were connecting with the MySQL Database, the corresponding properties will be as follows:
spring:
datasource:
url: jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_example
username: springuser
password: ThePassword
driver-class-name: com.mysql.jdbc.Driver
jpa:
hibernate:
ddl-auto: update
Case 2: Let’s pick above example 6 where we were connecting with the Eureka Server, the corresponding properties will be as follows:
eureka:
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://localhost:9096/eureka/
instance:
hostname: localhost
Java-Spring-Boot
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java
|
[
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n15 Dec, 2021"
},
{
"code": null,
"e": 25821,
"s": 25225,
"text": "As we already know Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because it’s a rapid production-ready environment that enables the developers to directly focus on the logic instead of struggling with the configuration and set-up. In Spring Boot, whenever you create a new Spring Boot Application in spring starter, or inside an IDE (Eclipse or STS) a file is located inside the src/main/resources folder named as application.properties file which is shown in the below image as shown below as follows:"
},
{
"code": null,
"e": 26468,
"s": 25821,
"text": "Geeks, now you must be wondering what does this file do? What are the major roles of this file during development? So in a spring boot application, application.properties file is used to write the application-related property into that file. This file contains the different configuration which is required to run the application in a different environment, and each environment will have a different property defined by it. Inside the application properties file, we define every type of property like changing the port, database connectivity, connection to the eureka server, and many more. Now let’s see some examples for better understanding."
},
{
"code": null,
"e": 26505,
"s": 26468,
"text": "Example 1: To Change the Port Number"
},
{
"code": null,
"e": 26598,
"s": 26505,
"text": "Sometimes when you run your spring application you may encounter the following type of error"
},
{
"code": null,
"e": 26871,
"s": 26598,
"text": "The error is Port 8989 was already in use. So in this case you may kill that process that is running on this port number or you may change your port number and rerun your application. So where do you have to change your port number? e.g in the application.properties file."
},
{
"code": null,
"e": 26962,
"s": 26871,
"text": "So as given in the above screenshot you can change your port number by the following line "
},
{
"code": null,
"e": 26979,
"s": 26962,
"text": "server.port=8989"
},
{
"code": null,
"e": 27028,
"s": 26979,
"text": "Example 2: To define the name of our application"
},
{
"code": null,
"e": 27105,
"s": 27028,
"text": "To define the name of our application you can write the properties like this"
},
{
"code": null,
"e": 27143,
"s": 27105,
"text": "spring.application.name = userservice"
},
{
"code": null,
"e": 27251,
"s": 27143,
"text": "So you can see this represents the property as key-value pair here, every key associated with a value also."
},
{
"code": null,
"e": 27297,
"s": 27251,
"text": "Example 3: Connecting with the MySQL Database"
},
{
"code": null,
"e": 27407,
"s": 27297,
"text": "To connect with the MySQL Database you have to write a bunch of lines. You can write the properties like this"
},
{
"code": null,
"e": 27655,
"s": 27407,
"text": "spring.jpa.hibernate.ddl-auto=update\nspring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_example\nspring.datasource.username=springuser\nspring.datasource.password=ThePassword\nspring.datasource.driver-class-name =com.mysql.jdbc.Driver"
},
{
"code": null,
"e": 27698,
"s": 27655,
"text": "Example 4: Connecting with the H2 Database"
},
{
"code": null,
"e": 28053,
"s": 27698,
"text": "H2 is an embedded, open-source, and in-memory database. It is a relational database management system written in Java. It is a client/server application. It is generally used in unit testing. It stores data in memory, not persist the data on disk. To connect with the H2 Database you have to write a bunch of lines. You can write the properties like this"
},
{
"code": null,
"e": 28300,
"s": 28053,
"text": "spring.h2.console.enabled=true\nspring.datasource.url=jdbc:h2:mem:dcbapp\nspring.datasource.driverClassName=org.h2.Driver\nspring.datasource.username=sa\nspring.datasource.password=password\nspring.jpa.database-platform=org.hibernate.dialect.H2Dialect"
},
{
"code": null,
"e": 28348,
"s": 28300,
"text": "Example 5: Connecting with the MongoDB Database"
},
{
"code": null,
"e": 28460,
"s": 28348,
"text": "To connect with the MongoDB Database you have to write a bunch of lines. You can write the properties like this"
},
{
"code": null,
"e": 28565,
"s": 28460,
"text": "spring.data.mongodb.host=localhost\nspring.data.mongodb.port=27017\nspring.data.mongodb.database=BookStore"
},
{
"code": null,
"e": 28610,
"s": 28565,
"text": "Example 6: Connecting with the Eureka Server"
},
{
"code": null,
"e": 28941,
"s": 28610,
"text": "Eureka Server is an application that holds information about all client-service applications. Every Microservice will register into the Eureka server and the Eureka server knows all the client applications running on each port and IP address. Eureka Server is also known as Discovery Server. You can write the properties like this"
},
{
"code": null,
"e": 29118,
"s": 28941,
"text": "eureka.client.register-with-eureka=true\neureka.client.fetch-registry=true\neureka.client.service-url.defaultZone=http://localhost:9096/eureka/\neureka.instance.hostname=localhost"
},
{
"code": null,
"e": 29244,
"s": 29118,
"text": "Note: The value written here is sample data. Please write the values as per your requirements. But the keys remain the same. "
},
{
"code": null,
"e": 29718,
"s": 29244,
"text": "The application.properties file is not that readable. So most of the time developers choose application.yml file over application.properties file. YAML is a superset of JSON, and as such is a very convenient format for specifying hierarchical configuration data. YAML is more readable and it is good for the developers to read/write configuration files. For example, let’s pick some of the properties files that we have explained above, and let’s write them in YAML format."
},
{
"code": null,
"e": 29852,
"s": 29718,
"text": "Case 1: Let’s pick above example 3 where we were connecting with the MySQL Database, the corresponding properties will be as follows:"
},
{
"code": null,
"e": 30077,
"s": 29852,
"text": "spring:\n datasource:\n url: jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_example\n username: springuser\n password: ThePassword\n driver-class-name: com.mysql.jdbc.Driver\n jpa:\n hibernate:\n ddl-auto: update"
},
{
"code": null,
"e": 30210,
"s": 30077,
"text": "Case 2: Let’s pick above example 6 where we were connecting with the Eureka Server, the corresponding properties will be as follows:"
},
{
"code": null,
"e": 30386,
"s": 30210,
"text": "eureka:\n client:\n register-with-eureka: true\n fetch-registry: true\n service-url:\n defaultZone: http://localhost:9096/eureka/\n instance:\n hostname: localhost"
},
{
"code": null,
"e": 30403,
"s": 30386,
"text": "Java-Spring-Boot"
},
{
"code": null,
"e": 30410,
"s": 30403,
"text": "Picked"
},
{
"code": null,
"e": 30415,
"s": 30410,
"text": "Java"
},
{
"code": null,
"e": 30420,
"s": 30415,
"text": "Java"
},
{
"code": null,
"e": 30518,
"s": 30420,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30533,
"s": 30518,
"text": "Stream In Java"
},
{
"code": null,
"e": 30554,
"s": 30533,
"text": "Constructors in Java"
},
{
"code": null,
"e": 30573,
"s": 30554,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 30603,
"s": 30573,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 30649,
"s": 30603,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 30666,
"s": 30649,
"text": "Generics in Java"
},
{
"code": null,
"e": 30687,
"s": 30666,
"text": "Introduction to Java"
},
{
"code": null,
"e": 30730,
"s": 30687,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 30766,
"s": 30730,
"text": "Internal Working of HashMap in Java"
}
] |
GATE | GATE CS 2008 | Question 63 - GeeksforGeeks
|
02 Dec, 2021
The P and V operations on counting semaphores, where s is a counting semaphore, are defined as follows:
P(s) : s = s - 1;
if (s < 0) then wait;
V(s) : s = s + 1;
if (s <= 0) then wakeup a process waiting on s;
Assume that Pb and Vb the wait and signal operations on binary semaphores are provided. Two binary semaphores Xb and Yb are used to implement the semaphore operations P(s) and V(s) as follows:
P(s) : Pb(Xb);
s = s - 1;
if (s < 0) {
Vb(Xb) ;
Pb(Yb) ;
}
else Vb(Xb);
V(s) : Pb(Xb) ;
s = s + 1;
if (s <= 0) Vb(Yb) ;
Vb(Xb) ;
The initial values of Xb and Yb are respectively
(A) 0 and 0(B) 0 and 1
(C) 1 and 0
(D) 1 and 1Answer: (C)Explanation: Suppose Xb = 0, then because of P(s): Pb(Xb) operation, Xb will be -1 and process will get blocked as it will enter into waiting section.
So, Xb will be one.
Suppose s=2(means 2 process are accessing shared resource), taking Xb as 1,
first P(s): Pb(Xb) operation will make Xb as zero. s will be 1 and Then Vb(Xb) operation will be executed which will increase the count of Xb as one. Then same process will be repeated making Xb as one and s as zero.
Now suppose one more process comes, then Xb will be 0 but s will be -1 which will make this process go into loop (s <0) and will result into calling Vb(Xb) and Pb(Yb) operations. Vb(Xb) will result into Xb as 1 and Pb(Yb) will result into decrementing the value of Yb.case 1: if Yb has value as 0, it will be -1 and it will go into waiting and will be blocked.total 2 process will access shared resource (according to counting semaphore, max 3 process can access shared resource) and value of s is -1 means only 1 process will be waiting for resources and just now, one process got blocked. So it is still true.
case 2: if Yb has value as 1, it will be 0. Total 3 process will access shared resource (according to counting semaphore, max 2 process can access shared resource) and value of s is -1 means only 1 process will be waiting for resources and but there is no process waiting for resources.So it is false.
See Question 2 of https://www.geeksforgeeks.org/operating-systems-set-10/
This solution is contributed by Nitika Bansal
Quiz of this Question
harshilmarwah
kk773572498
GATE-CS-2008
GATE-GATE CS 2008
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2006 | Question 47
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
|
[
{
"code": null,
"e": 25833,
"s": 25805,
"text": "\n02 Dec, 2021"
},
{
"code": null,
"e": 25937,
"s": 25833,
"text": "The P and V operations on counting semaphores, where s is a counting semaphore, are defined as follows:"
},
{
"code": null,
"e": 26049,
"s": 25937,
"text": "P(s) : s = s - 1;\n if (s < 0) then wait;\nV(s) : s = s + 1;\n if (s <= 0) then wakeup a process waiting on s;"
},
{
"code": null,
"e": 26242,
"s": 26049,
"text": "Assume that Pb and Vb the wait and signal operations on binary semaphores are provided. Two binary semaphores Xb and Yb are used to implement the semaphore operations P(s) and V(s) as follows:"
},
{
"code": null,
"e": 26393,
"s": 26242,
"text": "P(s) : Pb(Xb);\n s = s - 1;\n if (s < 0) {\n Vb(Xb) ;\n Pb(Yb) ;\n }\n else Vb(Xb); \n\nV(s) : Pb(Xb) ;\n s = s + 1;\n if (s <= 0) Vb(Yb) ;\n Vb(Xb) ;"
},
{
"code": null,
"e": 26442,
"s": 26393,
"text": "The initial values of Xb and Yb are respectively"
},
{
"code": null,
"e": 26465,
"s": 26442,
"text": "(A) 0 and 0(B) 0 and 1"
},
{
"code": null,
"e": 26477,
"s": 26465,
"text": "(C) 1 and 0"
},
{
"code": null,
"e": 26651,
"s": 26477,
"text": "(D) 1 and 1Answer: (C)Explanation: Suppose Xb = 0, then because of P(s): Pb(Xb) operation, Xb will be -1 and process will get blocked as it will enter into waiting section. "
},
{
"code": null,
"e": 26672,
"s": 26651,
"text": "So, Xb will be one. "
},
{
"code": null,
"e": 26748,
"s": 26672,
"text": "Suppose s=2(means 2 process are accessing shared resource), taking Xb as 1,"
},
{
"code": null,
"e": 26965,
"s": 26748,
"text": "first P(s): Pb(Xb) operation will make Xb as zero. s will be 1 and Then Vb(Xb) operation will be executed which will increase the count of Xb as one. Then same process will be repeated making Xb as one and s as zero."
},
{
"code": null,
"e": 27577,
"s": 26965,
"text": "Now suppose one more process comes, then Xb will be 0 but s will be -1 which will make this process go into loop (s <0) and will result into calling Vb(Xb) and Pb(Yb) operations. Vb(Xb) will result into Xb as 1 and Pb(Yb) will result into decrementing the value of Yb.case 1: if Yb has value as 0, it will be -1 and it will go into waiting and will be blocked.total 2 process will access shared resource (according to counting semaphore, max 3 process can access shared resource) and value of s is -1 means only 1 process will be waiting for resources and just now, one process got blocked. So it is still true."
},
{
"code": null,
"e": 27879,
"s": 27577,
"text": "case 2: if Yb has value as 1, it will be 0. Total 3 process will access shared resource (according to counting semaphore, max 2 process can access shared resource) and value of s is -1 means only 1 process will be waiting for resources and but there is no process waiting for resources.So it is false."
},
{
"code": null,
"e": 27954,
"s": 27879,
"text": "See Question 2 of https://www.geeksforgeeks.org/operating-systems-set-10/ "
},
{
"code": null,
"e": 28000,
"s": 27954,
"text": "This solution is contributed by Nitika Bansal"
},
{
"code": null,
"e": 28022,
"s": 28000,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 28036,
"s": 28022,
"text": "harshilmarwah"
},
{
"code": null,
"e": 28048,
"s": 28036,
"text": "kk773572498"
},
{
"code": null,
"e": 28061,
"s": 28048,
"text": "GATE-CS-2008"
},
{
"code": null,
"e": 28079,
"s": 28061,
"text": "GATE-GATE CS 2008"
},
{
"code": null,
"e": 28084,
"s": 28079,
"text": "GATE"
},
{
"code": null,
"e": 28182,
"s": 28084,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28216,
"s": 28182,
"text": "GATE | Gate IT 2007 | Question 25"
},
{
"code": null,
"e": 28250,
"s": 28216,
"text": "GATE | GATE-CS-2001 | Question 39"
},
{
"code": null,
"e": 28284,
"s": 28250,
"text": "GATE | GATE-CS-2000 | Question 41"
},
{
"code": null,
"e": 28317,
"s": 28284,
"text": "GATE | GATE-CS-2005 | Question 6"
},
{
"code": null,
"e": 28353,
"s": 28317,
"text": "GATE | GATE MOCK 2017 | Question 21"
},
{
"code": null,
"e": 28389,
"s": 28353,
"text": "GATE | GATE MOCK 2017 | Question 24"
},
{
"code": null,
"e": 28423,
"s": 28389,
"text": "GATE | GATE-CS-2006 | Question 47"
},
{
"code": null,
"e": 28457,
"s": 28423,
"text": "GATE | Gate IT 2008 | Question 43"
},
{
"code": null,
"e": 28491,
"s": 28457,
"text": "GATE | GATE-CS-2009 | Question 38"
}
] |
Python - Matrix Row subset - GeeksforGeeks
|
30 Dec, 2020
Sometimes, while working with Python Matrix, one can have a problem in which, one needs to extract all the rows that are a possible subset of any row of other Matrix. This kind of problem can have application in data domains as a matrix is a key data type in those domains. Let’s discuss certain ways in which this problem can be solved.
Input : test_list = [[4, 5, 7], [2, 3, 4], [9, 8, 6]], check_matr = [[2, 3], [1, 2], [9, 0]]Output : [[2, 3]]
Input : test_list = [[4, 1, 2], [2, 3, 4], [9, 8, 0]], check_matr = [[2, 3], [1, 2], [9, 0]]Output : [[2, 3], [1, 2], [9, 0]]
Method #1 : Using any() + all() + list comprehensionThe combination of above functions offer a way in which this problem can be solved. In this, we check for occurrence of all elements of row using all() and any() is used to match to any row of Matrix. List comprehension is used to bind the logic together.
# Python3 code to demonstrate working of # Matrix Row subset# Using any() + all() + list comprehension # initializing liststest_list = [[4, 5, 7], [2, 3, 4], [9, 8, 0]] # printing original listprint("The original list is : " + str(test_list)) # initializing check Matrixcheck_matr = [[2, 3], [1, 2], [9, 0]] # Matrix Row subset# Using any() + all() + list comprehensionres = [ele for ele in check_matr if any(all(a in sub for a in ele) for sub in test_list)] # printing result print("Matrix row subsets : " + str(res))
The original list is : [[4, 5, 7], [2, 3, 4], [9, 8, 0]]
Matrix row subsets : [[2, 3], [9, 0]]
Method #2 : Using product() + set() + list comprehensionThe combination of above functions can be used for this task. In this, we perform the task of nested loop using product() and set() conversion is to check for subset of one container over other. List comprehension is used to bind all together.
# Python3 code to demonstrate working of # Matrix Row subset# Using product() + set() + list comprehensionimport itertools # initializing liststest_list = [[4, 5, 7], [2, 3, 4], [9, 8, 0]] # printing original listprint("The original list is : " + str(test_list)) # initializing check Matrixcheck_matr = [[2, 3], [1, 2], [9, 0]] # Matrix Row subset# Using product() + set() + list comprehensionres = [a for a, b in itertools.product(check_matr, test_list) if set(a) <= set(b)] # printing result print("Matrix row subsets : " + str(res))
The original list is : [[4, 5, 7], [2, 3, 4], [9, 8, 0]]
Matrix row subsets : [[2, 3], [9, 0]]
Python list-programs
Python matrix-program
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n30 Dec, 2020"
},
{
"code": null,
"e": 25875,
"s": 25537,
"text": "Sometimes, while working with Python Matrix, one can have a problem in which, one needs to extract all the rows that are a possible subset of any row of other Matrix. This kind of problem can have application in data domains as a matrix is a key data type in those domains. Let’s discuss certain ways in which this problem can be solved."
},
{
"code": null,
"e": 25985,
"s": 25875,
"text": "Input : test_list = [[4, 5, 7], [2, 3, 4], [9, 8, 6]], check_matr = [[2, 3], [1, 2], [9, 0]]Output : [[2, 3]]"
},
{
"code": null,
"e": 26111,
"s": 25985,
"text": "Input : test_list = [[4, 1, 2], [2, 3, 4], [9, 8, 0]], check_matr = [[2, 3], [1, 2], [9, 0]]Output : [[2, 3], [1, 2], [9, 0]]"
},
{
"code": null,
"e": 26419,
"s": 26111,
"text": "Method #1 : Using any() + all() + list comprehensionThe combination of above functions offer a way in which this problem can be solved. In this, we check for occurrence of all elements of row using all() and any() is used to match to any row of Matrix. List comprehension is used to bind the logic together."
},
{
"code": "# Python3 code to demonstrate working of # Matrix Row subset# Using any() + all() + list comprehension # initializing liststest_list = [[4, 5, 7], [2, 3, 4], [9, 8, 0]] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing check Matrixcheck_matr = [[2, 3], [1, 2], [9, 0]] # Matrix Row subset# Using any() + all() + list comprehensionres = [ele for ele in check_matr if any(all(a in sub for a in ele) for sub in test_list)] # printing result print(\"Matrix row subsets : \" + str(res)) ",
"e": 26986,
"s": 26419,
"text": null
},
{
"code": null,
"e": 27082,
"s": 26986,
"text": "The original list is : [[4, 5, 7], [2, 3, 4], [9, 8, 0]]\nMatrix row subsets : [[2, 3], [9, 0]]\n"
},
{
"code": null,
"e": 27384,
"s": 27084,
"text": "Method #2 : Using product() + set() + list comprehensionThe combination of above functions can be used for this task. In this, we perform the task of nested loop using product() and set() conversion is to check for subset of one container over other. List comprehension is used to bind all together."
},
{
"code": "# Python3 code to demonstrate working of # Matrix Row subset# Using product() + set() + list comprehensionimport itertools # initializing liststest_list = [[4, 5, 7], [2, 3, 4], [9, 8, 0]] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing check Matrixcheck_matr = [[2, 3], [1, 2], [9, 0]] # Matrix Row subset# Using product() + set() + list comprehensionres = [a for a, b in itertools.product(check_matr, test_list) if set(a) <= set(b)] # printing result print(\"Matrix row subsets : \" + str(res)) ",
"e": 27966,
"s": 27384,
"text": null
},
{
"code": null,
"e": 28062,
"s": 27966,
"text": "The original list is : [[4, 5, 7], [2, 3, 4], [9, 8, 0]]\nMatrix row subsets : [[2, 3], [9, 0]]\n"
},
{
"code": null,
"e": 28083,
"s": 28062,
"text": "Python list-programs"
},
{
"code": null,
"e": 28105,
"s": 28083,
"text": "Python matrix-program"
},
{
"code": null,
"e": 28112,
"s": 28105,
"text": "Python"
},
{
"code": null,
"e": 28128,
"s": 28112,
"text": "Python Programs"
},
{
"code": null,
"e": 28226,
"s": 28128,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28258,
"s": 28226,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28300,
"s": 28258,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28342,
"s": 28300,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28369,
"s": 28342,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28425,
"s": 28369,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28447,
"s": 28425,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28486,
"s": 28447,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28532,
"s": 28486,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 28570,
"s": 28532,
"text": "Python | Convert a list to dictionary"
}
] |
Angular PrimeNG OrderList Component - GeeksforGeeks
|
03 Oct, 2021
Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the OrderList component in Angular PrimeNG. We will also learn about the properties, events & styling along with their syntaxes that will be used in the code example.
OrderList component: It is used to maintain the list of items and products.
Properties:
value: It is an array of objects to reorder. It accepts the array data type & the default value is null.
selection: It is an array of objects to bind the selections. It accepts the array data type & the default value is null.
header: It is the text for the caption. It is of string data type & the default value is null.
style: It is an inline style of the component. It is of string data type & the default value is null.
styleClass: It is the style class of the component. It is of string data type & the default value is null.
listStyle: It is an inline style of the list element. It is of string data type & the default value is null.
filterBy: It is used to specify whether to display an input field to filter the items on keyup and decides which fields to search against. It is of string data type & the default value is null.
filterMatchMode: It is used to define how the items are filtered. It is of string data type & the default value is contains.
filterLocale: It is used to set the locale to use in filtering. It is of string data type & the default value is undefined.
metaKeySelection: It is used to specify whether metaKey needs to be pressed to select or discard the item. It accepts the boolean data type & the default value is true.
dragdrop: It is used to specify whether to enable drag-drop based reordering. It accepts the boolean data type & the default value is false.
filterPlaceHolder: It is the placeholder text. It is of string data type & the default value is null.
trackBy: It is the function to optimize the dom operations by delegating to ngForTrackBy. It is of function type & the default value is null.
controlsPosition: It is used to define the location of the buttons with respect to the list, valid values are “left” or “right”. It is of string data type & the default value is left.
ariaFilterLabel: It is used to define a string that labels the filter input. It is of string data type & the default value is null.
Events:
onReorder: It is a callback that is fired when the list is reordered.
onSelectionChange: It is a callback to invoke when selection changes.
onFilterEvent: It is a callback that is fired when filtering occurs.
Styling:
p-orderlist: It is a container element.
p-orderlist-list: It is a list container.
p-orderlist-item: It is a list item.
Creating Angular application & module installation:
Step 1: Create an Angular application using the following command.
ng new appname
Step 2: After creating your project folder i.e. appname, move to it using the following command.
cd appname
Step 3: Install PrimeNG in your given directory.
npm install primeng --save
npm install primeicons --save
Project Structure: It will look like the following:
Example 1: This is the basic example that illustrates how to use the Orderlist component.
app.component.html
<h2>GeeksforGeeks</h2><p-orderList [value]="product" header="OrderList Component"> <ng-template let-product pTemplate="item"> <div class="product-item"> <div class="product-list-detail"> <h5 class="p-mb-2">{{product}}</h5> <h6 class="p-mb-2">{{gfg}}</h6> </div> </div> </ng-template></p-orderList>
app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent { product: string[] = ['Geek1', 'Geek2', 'Geek3', 'Geek4']; gfg: string[] = ['200'];}
app.module.ts
import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { OrderListModule } from 'primeng/orderlist'; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, OrderListModule], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {}
Output:
Example 2: In this example, we will use dragdrop property in the OrderList Component.
app.component.html
<h2>GeeksforGeeks</h2><p-orderList [value]="product" header="OrderList Component" dragdrop="true"> <ng-template let-product pTemplate="item"> <div class="product-item"> <div class="product-list-detail"> <h5 class="p-mb-2">{{product}}</h5> <h6 class="p-mb-2">{{gfg}}</h6> </div> </div> </ng-template></p-orderList>
app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent { product: string[] = ['Geek1', 'Geek2', 'Geek3', 'Geek4']; gfg: string[] = ['200'];}
app.module.ts
import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { OrderListModule } from 'primeng/orderlist'; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, OrderListModule], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {}
Output:
Reference: https://primefaces.org/primeng/showcase/#/orderlist
Angular-PrimeNG
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular PrimeNG Dropdown Component
Angular PrimeNG Calendar Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Angular PrimeNG Messages Component
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
|
[
{
"code": null,
"e": 26354,
"s": 26326,
"text": "\n03 Oct, 2021"
},
{
"code": null,
"e": 26763,
"s": 26354,
"text": "Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the OrderList component in Angular PrimeNG. We will also learn about the properties, events & styling along with their syntaxes that will be used in the code example. "
},
{
"code": null,
"e": 26839,
"s": 26763,
"text": "OrderList component: It is used to maintain the list of items and products."
},
{
"code": null,
"e": 26852,
"s": 26839,
"text": "Properties: "
},
{
"code": null,
"e": 26957,
"s": 26852,
"text": "value: It is an array of objects to reorder. It accepts the array data type & the default value is null."
},
{
"code": null,
"e": 27078,
"s": 26957,
"text": "selection: It is an array of objects to bind the selections. It accepts the array data type & the default value is null."
},
{
"code": null,
"e": 27173,
"s": 27078,
"text": "header: It is the text for the caption. It is of string data type & the default value is null."
},
{
"code": null,
"e": 27275,
"s": 27173,
"text": "style: It is an inline style of the component. It is of string data type & the default value is null."
},
{
"code": null,
"e": 27382,
"s": 27275,
"text": "styleClass: It is the style class of the component. It is of string data type & the default value is null."
},
{
"code": null,
"e": 27491,
"s": 27382,
"text": "listStyle: It is an inline style of the list element. It is of string data type & the default value is null."
},
{
"code": null,
"e": 27685,
"s": 27491,
"text": "filterBy: It is used to specify whether to display an input field to filter the items on keyup and decides which fields to search against. It is of string data type & the default value is null."
},
{
"code": null,
"e": 27810,
"s": 27685,
"text": "filterMatchMode: It is used to define how the items are filtered. It is of string data type & the default value is contains."
},
{
"code": null,
"e": 27934,
"s": 27810,
"text": "filterLocale: It is used to set the locale to use in filtering. It is of string data type & the default value is undefined."
},
{
"code": null,
"e": 28103,
"s": 27934,
"text": "metaKeySelection: It is used to specify whether metaKey needs to be pressed to select or discard the item. It accepts the boolean data type & the default value is true."
},
{
"code": null,
"e": 28244,
"s": 28103,
"text": "dragdrop: It is used to specify whether to enable drag-drop based reordering. It accepts the boolean data type & the default value is false."
},
{
"code": null,
"e": 28346,
"s": 28244,
"text": "filterPlaceHolder: It is the placeholder text. It is of string data type & the default value is null."
},
{
"code": null,
"e": 28488,
"s": 28346,
"text": "trackBy: It is the function to optimize the dom operations by delegating to ngForTrackBy. It is of function type & the default value is null."
},
{
"code": null,
"e": 28672,
"s": 28488,
"text": "controlsPosition: It is used to define the location of the buttons with respect to the list, valid values are “left” or “right”. It is of string data type & the default value is left."
},
{
"code": null,
"e": 28804,
"s": 28672,
"text": "ariaFilterLabel: It is used to define a string that labels the filter input. It is of string data type & the default value is null."
},
{
"code": null,
"e": 28812,
"s": 28804,
"text": "Events:"
},
{
"code": null,
"e": 28882,
"s": 28812,
"text": "onReorder: It is a callback that is fired when the list is reordered."
},
{
"code": null,
"e": 28952,
"s": 28882,
"text": "onSelectionChange: It is a callback to invoke when selection changes."
},
{
"code": null,
"e": 29021,
"s": 28952,
"text": "onFilterEvent: It is a callback that is fired when filtering occurs."
},
{
"code": null,
"e": 29032,
"s": 29023,
"text": "Styling:"
},
{
"code": null,
"e": 29072,
"s": 29032,
"text": "p-orderlist: It is a container element."
},
{
"code": null,
"e": 29114,
"s": 29072,
"text": "p-orderlist-list: It is a list container."
},
{
"code": null,
"e": 29151,
"s": 29114,
"text": "p-orderlist-item: It is a list item."
},
{
"code": null,
"e": 29203,
"s": 29151,
"text": "Creating Angular application & module installation:"
},
{
"code": null,
"e": 29270,
"s": 29203,
"text": "Step 1: Create an Angular application using the following command."
},
{
"code": null,
"e": 29285,
"s": 29270,
"text": "ng new appname"
},
{
"code": null,
"e": 29382,
"s": 29285,
"text": "Step 2: After creating your project folder i.e. appname, move to it using the following command."
},
{
"code": null,
"e": 29393,
"s": 29382,
"text": "cd appname"
},
{
"code": null,
"e": 29442,
"s": 29393,
"text": "Step 3: Install PrimeNG in your given directory."
},
{
"code": null,
"e": 29499,
"s": 29442,
"text": "npm install primeng --save\nnpm install primeicons --save"
},
{
"code": null,
"e": 29551,
"s": 29499,
"text": "Project Structure: It will look like the following:"
},
{
"code": null,
"e": 29641,
"s": 29551,
"text": "Example 1: This is the basic example that illustrates how to use the Orderlist component."
},
{
"code": null,
"e": 29660,
"s": 29641,
"text": "app.component.html"
},
{
"code": "<h2>GeeksforGeeks</h2><p-orderList [value]=\"product\" header=\"OrderList Component\"> <ng-template let-product pTemplate=\"item\"> <div class=\"product-item\"> <div class=\"product-list-detail\"> <h5 class=\"p-mb-2\">{{product}}</h5> <h6 class=\"p-mb-2\">{{gfg}}</h6> </div> </div> </ng-template></p-orderList>",
"e": 29990,
"s": 29660,
"text": null
},
{
"code": null,
"e": 30007,
"s": 29990,
"text": "app.component.ts"
},
{
"code": "import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent { product: string[] = ['Geek1', 'Geek2', 'Geek3', 'Geek4']; gfg: string[] = ['200'];}",
"e": 30239,
"s": 30007,
"text": null
},
{
"code": null,
"e": 30253,
"s": 30239,
"text": "app.module.ts"
},
{
"code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { OrderListModule } from 'primeng/orderlist'; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, OrderListModule], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {}",
"e": 30730,
"s": 30253,
"text": null
},
{
"code": null,
"e": 30739,
"s": 30730,
"text": "Output: "
},
{
"code": null,
"e": 30825,
"s": 30739,
"text": "Example 2: In this example, we will use dragdrop property in the OrderList Component."
},
{
"code": null,
"e": 30844,
"s": 30825,
"text": "app.component.html"
},
{
"code": "<h2>GeeksforGeeks</h2><p-orderList [value]=\"product\" header=\"OrderList Component\" dragdrop=\"true\"> <ng-template let-product pTemplate=\"item\"> <div class=\"product-item\"> <div class=\"product-list-detail\"> <h5 class=\"p-mb-2\">{{product}}</h5> <h6 class=\"p-mb-2\">{{gfg}}</h6> </div> </div> </ng-template></p-orderList>",
"e": 31198,
"s": 30844,
"text": null
},
{
"code": null,
"e": 31215,
"s": 31198,
"text": "app.component.ts"
},
{
"code": "import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent { product: string[] = ['Geek1', 'Geek2', 'Geek3', 'Geek4']; gfg: string[] = ['200'];}",
"e": 31447,
"s": 31215,
"text": null
},
{
"code": null,
"e": 31461,
"s": 31447,
"text": "app.module.ts"
},
{
"code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { OrderListModule } from 'primeng/orderlist'; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, OrderListModule], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {}",
"e": 31937,
"s": 31461,
"text": null
},
{
"code": null,
"e": 31945,
"s": 31937,
"text": "Output:"
},
{
"code": null,
"e": 32008,
"s": 31945,
"text": "Reference: https://primefaces.org/primeng/showcase/#/orderlist"
},
{
"code": null,
"e": 32024,
"s": 32008,
"text": "Angular-PrimeNG"
},
{
"code": null,
"e": 32034,
"s": 32024,
"text": "AngularJS"
},
{
"code": null,
"e": 32051,
"s": 32034,
"text": "Web Technologies"
},
{
"code": null,
"e": 32149,
"s": 32051,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32184,
"s": 32149,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 32219,
"s": 32184,
"text": "Angular PrimeNG Calendar Component"
},
{
"code": null,
"e": 32243,
"s": 32219,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 32296,
"s": 32243,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 32331,
"s": 32296,
"text": "Angular PrimeNG Messages Component"
},
{
"code": null,
"e": 32371,
"s": 32331,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 32404,
"s": 32371,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 32449,
"s": 32404,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 32492,
"s": 32449,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
General Tree (Each node can have arbitrary number of children) Level Order Traversal - GeeksforGeeks
|
28 Jun, 2021
Given a generic tree, perform a Level order traversal and print all of its nodesExamples:
Input : 10
/ / \ \
2 34 56 100
/ \ | / | \
77 88 1 7 8 9
Output : 10
2 34 56 100
77 88 1 7 8 9
Input : 1
/ / \ \
2 3 4 5
/ \ | / | \
6 7 8 9 10 11
Output : 1
2 3 4 5
6 7 8 9 10 11
The approach to this problem is similar to Level Order traversal in a binary tree. We Start with pushing root node in a queue and for each node we pop it, print it and push all its child in the queue.In case of a generic tree we store child nodes in a vector. Thus we put all elements of the vector in the queue.
C++
Java
Python3
C#
Javascript
// CPP program to do level order traversal// of a generic tree#include <bits/stdc++.h>using namespace std; // Represents a node of an n-ary treestruct Node{ int key; vector<Node *>child;}; // Utility function to create a new tree nodeNode *newNode(int key){ Node *temp = new Node; temp->key = key; return temp;} // Prints the n-ary tree level wisevoid LevelOrderTraversal(Node * root){ if (root==NULL) return; // Standard level order traversal code // using queue queue<Node *> q; // Create a queue q.push(root); // Enqueue root while (!q.empty()) { int n = q.size(); // If this node has children while (n > 0) { // Dequeue an item from queue and print it Node * p = q.front(); q.pop(); cout << p->key << " "; // Enqueue all children of the dequeued item for (int i=0; i<p->child.size(); i++) q.push(p->child[i]); n--; } cout << endl; // Print new line between two levels }} // Driver programint main(){ /* Let us create below tree * 10 * / / \ \ * 2 34 56 100 * / \ | / | \ * 77 88 1 7 8 9 */ Node *root = newNode(10); (root->child).push_back(newNode(2)); (root->child).push_back(newNode(34)); (root->child).push_back(newNode(56)); (root->child).push_back(newNode(100)); (root->child[0]->child).push_back(newNode(77)); (root->child[0]->child).push_back(newNode(88)); (root->child[2]->child).push_back(newNode(1)); (root->child[3]->child).push_back(newNode(7)); (root->child[3]->child).push_back(newNode(8)); (root->child[3]->child).push_back(newNode(9)); cout << "Level order traversal Before Mirroring\n"; LevelOrderTraversal(root); return 0;}
// Java program to do level order traversal// of a generic treeimport java.util.*; class GFG{ // Represents a node of an n-ary treestatic class Node{ int key; Vector<Node >child = new Vector<>();}; // Utility function to create a new tree nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = key; return temp;} // Prints the n-ary tree level wisestatic void LevelOrderTraversal(Node root){ if (root == null) return; // Standard level order traversal code // using queue Queue<Node > q = new LinkedList<>(); // Create a queue q.add(root); // Enqueue root while (!q.isEmpty()) { int n = q.size(); // If this node has children while (n > 0) { // Dequeue an item from queue // and print it Node p = q.peek(); q.remove(); System.out.print(p.key + " "); // Enqueue all children of // the dequeued item for (int i = 0; i < p.child.size(); i++) q.add(p.child.get(i)); n--; } // Print new line between two levels System.out.println(); }} // Driver Codepublic static void main(String[] args){ /* Let us create below tree * 10 * / / \ \ * 2 34 56 100 * / \ | / | \ * 77 88 1 7 8 9 */ Node root = newNode(10); (root.child).add(newNode(2)); (root.child).add(newNode(34)); (root.child).add(newNode(56)); (root.child).add(newNode(100)); (root.child.get(0).child).add(newNode(77)); (root.child.get(0).child).add(newNode(88)); (root.child.get(2).child).add(newNode(1)); (root.child.get(3).child).add(newNode(7)); (root.child.get(3).child).add(newNode(8)); (root.child.get(3).child).add(newNode(9)); System.out.println("Level order traversal " + "Before Mirroring "); LevelOrderTraversal(root);}} // This code is contributed by Rajput-Ji
# Python3 program to do level order traversal# of a generic tree # Represents a node of an n-ary treeclass Node: def __init__(self, key): self.key = key self.child = [] # Utility function to create a new tree nodedef newNode(key): temp = Node(key) return temp # Prints the n-ary tree level wisedef LevelOrderTraversal(root): if (root == None): return; # Standard level order traversal code # using queue q = [] # Create a queue q.append(root); # Enqueue root while (len(q) != 0): n = len(q); # If this node has children while (n > 0): # Dequeue an item from queue and print it p = q[0] q.pop(0); print(p.key, end=' ') # Enqueue all children of the dequeued item for i in range(len(p.child)): q.append(p.child[i]); n -= 1 print() # Print new line between two levels # Driver programif __name__=='__main__': ''' Let us create below tree 10 / / \ \ 2 34 56 100 / \ | / | \ 77 88 1 7 8 9 ''' root = newNode(10); (root.child).append(newNode(2)); (root.child).append(newNode(34)); (root.child).append(newNode(56)); (root.child).append(newNode(100)); (root.child[0].child).append(newNode(77)); (root.child[0].child).append(newNode(88)); (root.child[2].child).append(newNode(1)); (root.child[3].child).append(newNode(7)); (root.child[3].child).append(newNode(8)); (root.child[3].child).append(newNode(9)); print("Level order traversal Before Mirroring") LevelOrderTraversal(root); # This code is contributed by rutvik_56.
// C# program to do level order traversal// of a generic treeusing System;using System.Collections.Generic; class GFG{ // Represents a node of an n-ary treepublic class Node{ public int key; public List<Node >child = new List<Node>();}; // Utility function to create a new tree nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = key; return temp;} // Prints the n-ary tree level wisestatic void LevelOrderTraversal(Node root){ if (root == null) return; // Standard level order traversal code // using queue Queue<Node > q = new Queue<Node >(); // Create a queue q.Enqueue(root); // Enqueue root while (q.Count != 0) { int n = q.Count; // If this node has children while (n > 0) { // Dequeue an item from queue // and print it Node p = q.Peek(); q.Dequeue(); Console.Write(p.key + " "); // Enqueue all children of // the dequeued item for (int i = 0; i < p.child.Count; i++) q.Enqueue(p.child[i]); n--; } // Print new line between two levels Console.WriteLine(); }} // Driver Codepublic static void Main(String[] args){ /* Let us create below tree * 10 * / / \ \ * 2 34 56 100 * / \ | / | \ * 77 88 1 7 8 9 */ Node root = newNode(10); (root.child).Add(newNode(2)); (root.child).Add(newNode(34)); (root.child).Add(newNode(56)); (root.child).Add(newNode(100)); (root.child[0].child).Add(newNode(77)); (root.child[0].child).Add(newNode(88)); (root.child[2].child).Add(newNode(1)); (root.child[3].child).Add(newNode(7)); (root.child[3].child).Add(newNode(8)); (root.child[3].child).Add(newNode(9)); Console.WriteLine("Level order traversal " + "Before Mirroring "); LevelOrderTraversal(root);}} // This code is contributed by Rajput-Ji
<script> // JavaScript program to do level order traversal// of a generic tree // Represents a node of an n-ary treeclass Node{ constructor() { this.key = 0; this.child = []; }}; // Utility function to create a new tree nodefunction newNode(key){ var temp = new Node(); temp.key = key; return temp;} // Prints the n-ary tree level wisefunction LevelOrderTraversal(root){ if (root == null) return; // Standard level order traversal code // using queue var q = []; // Create a queue q.push(root); // push root while (q.length != 0) { var n = q.length; // If this node has children while (n > 0) { // Dequeue an item from queue // and print it var p = q[0]; q.shift(); document.write(p.key + " "); // push all children of // the dequeued item for (var i = 0; i < p.child.length; i++) q.push(p.child[i]); n--; } // Print new line between two levels document.write("<br>"); }} // Driver Code/* Let us create below tree* 10* / / \ \* 2 34 56 100* / \ | / | \* 77 88 1 7 8 9*/var root = newNode(10);(root.child).push(newNode(2));(root.child).push(newNode(34));(root.child).push(newNode(56));(root.child).push(newNode(100));(root.child[0].child).push(newNode(77));(root.child[0].child).push(newNode(88));(root.child[2].child).push(newNode(1));(root.child[3].child).push(newNode(7));(root.child[3].child).push(newNode(8));(root.child[3].child).push(newNode(9));document.write("Level order traversal " + "Before Mirroring <br>");LevelOrderTraversal(root); </script>
Output:
10
2 34 56 100
77 88 1 7 8 9
YouTubeGeeksforGeeks500K subscribersGeneral Tree Level Order Traversal | 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 / 5:09•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=VBJZBPWnpAc" 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 Raghav Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Rajput-Ji
rutvik_56
noob2000
cpp-queue
cpp-vector
n-ary-tree
tree-level-order
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Decision Tree
Binary Tree | Set 2 (Properties)
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Introduction to Tree Data Structure
Lowest Common Ancestor in a Binary Tree | Set 1
Expression Tree
Binary Tree (Array implementation)
BFS vs DFS for Binary Tree
Deletion in a Binary Tree
Insertion in a Binary Tree in level order
|
[
{
"code": null,
"e": 24984,
"s": 24956,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 25076,
"s": 24984,
"text": "Given a generic tree, perform a Level order traversal and print all of its nodesExamples: "
},
{
"code": null,
"e": 25476,
"s": 25076,
"text": "Input : 10\n / / \\ \\\n 2 34 56 100\n / \\ | / | \\\n 77 88 1 7 8 9\n\nOutput : 10\n 2 34 56 100\n 77 88 1 7 8 9\n\nInput : 1\n / / \\ \\\n 2 3 4 5\n / \\ | / | \\\n 6 7 8 9 10 11\nOutput : 1\n 2 3 4 5\n 6 7 8 9 10 11"
},
{
"code": null,
"e": 25793,
"s": 25478,
"text": "The approach to this problem is similar to Level Order traversal in a binary tree. We Start with pushing root node in a queue and for each node we pop it, print it and push all its child in the queue.In case of a generic tree we store child nodes in a vector. Thus we put all elements of the vector in the queue. "
},
{
"code": null,
"e": 25797,
"s": 25793,
"text": "C++"
},
{
"code": null,
"e": 25802,
"s": 25797,
"text": "Java"
},
{
"code": null,
"e": 25810,
"s": 25802,
"text": "Python3"
},
{
"code": null,
"e": 25813,
"s": 25810,
"text": "C#"
},
{
"code": null,
"e": 25824,
"s": 25813,
"text": "Javascript"
},
{
"code": "// CPP program to do level order traversal// of a generic tree#include <bits/stdc++.h>using namespace std; // Represents a node of an n-ary treestruct Node{ int key; vector<Node *>child;}; // Utility function to create a new tree nodeNode *newNode(int key){ Node *temp = new Node; temp->key = key; return temp;} // Prints the n-ary tree level wisevoid LevelOrderTraversal(Node * root){ if (root==NULL) return; // Standard level order traversal code // using queue queue<Node *> q; // Create a queue q.push(root); // Enqueue root while (!q.empty()) { int n = q.size(); // If this node has children while (n > 0) { // Dequeue an item from queue and print it Node * p = q.front(); q.pop(); cout << p->key << \" \"; // Enqueue all children of the dequeued item for (int i=0; i<p->child.size(); i++) q.push(p->child[i]); n--; } cout << endl; // Print new line between two levels }} // Driver programint main(){ /* Let us create below tree * 10 * / / \\ \\ * 2 34 56 100 * / \\ | / | \\ * 77 88 1 7 8 9 */ Node *root = newNode(10); (root->child).push_back(newNode(2)); (root->child).push_back(newNode(34)); (root->child).push_back(newNode(56)); (root->child).push_back(newNode(100)); (root->child[0]->child).push_back(newNode(77)); (root->child[0]->child).push_back(newNode(88)); (root->child[2]->child).push_back(newNode(1)); (root->child[3]->child).push_back(newNode(7)); (root->child[3]->child).push_back(newNode(8)); (root->child[3]->child).push_back(newNode(9)); cout << \"Level order traversal Before Mirroring\\n\"; LevelOrderTraversal(root); return 0;}",
"e": 27705,
"s": 25824,
"text": null
},
{
"code": "// Java program to do level order traversal// of a generic treeimport java.util.*; class GFG{ // Represents a node of an n-ary treestatic class Node{ int key; Vector<Node >child = new Vector<>();}; // Utility function to create a new tree nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = key; return temp;} // Prints the n-ary tree level wisestatic void LevelOrderTraversal(Node root){ if (root == null) return; // Standard level order traversal code // using queue Queue<Node > q = new LinkedList<>(); // Create a queue q.add(root); // Enqueue root while (!q.isEmpty()) { int n = q.size(); // If this node has children while (n > 0) { // Dequeue an item from queue // and print it Node p = q.peek(); q.remove(); System.out.print(p.key + \" \"); // Enqueue all children of // the dequeued item for (int i = 0; i < p.child.size(); i++) q.add(p.child.get(i)); n--; } // Print new line between two levels System.out.println(); }} // Driver Codepublic static void main(String[] args){ /* Let us create below tree * 10 * / / \\ \\ * 2 34 56 100 * / \\ | / | \\ * 77 88 1 7 8 9 */ Node root = newNode(10); (root.child).add(newNode(2)); (root.child).add(newNode(34)); (root.child).add(newNode(56)); (root.child).add(newNode(100)); (root.child.get(0).child).add(newNode(77)); (root.child.get(0).child).add(newNode(88)); (root.child.get(2).child).add(newNode(1)); (root.child.get(3).child).add(newNode(7)); (root.child.get(3).child).add(newNode(8)); (root.child.get(3).child).add(newNode(9)); System.out.println(\"Level order traversal \" + \"Before Mirroring \"); LevelOrderTraversal(root);}} // This code is contributed by Rajput-Ji",
"e": 29695,
"s": 27705,
"text": null
},
{
"code": "# Python3 program to do level order traversal# of a generic tree # Represents a node of an n-ary treeclass Node: def __init__(self, key): self.key = key self.child = [] # Utility function to create a new tree nodedef newNode(key): temp = Node(key) return temp # Prints the n-ary tree level wisedef LevelOrderTraversal(root): if (root == None): return; # Standard level order traversal code # using queue q = [] # Create a queue q.append(root); # Enqueue root while (len(q) != 0): n = len(q); # If this node has children while (n > 0): # Dequeue an item from queue and print it p = q[0] q.pop(0); print(p.key, end=' ') # Enqueue all children of the dequeued item for i in range(len(p.child)): q.append(p.child[i]); n -= 1 print() # Print new line between two levels # Driver programif __name__=='__main__': ''' Let us create below tree 10 / / \\ \\ 2 34 56 100 / \\ | / | \\ 77 88 1 7 8 9 ''' root = newNode(10); (root.child).append(newNode(2)); (root.child).append(newNode(34)); (root.child).append(newNode(56)); (root.child).append(newNode(100)); (root.child[0].child).append(newNode(77)); (root.child[0].child).append(newNode(88)); (root.child[2].child).append(newNode(1)); (root.child[3].child).append(newNode(7)); (root.child[3].child).append(newNode(8)); (root.child[3].child).append(newNode(9)); print(\"Level order traversal Before Mirroring\") LevelOrderTraversal(root); # This code is contributed by rutvik_56.",
"e": 31499,
"s": 29695,
"text": null
},
{
"code": "// C# program to do level order traversal// of a generic treeusing System;using System.Collections.Generic; class GFG{ // Represents a node of an n-ary treepublic class Node{ public int key; public List<Node >child = new List<Node>();}; // Utility function to create a new tree nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = key; return temp;} // Prints the n-ary tree level wisestatic void LevelOrderTraversal(Node root){ if (root == null) return; // Standard level order traversal code // using queue Queue<Node > q = new Queue<Node >(); // Create a queue q.Enqueue(root); // Enqueue root while (q.Count != 0) { int n = q.Count; // If this node has children while (n > 0) { // Dequeue an item from queue // and print it Node p = q.Peek(); q.Dequeue(); Console.Write(p.key + \" \"); // Enqueue all children of // the dequeued item for (int i = 0; i < p.child.Count; i++) q.Enqueue(p.child[i]); n--; } // Print new line between two levels Console.WriteLine(); }} // Driver Codepublic static void Main(String[] args){ /* Let us create below tree * 10 * / / \\ \\ * 2 34 56 100 * / \\ | / | \\ * 77 88 1 7 8 9 */ Node root = newNode(10); (root.child).Add(newNode(2)); (root.child).Add(newNode(34)); (root.child).Add(newNode(56)); (root.child).Add(newNode(100)); (root.child[0].child).Add(newNode(77)); (root.child[0].child).Add(newNode(88)); (root.child[2].child).Add(newNode(1)); (root.child[3].child).Add(newNode(7)); (root.child[3].child).Add(newNode(8)); (root.child[3].child).Add(newNode(9)); Console.WriteLine(\"Level order traversal \" + \"Before Mirroring \"); LevelOrderTraversal(root);}} // This code is contributed by Rajput-Ji",
"e": 33501,
"s": 31499,
"text": null
},
{
"code": "<script> // JavaScript program to do level order traversal// of a generic tree // Represents a node of an n-ary treeclass Node{ constructor() { this.key = 0; this.child = []; }}; // Utility function to create a new tree nodefunction newNode(key){ var temp = new Node(); temp.key = key; return temp;} // Prints the n-ary tree level wisefunction LevelOrderTraversal(root){ if (root == null) return; // Standard level order traversal code // using queue var q = []; // Create a queue q.push(root); // push root while (q.length != 0) { var n = q.length; // If this node has children while (n > 0) { // Dequeue an item from queue // and print it var p = q[0]; q.shift(); document.write(p.key + \" \"); // push all children of // the dequeued item for (var i = 0; i < p.child.length; i++) q.push(p.child[i]); n--; } // Print new line between two levels document.write(\"<br>\"); }} // Driver Code/* Let us create below tree* 10* / / \\ \\* 2 34 56 100* / \\ | / | \\* 77 88 1 7 8 9*/var root = newNode(10);(root.child).push(newNode(2));(root.child).push(newNode(34));(root.child).push(newNode(56));(root.child).push(newNode(100));(root.child[0].child).push(newNode(77));(root.child[0].child).push(newNode(88));(root.child[2].child).push(newNode(1));(root.child[3].child).push(newNode(7));(root.child[3].child).push(newNode(8));(root.child[3].child).push(newNode(9));document.write(\"Level order traversal \" + \"Before Mirroring <br>\");LevelOrderTraversal(root); </script>",
"e": 35259,
"s": 33501,
"text": null
},
{
"code": null,
"e": 35269,
"s": 35259,
"text": "Output: "
},
{
"code": null,
"e": 35300,
"s": 35269,
"text": "10 \n2 34 56 100 \n77 88 1 7 8 9"
},
{
"code": null,
"e": 36135,
"s": 35302,
"text": "YouTubeGeeksforGeeks500K subscribersGeneral Tree Level Order Traversal | 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 / 5:09•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=VBJZBPWnpAc\" 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": 36557,
"s": 36135,
"text": "This article is contributed by Raghav Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 36567,
"s": 36557,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 36577,
"s": 36567,
"text": "rutvik_56"
},
{
"code": null,
"e": 36586,
"s": 36577,
"text": "noob2000"
},
{
"code": null,
"e": 36596,
"s": 36586,
"text": "cpp-queue"
},
{
"code": null,
"e": 36607,
"s": 36596,
"text": "cpp-vector"
},
{
"code": null,
"e": 36618,
"s": 36607,
"text": "n-ary-tree"
},
{
"code": null,
"e": 36635,
"s": 36618,
"text": "tree-level-order"
},
{
"code": null,
"e": 36640,
"s": 36635,
"text": "Tree"
},
{
"code": null,
"e": 36645,
"s": 36640,
"text": "Tree"
},
{
"code": null,
"e": 36743,
"s": 36645,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36752,
"s": 36743,
"text": "Comments"
},
{
"code": null,
"e": 36765,
"s": 36752,
"text": "Old Comments"
},
{
"code": null,
"e": 36779,
"s": 36765,
"text": "Decision Tree"
},
{
"code": null,
"e": 36812,
"s": 36779,
"text": "Binary Tree | Set 2 (Properties)"
},
{
"code": null,
"e": 36895,
"s": 36812,
"text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree"
},
{
"code": null,
"e": 36931,
"s": 36895,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 36979,
"s": 36931,
"text": "Lowest Common Ancestor in a Binary Tree | Set 1"
},
{
"code": null,
"e": 36995,
"s": 36979,
"text": "Expression Tree"
},
{
"code": null,
"e": 37030,
"s": 36995,
"text": "Binary Tree (Array implementation)"
},
{
"code": null,
"e": 37057,
"s": 37030,
"text": "BFS vs DFS for Binary Tree"
},
{
"code": null,
"e": 37083,
"s": 37057,
"text": "Deletion in a Binary Tree"
}
] |
How to use Boto3 to get the details of a connection from AWS Glue Data catalog?
|
Problem Statement − Use boto3 library in Python to get details of a connection present in AWS Glue Data catalog.
Example − Get the details of a connection definition, ‘aurora-test’.
Step 1 − Import boto3 and botocore exceptions to handle exceptions.
Step 2 − Pass the parameter connection_name whose definition needs to check.
Step 3 − Create an AWS session using boto3 library. Make sure region_name is mentioned in default profile. If it is not mentioned, then explicitly pass the region_name while creating the session.
Step 4 − Create an AWS client for glue.
Step 5 − Call get_connection function and pass the connection_name as Name parameter.
Step 6 − It will fetch the details of the connection definition from AWS Glue Data Catalog.
Step 7 − Handle the generic exception if something went wrong while checking the job.
Use the following code to get definition of a connection in AWS Glue Data catalog −
import boto3
from botocore.exceptions import ClientError
def get_details_of_a_connection(connection_name):
session = boto3.session.Session()
glue_client = session.client('glue')
try:
response = glue_client.get_connection(Name= connection_name)
return response
except ClientError as e:
raise Exception("boto3 client error in get_details_of_a_connection: " + e.__str__())
except Exception as e:
raise Exception("Unexpected error in get_details_of_a_connection: " + e.__str__())
print(get_details_of_a_connection("aurora-poc"))
{'Connection': {'Name': 'aurora-poc', 'ConnectionType': 'JDBC',
'ConnectionProperties': {'JDBC_CONNECTION_URL': 'jdbc:postgresql://abcpostgresql-cluster.cluster-abc.us-east-1.rds.amazonaws.com:0132/abc,
'JDBC_ENFORCE_SSL': 'false', 'PASSWORD': '******', 'USERNAME':
'abc***'}, 'PhysicalConnectionRequirements': {'SubnetId': 'subnet351*****', 'SecurityGroupIdList': ['sg-caa******', 'sg-*************'],
'AvailabilityZone': 'us-east-1c'}, 'CreationTime':
datetime.datetime(2020, 11, 18, 12, 38, 29, 625000, tzinfo=tzlocal()),
'LastUpdatedTime': datetime.datetime(2020, 11, 18, 12, 51, 16, 59000,
tzinfo=tzlocal())}, 'ResponseMetadata': {'RequestId': '6f13524b-4175-
454b-bc60-c7f408967098', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date':
'Sun, 28 Feb 2021 11:19:18 GMT', 'content-type': 'application/x-amzjson-1.1', 'content-length': '523', 'connection': 'keep-alive', 'x-amznrequestid': '6f13524b-*****************7098'}, 'RetryAttempts': 0}}
|
[
{
"code": null,
"e": 1175,
"s": 1062,
"text": "Problem Statement − Use boto3 library in Python to get details of a connection present in AWS Glue Data catalog."
},
{
"code": null,
"e": 1244,
"s": 1175,
"text": "Example − Get the details of a connection definition, ‘aurora-test’."
},
{
"code": null,
"e": 1312,
"s": 1244,
"text": "Step 1 − Import boto3 and botocore exceptions to handle exceptions."
},
{
"code": null,
"e": 1389,
"s": 1312,
"text": "Step 2 − Pass the parameter connection_name whose definition needs to check."
},
{
"code": null,
"e": 1585,
"s": 1389,
"text": "Step 3 − Create an AWS session using boto3 library. Make sure region_name is mentioned in default profile. If it is not mentioned, then explicitly pass the region_name while creating the session."
},
{
"code": null,
"e": 1625,
"s": 1585,
"text": "Step 4 − Create an AWS client for glue."
},
{
"code": null,
"e": 1711,
"s": 1625,
"text": "Step 5 − Call get_connection function and pass the connection_name as Name parameter."
},
{
"code": null,
"e": 1803,
"s": 1711,
"text": "Step 6 − It will fetch the details of the connection definition from AWS Glue Data Catalog."
},
{
"code": null,
"e": 1889,
"s": 1803,
"text": "Step 7 − Handle the generic exception if something went wrong while checking the job."
},
{
"code": null,
"e": 1973,
"s": 1889,
"text": "Use the following code to get definition of a connection in AWS Glue Data catalog −"
},
{
"code": null,
"e": 2538,
"s": 1973,
"text": "import boto3\nfrom botocore.exceptions import ClientError\n\ndef get_details_of_a_connection(connection_name):\n session = boto3.session.Session()\n glue_client = session.client('glue')\n try:\n response = glue_client.get_connection(Name= connection_name)\n return response\n except ClientError as e:\n raise Exception(\"boto3 client error in get_details_of_a_connection: \" + e.__str__())\n except Exception as e:\n raise Exception(\"Unexpected error in get_details_of_a_connection: \" + e.__str__())\nprint(get_details_of_a_connection(\"aurora-poc\"))"
},
{
"code": null,
"e": 3481,
"s": 2538,
"text": "{'Connection': {'Name': 'aurora-poc', 'ConnectionType': 'JDBC',\n'ConnectionProperties': {'JDBC_CONNECTION_URL': 'jdbc:postgresql://abcpostgresql-cluster.cluster-abc.us-east-1.rds.amazonaws.com:0132/abc,\n'JDBC_ENFORCE_SSL': 'false', 'PASSWORD': '******', 'USERNAME':\n'abc***'}, 'PhysicalConnectionRequirements': {'SubnetId': 'subnet351*****', 'SecurityGroupIdList': ['sg-caa******', 'sg-*************'],\n'AvailabilityZone': 'us-east-1c'}, 'CreationTime':\ndatetime.datetime(2020, 11, 18, 12, 38, 29, 625000, tzinfo=tzlocal()),\n'LastUpdatedTime': datetime.datetime(2020, 11, 18, 12, 51, 16, 59000,\ntzinfo=tzlocal())}, 'ResponseMetadata': {'RequestId': '6f13524b-4175-\n454b-bc60-c7f408967098', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date':\n'Sun, 28 Feb 2021 11:19:18 GMT', 'content-type': 'application/x-amzjson-1.1', 'content-length': '523', 'connection': 'keep-alive', 'x-amznrequestid': '6f13524b-*****************7098'}, 'RetryAttempts': 0}}"
}
] |
Number of ways to reach Nth floor by taking at-most K leaps - GeeksforGeeks
|
31 May, 2021
Given N number of stairs. Also given the number of steps that one can cover at most in one leap (K). The task is to find the number of possible ways one (only consider combinations) can climb to the top of the building in K leaps or less from the ground floor.Examples:
Input: N = 5, K = 3 Output: 5 To reach stair no-5 we can choose following combination of leaps: 1 1 1 1 1 1 1 1 2 1 2 2 1 1 3 2 3 Therefore the answer is 5.Input: N = 29, K = 5 Output: 603
Let combo[i] be the number of ways to reach the i-th floor. Hence the number of ways to reach combo[i] from combo[j] by taking a leap of i-j will be combo[i] += combo[j]. So iterate for all possible leaps, and for each possible leaps keep adding the possible combinations to the combo array. The final answer will be stored in combo[N]. Below is the implementation of the above approach.
C++
Java
Python 3
C#
PHP
Javascript
// C++ program to reach N-th stair// by taking a maximum of K leap#include <bits/stdc++.h> using namespace std; int solve(int N, int K){ // elements of combo[] stores the no of // possible ways to reach it by all // combinations of k leaps or less int combo[N + 1] = { 0 }; // assuming leap 0 exist and assigning // its value to 1 for calculation combo[0] = 1; // loop to iterate over all // possible leaps upto k; for (int i = 1; i <= K; i++) { // in this loop we count all possible // leaps to reach the jth stair with // the help of ith leap or less for (int j = 0; j <= N; j++) { // if the leap is not more than the i-j if (j >= i) { // calculate the value and // store in combo[j] // to reuse it for next leap // calculation for the jth stair combo[j] += combo[j - i]; } } } // returns the no of possible number // of leaps to reach the top of // building of n stairs return combo[N];} // Driver Codeint main(){ // N i the no of total stairs // K is the value of the greatest leap int N = 29; int K = 5; cout << solve(N, K); solve(N, K); return 0;}
// Java program to reach N-th// stair by taking a maximum// of K leapclass GFG{static int solve(int N, int K){ // elements of combo[] stores // the no. of possible ways // to reach it by all combinations // of k leaps or less int[] combo; combo = new int[50]; // assuming leap 0 exist // and assigning its value // to 1 for calculation combo[0] = 1; // loop to iterate over all // possible leaps upto k; for (int i = 1; i <= K; i++) { // in this loop we count all // possible leaps to reach // the jth stair with the // help of ith leap or less for (int j = 0; j <= N; j++) { // if the leap is not // more than the i-j if (j >= i) { // calculate the value and // store in combo[j] to // reuse it for next leap // calculation for the // jth stair combo[j] += combo[j - i]; } } } // returns the no of possible // number of leaps to reach // the top of building of // n stairs return combo[N];} // Driver Codepublic static void main(String args[]){ // N i the no of total stairs // K is the value of the // greatest leap int N = 29; int K = 5; System.out.println(solve(N, K)); solve(N, K);}} // This code is contributed// by ankita_saini
# Python3 program to reach N-th stair# by taking a maximum of K leap def solve(N, K) : # elements of combo[] stores the no of # possible ways to reach it by all # combinations of k leaps or less combo = [0] * (N + 1) # assuming leap 0 exist and assigning # its value to 1 for calculation combo[0] = 1 # loop to iterate over all # possible leaps upto k; for i in range(1, K + 1) : # in this loop we count all possible # leaps to reach the jth stair with # the help of ith leap or less for j in range(0, N + 1) : # if the leap is not more than the i-j if j >= i : # calculate the value and # store in combo[j] # to reuse it for next leap # calculation for the jth stair combo[j] += combo[j - i] # returns the no of possible number # of leaps to reach the top of # building of n stairs return combo[N] # Driver Codeif __name__ == "__main__" : # N i the no of total stairs # K is the value of the greatest leap N, K = 29, 5 print(solve(N, K)) # This code is contributed by ANKITRAI1
// C# program to reach N-th// stair by taking a maximum// of K leapusing System; class GFG{static int solve(int N, int K){ // elements of combo[] stores // the no. of possible ways // to reach it by all combinations // of k leaps or less int[] combo; combo = new int[50]; // assuming leap 0 exist // and assigning its value // to 1 for calculation combo[0] = 1; // loop to iterate over all // possible leaps upto k; for (int i = 1; i <= K; i++) { // in this loop we count all // possible leaps to reach // the jth stair with the // help of ith leap or less for (int j = 0; j <= N; j++) { // if the leap is not // more than the i-j if (j >= i) { // calculate the value and // store in combo[j] to // reuse it for next leap // calculation for the // jth stair combo[j] += combo[j - i]; } } } // returns the no of possible // number of leaps to reach // the top of building of // n stairs return combo[N];} // Driver Codepublic static void Main(){ // N i the no of total stairs // K is the value of the // greatest leap int N = 29; int K = 5; Console.WriteLine(solve(N, K)); solve(N, K);}} // This code is contributed// by Akanksha Rai(Abby_akku)
<?phperror_reporting(0);// PHP program to reach N-th// stair by taking a maximum// of K leapfunction solve($N, $K){ // elements of combo[] stores // the no of possible ways to // reach it by all combinations // of k leaps or less $combo[$N + 1] = array(); // assuming leap 0 exist and // assigning its value to 1 // for calculation $combo[0] = 1; // loop to iterate over all // possible leaps upto k; for ($i = 1; $i <= $K; $i++) { // in this loop we count // all possible leaps to // reach the jth stair with // the help of ith leap or less for ($j = 0; $j <= $N; $j++) { // if the leap is not // more than the i-j if ($j >= $i) { // calculate the value and // store in combo[j] // to reuse it for next leap // calculation for the jth stair $combo[$j] += $combo[$j - $i]; } } } // returns the no of possible // number of leaps to reach // the top of building of n stairs return $combo[$N];} // Driver Code // N i the no of total stairs// K is the value of the greatest leap$N = 29;$K = 5; echo solve($N, $K); solve($N, $K); // This code is contributed// by Akanksha Rai(Abby_akku)?>
<script> // Javascript program to reach N-th // stair by taking a maximum // of K leap function solve(N, K) { // elements of combo[] stores // the no. of possible ways // to reach it by all combinations // of k leaps or less let combo = new Array(50); combo.fill(0); // assuming leap 0 exist // and assigning its value // to 1 for calculation combo[0] = 1; // loop to iterate over all // possible leaps upto k; for (let i = 1; i <= K; i++) { // in this loop we count all // possible leaps to reach // the jth stair with the // help of ith leap or less for (let j = 0; j <= N; j++) { // if the leap is not // more than the i-j if (j >= i) { // calculate the value and // store in combo[j] to // reuse it for next leap // calculation for the // jth stair combo[j] += combo[j - i]; } } } // returns the no of possible // number of leaps to reach // the top of building of // n stairs return combo[N]; } // N i the no of total stairs // K is the value of the // greatest leap let N = 29; let K = 5; document.write(solve(N, K)); solve(N, K); // This code is contributed by decode2207.</script>
603
Time Complexity: O(N*K) Auxiliary Space: O(N)
ankita_saini
Akanksha_Rai
ankthon
decode2207
Algorithms-Dynamic Programming
Combinatorial
Dynamic Programming
Dynamic Programming
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Find the Number of Permutations that satisfy the given condition in an array
Split array into subarrays at minimum cost by minimizing count of repeating elements in each subarray
Ways to sum to N using Natural Numbers up to K with repetitions allowed
Number of Simple Graph with N Vertices and M Edges
Largest substring with same Characters
0-1 Knapsack Problem | DP-10
Program for Fibonacci numbers
Largest Sum Contiguous Subarray
Longest Common Subsequence | DP-4
Longest Increasing Subsequence | DP-3
|
[
{
"code": null,
"e": 25085,
"s": 25057,
"text": "\n31 May, 2021"
},
{
"code": null,
"e": 25357,
"s": 25085,
"text": "Given N number of stairs. Also given the number of steps that one can cover at most in one leap (K). The task is to find the number of possible ways one (only consider combinations) can climb to the top of the building in K leaps or less from the ground floor.Examples: "
},
{
"code": null,
"e": 25548,
"s": 25357,
"text": "Input: N = 5, K = 3 Output: 5 To reach stair no-5 we can choose following combination of leaps: 1 1 1 1 1 1 1 1 2 1 2 2 1 1 3 2 3 Therefore the answer is 5.Input: N = 29, K = 5 Output: 603 "
},
{
"code": null,
"e": 25940,
"s": 25550,
"text": "Let combo[i] be the number of ways to reach the i-th floor. Hence the number of ways to reach combo[i] from combo[j] by taking a leap of i-j will be combo[i] += combo[j]. So iterate for all possible leaps, and for each possible leaps keep adding the possible combinations to the combo array. The final answer will be stored in combo[N]. Below is the implementation of the above approach. "
},
{
"code": null,
"e": 25944,
"s": 25940,
"text": "C++"
},
{
"code": null,
"e": 25949,
"s": 25944,
"text": "Java"
},
{
"code": null,
"e": 25958,
"s": 25949,
"text": "Python 3"
},
{
"code": null,
"e": 25961,
"s": 25958,
"text": "C#"
},
{
"code": null,
"e": 25965,
"s": 25961,
"text": "PHP"
},
{
"code": null,
"e": 25976,
"s": 25965,
"text": "Javascript"
},
{
"code": "// C++ program to reach N-th stair// by taking a maximum of K leap#include <bits/stdc++.h> using namespace std; int solve(int N, int K){ // elements of combo[] stores the no of // possible ways to reach it by all // combinations of k leaps or less int combo[N + 1] = { 0 }; // assuming leap 0 exist and assigning // its value to 1 for calculation combo[0] = 1; // loop to iterate over all // possible leaps upto k; for (int i = 1; i <= K; i++) { // in this loop we count all possible // leaps to reach the jth stair with // the help of ith leap or less for (int j = 0; j <= N; j++) { // if the leap is not more than the i-j if (j >= i) { // calculate the value and // store in combo[j] // to reuse it for next leap // calculation for the jth stair combo[j] += combo[j - i]; } } } // returns the no of possible number // of leaps to reach the top of // building of n stairs return combo[N];} // Driver Codeint main(){ // N i the no of total stairs // K is the value of the greatest leap int N = 29; int K = 5; cout << solve(N, K); solve(N, K); return 0;}",
"e": 27249,
"s": 25976,
"text": null
},
{
"code": "// Java program to reach N-th// stair by taking a maximum// of K leapclass GFG{static int solve(int N, int K){ // elements of combo[] stores // the no. of possible ways // to reach it by all combinations // of k leaps or less int[] combo; combo = new int[50]; // assuming leap 0 exist // and assigning its value // to 1 for calculation combo[0] = 1; // loop to iterate over all // possible leaps upto k; for (int i = 1; i <= K; i++) { // in this loop we count all // possible leaps to reach // the jth stair with the // help of ith leap or less for (int j = 0; j <= N; j++) { // if the leap is not // more than the i-j if (j >= i) { // calculate the value and // store in combo[j] to // reuse it for next leap // calculation for the // jth stair combo[j] += combo[j - i]; } } } // returns the no of possible // number of leaps to reach // the top of building of // n stairs return combo[N];} // Driver Codepublic static void main(String args[]){ // N i the no of total stairs // K is the value of the // greatest leap int N = 29; int K = 5; System.out.println(solve(N, K)); solve(N, K);}} // This code is contributed// by ankita_saini",
"e": 28668,
"s": 27249,
"text": null
},
{
"code": "# Python3 program to reach N-th stair# by taking a maximum of K leap def solve(N, K) : # elements of combo[] stores the no of # possible ways to reach it by all # combinations of k leaps or less combo = [0] * (N + 1) # assuming leap 0 exist and assigning # its value to 1 for calculation combo[0] = 1 # loop to iterate over all # possible leaps upto k; for i in range(1, K + 1) : # in this loop we count all possible # leaps to reach the jth stair with # the help of ith leap or less for j in range(0, N + 1) : # if the leap is not more than the i-j if j >= i : # calculate the value and # store in combo[j] # to reuse it for next leap # calculation for the jth stair combo[j] += combo[j - i] # returns the no of possible number # of leaps to reach the top of # building of n stairs return combo[N] # Driver Codeif __name__ == \"__main__\" : # N i the no of total stairs # K is the value of the greatest leap N, K = 29, 5 print(solve(N, K)) # This code is contributed by ANKITRAI1",
"e": 29854,
"s": 28668,
"text": null
},
{
"code": "// C# program to reach N-th// stair by taking a maximum// of K leapusing System; class GFG{static int solve(int N, int K){ // elements of combo[] stores // the no. of possible ways // to reach it by all combinations // of k leaps or less int[] combo; combo = new int[50]; // assuming leap 0 exist // and assigning its value // to 1 for calculation combo[0] = 1; // loop to iterate over all // possible leaps upto k; for (int i = 1; i <= K; i++) { // in this loop we count all // possible leaps to reach // the jth stair with the // help of ith leap or less for (int j = 0; j <= N; j++) { // if the leap is not // more than the i-j if (j >= i) { // calculate the value and // store in combo[j] to // reuse it for next leap // calculation for the // jth stair combo[j] += combo[j - i]; } } } // returns the no of possible // number of leaps to reach // the top of building of // n stairs return combo[N];} // Driver Codepublic static void Main(){ // N i the no of total stairs // K is the value of the // greatest leap int N = 29; int K = 5; Console.WriteLine(solve(N, K)); solve(N, K);}} // This code is contributed// by Akanksha Rai(Abby_akku)",
"e": 31281,
"s": 29854,
"text": null
},
{
"code": "<?phperror_reporting(0);// PHP program to reach N-th// stair by taking a maximum// of K leapfunction solve($N, $K){ // elements of combo[] stores // the no of possible ways to // reach it by all combinations // of k leaps or less $combo[$N + 1] = array(); // assuming leap 0 exist and // assigning its value to 1 // for calculation $combo[0] = 1; // loop to iterate over all // possible leaps upto k; for ($i = 1; $i <= $K; $i++) { // in this loop we count // all possible leaps to // reach the jth stair with // the help of ith leap or less for ($j = 0; $j <= $N; $j++) { // if the leap is not // more than the i-j if ($j >= $i) { // calculate the value and // store in combo[j] // to reuse it for next leap // calculation for the jth stair $combo[$j] += $combo[$j - $i]; } } } // returns the no of possible // number of leaps to reach // the top of building of n stairs return $combo[$N];} // Driver Code // N i the no of total stairs// K is the value of the greatest leap$N = 29;$K = 5; echo solve($N, $K); solve($N, $K); // This code is contributed// by Akanksha Rai(Abby_akku)?>",
"e": 32608,
"s": 31281,
"text": null
},
{
"code": "<script> // Javascript program to reach N-th // stair by taking a maximum // of K leap function solve(N, K) { // elements of combo[] stores // the no. of possible ways // to reach it by all combinations // of k leaps or less let combo = new Array(50); combo.fill(0); // assuming leap 0 exist // and assigning its value // to 1 for calculation combo[0] = 1; // loop to iterate over all // possible leaps upto k; for (let i = 1; i <= K; i++) { // in this loop we count all // possible leaps to reach // the jth stair with the // help of ith leap or less for (let j = 0; j <= N; j++) { // if the leap is not // more than the i-j if (j >= i) { // calculate the value and // store in combo[j] to // reuse it for next leap // calculation for the // jth stair combo[j] += combo[j - i]; } } } // returns the no of possible // number of leaps to reach // the top of building of // n stairs return combo[N]; } // N i the no of total stairs // K is the value of the // greatest leap let N = 29; let K = 5; document.write(solve(N, K)); solve(N, K); // This code is contributed by decode2207.</script>",
"e": 34170,
"s": 32608,
"text": null
},
{
"code": null,
"e": 34174,
"s": 34170,
"text": "603"
},
{
"code": null,
"e": 34223,
"s": 34176,
"text": "Time Complexity: O(N*K) Auxiliary Space: O(N) "
},
{
"code": null,
"e": 34236,
"s": 34223,
"text": "ankita_saini"
},
{
"code": null,
"e": 34249,
"s": 34236,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 34257,
"s": 34249,
"text": "ankthon"
},
{
"code": null,
"e": 34268,
"s": 34257,
"text": "decode2207"
},
{
"code": null,
"e": 34299,
"s": 34268,
"text": "Algorithms-Dynamic Programming"
},
{
"code": null,
"e": 34313,
"s": 34299,
"text": "Combinatorial"
},
{
"code": null,
"e": 34333,
"s": 34313,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 34353,
"s": 34333,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 34367,
"s": 34353,
"text": "Combinatorial"
},
{
"code": null,
"e": 34465,
"s": 34367,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34474,
"s": 34465,
"text": "Comments"
},
{
"code": null,
"e": 34487,
"s": 34474,
"text": "Old Comments"
},
{
"code": null,
"e": 34564,
"s": 34487,
"text": "Find the Number of Permutations that satisfy the given condition in an array"
},
{
"code": null,
"e": 34666,
"s": 34564,
"text": "Split array into subarrays at minimum cost by minimizing count of repeating elements in each subarray"
},
{
"code": null,
"e": 34738,
"s": 34666,
"text": "Ways to sum to N using Natural Numbers up to K with repetitions allowed"
},
{
"code": null,
"e": 34789,
"s": 34738,
"text": "Number of Simple Graph with N Vertices and M Edges"
},
{
"code": null,
"e": 34828,
"s": 34789,
"text": "Largest substring with same Characters"
},
{
"code": null,
"e": 34857,
"s": 34828,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 34887,
"s": 34857,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 34919,
"s": 34887,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 34953,
"s": 34919,
"text": "Longest Common Subsequence | DP-4"
}
] |
Types of Statements in JDBC
|
09 Jul, 2021
The statement interface is used to create SQL basic statements in Java it provides methods to execute queries with the database. There are different types of statements that are used in JDBC as follows:
Create Statement
Prepared Statement
Callable Statement
1. Create a Statement: From the connection interface, you can create the object for this interface. It is generally used for general–purpose access to databases and is useful while using static SQL statements at runtime.
Syntax:
Statement statement = connection.createStatement();
Implementation: Once the Statement object is created, there are three ways to execute it.
boolean execute(String SQL): If the ResultSet object is retrieved, then it returns true else false is returned. Is used to execute SQL DDL statements or for dynamic SQL.
int executeUpdate(String SQL): Returns number of rows that are affected by the execution of the statement, used when you need a number for INSERT, DELETE or UPDATE statements.
ResultSet executeQuery(String SQL): Returns a ResultSet object. Used similarly as SELECT is used in SQL.
Example:
Java
// Java Program illustrating Create Statement in JDBC // Importing Database(SQL) classesimport java.sql.*; // Classclass GFG { // Main driver method public static void main(String[] args) { // Try block to check if any exceptions occur try { // Step 2: Loading and registering drivers // Loading driver using forName() method Class.forName("com.mysql.cj.jdbc.Driver"); // Registering driver using DriverManager Connection con = DriverManager.getConnection( "jdbc:mysql:///world", "root", "12345"); // Step 3: Create a statement Statement statement = con.createStatement(); String sql = "select * from people"; // Step 4: Execute the query ResultSet result = statement.executeQuery(sql); // Step 5: Process the results // Condition check using hasNext() method which // holds true till there is single element // remaining in List while (result.next()) { // Print name an age System.out.println( "Name: " + result.getString("name")); System.out.println( "Age:" + result.getString("age")); } } // Catching database exceptions if any catch (SQLException e) { // Print the exception System.out.println(e); } // Catching generic ClassNotFoundException if any catch (ClassNotFoundException e) { // Print and display the line number // where exception occurred e.printStackTrace(); } }}
Output: Name and age are as shown for random inputs
2. Prepared Statement represents a recompiled SQL statement, that can be executed many times. This accepts parameterized SQL queries. In this, “?” is used instead of the parameter, one can pass the parameter dynamically by using the methods of PREPARED STATEMENT at run time.
Illustration:
Considering in the people database if there is a need to INSERT some values, SQL statements such as these are used:
INSERT INTO people VALUES ("Ayan",25);
INSERT INTO people VALUES("Kriya",32);
To do the same in Java, one may use Prepared Statements and set the values in the ? holders, setXXX() of a prepared statement is used as shown:
String query = "INSERT INTO people(name, age)VALUES(?, ?)";
Statement pstmt = con.prepareStatement(query);
pstmt.setString(1,"Ayan");
ptstmt.setInt(2,25);
// where pstmt is an object name
Implementation: Once the PreparedStatement object is created, there are three ways to execute it:
execute(): This returns a boolean value and executes a static SQL statement that is present in the prepared statement object.
executeQuery(): Returns a ResultSet from the current prepared statement.
executeUpdate(): Returns the number of rows affected by the DML statements such as INSERT, DELETE, and more that is present in the current Prepared Statement.
Example:
Java
// Java Program illustrating Prepared Statement in JDBC // Step 1: Importing DB(SQL here) classesimport java.sql.*;// Importing Scanner class to// take input from the userimport java.util.Scanner; // Main clasclass GFG { // Main driver method public static void main(String[] args) { // try block to check for exceptions try { // Step 2: Establish a connection // Step 3: Load and register drivers // Loading drivers using forName() method Class.forName("com.mysql.cj.jdbc.Driver"); // Scanner class to take input from user Scanner sc = new Scanner(System.in); // Display message for ease for user System.out.println( "What age do you want to search?? "); // Reading age an primitive datatype from user // using nextInt() method int age = sc.nextInt(); // Registering drivers using DriverManager Connection con = DriverManager.getConnection( "jdbc:mysql:///world", "root", "12345"); // Step 4: Create a statement PreparedStatement ps = con.prepareStatement( "select name from world.people where age = ?"); // Step 5: Execute the query ps.setInt(1, age); ResultSet result = ps.executeQuery(); // Step 6: Process the results // Condition check using next() method // to check for element while (result.next()) { // Print and display elements(Names) System.out.println("Name : " + result.getString(1)); } // Step 7: Closing the connections // (Optional but it is recommended to do so) } // Catch block to handle database exceptions catch (SQLException e) { // Display the DB exception if any System.out.println(e); } // Catch block to handle class exceptions catch (ClassNotFoundException e) { // Print the line number where exception occurred // using printStackTrace() method if any e.printStackTrace(); } }}
Output:
3. Callable Statement are stored procedures which are a group of statements that we compile in the database for some task, they are beneficial when we are dealing with multiple tables with complex scenario & rather than sending multiple queries to the database, we can send the required data to the stored procedure & lower the logic executed in the database server itself. The Callable Statement interface provided by JDBC API helps in executing stored procedures.
Syntax: To prepare a CallableStatement
CallableStatement cstmt = con.prepareCall("{call Procedure_name(?, ?}");
Implementation: Once the callable statement object is created
execute() is used to perform the execution of the statement.
Example:
Java
// Java Program illustrating Callable Statement in JDBC // Step 1: Importing DB(SQL) classesimport java.sql.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Try block to check if any exceptions occurs try { // Step 2: Establish a connection // Step 3: Loading and registering drivers // Loading driver using forName() method Class.forName("com.mysql.cj.jdbc.Driver"); // Registering driver using DriverManager Connection con = DriverManager.getConnection( "jdbc:mysql:///world", "root", "12345"); // Step 4: Create a statement Statement s = con.createStatement(); // Step 5: Execute the query // select * from people CallableStatement cs = con.prepareCall("{call peopleinfo(?,?)}"); cs.setString(1, "Bob"); cs.setInt(2, 64); cs.execute(); ResultSet result = s.executeQuery("select * from people"); // Step 6: Process the results // Condition check using next() method // to check for element while (result.next()) { // Print and display elements (Name and Age) System.out.println("Name : " + result.getString(1)); System.out.println("Age : " + result.getInt(2)); } } // Catch statement for DB exceptions catch (SQLException e) { // Print the exception System.out.println(e); } // Catch block for generic class exceptions catch (ClassNotFoundException e) { // Print the line number where exception occurred e.printStackTrace(); } }}
Output:
adnanirshad158
sooda367
surinderdawra388
simranarora5sos
saurabh1990aror
JDBC
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Jul, 2021"
},
{
"code": null,
"e": 257,
"s": 54,
"text": "The statement interface is used to create SQL basic statements in Java it provides methods to execute queries with the database. There are different types of statements that are used in JDBC as follows:"
},
{
"code": null,
"e": 274,
"s": 257,
"text": "Create Statement"
},
{
"code": null,
"e": 293,
"s": 274,
"text": "Prepared Statement"
},
{
"code": null,
"e": 312,
"s": 293,
"text": "Callable Statement"
},
{
"code": null,
"e": 534,
"s": 312,
"text": "1. Create a Statement: From the connection interface, you can create the object for this interface. It is generally used for general–purpose access to databases and is useful while using static SQL statements at runtime."
},
{
"code": null,
"e": 542,
"s": 534,
"text": "Syntax:"
},
{
"code": null,
"e": 594,
"s": 542,
"text": "Statement statement = connection.createStatement();"
},
{
"code": null,
"e": 684,
"s": 594,
"text": "Implementation: Once the Statement object is created, there are three ways to execute it."
},
{
"code": null,
"e": 854,
"s": 684,
"text": "boolean execute(String SQL): If the ResultSet object is retrieved, then it returns true else false is returned. Is used to execute SQL DDL statements or for dynamic SQL."
},
{
"code": null,
"e": 1030,
"s": 854,
"text": "int executeUpdate(String SQL): Returns number of rows that are affected by the execution of the statement, used when you need a number for INSERT, DELETE or UPDATE statements."
},
{
"code": null,
"e": 1135,
"s": 1030,
"text": "ResultSet executeQuery(String SQL): Returns a ResultSet object. Used similarly as SELECT is used in SQL."
},
{
"code": null,
"e": 1144,
"s": 1135,
"text": "Example:"
},
{
"code": null,
"e": 1149,
"s": 1144,
"text": "Java"
},
{
"code": "// Java Program illustrating Create Statement in JDBC // Importing Database(SQL) classesimport java.sql.*; // Classclass GFG { // Main driver method public static void main(String[] args) { // Try block to check if any exceptions occur try { // Step 2: Loading and registering drivers // Loading driver using forName() method Class.forName(\"com.mysql.cj.jdbc.Driver\"); // Registering driver using DriverManager Connection con = DriverManager.getConnection( \"jdbc:mysql:///world\", \"root\", \"12345\"); // Step 3: Create a statement Statement statement = con.createStatement(); String sql = \"select * from people\"; // Step 4: Execute the query ResultSet result = statement.executeQuery(sql); // Step 5: Process the results // Condition check using hasNext() method which // holds true till there is single element // remaining in List while (result.next()) { // Print name an age System.out.println( \"Name: \" + result.getString(\"name\")); System.out.println( \"Age:\" + result.getString(\"age\")); } } // Catching database exceptions if any catch (SQLException e) { // Print the exception System.out.println(e); } // Catching generic ClassNotFoundException if any catch (ClassNotFoundException e) { // Print and display the line number // where exception occurred e.printStackTrace(); } }}",
"e": 2847,
"s": 1149,
"text": null
},
{
"code": null,
"e": 2899,
"s": 2847,
"text": "Output: Name and age are as shown for random inputs"
},
{
"code": null,
"e": 3177,
"s": 2901,
"text": "2. Prepared Statement represents a recompiled SQL statement, that can be executed many times. This accepts parameterized SQL queries. In this, “?” is used instead of the parameter, one can pass the parameter dynamically by using the methods of PREPARED STATEMENT at run time."
},
{
"code": null,
"e": 3192,
"s": 3177,
"text": "Illustration: "
},
{
"code": null,
"e": 3309,
"s": 3192,
"text": "Considering in the people database if there is a need to INSERT some values, SQL statements such as these are used: "
},
{
"code": null,
"e": 3387,
"s": 3309,
"text": "INSERT INTO people VALUES (\"Ayan\",25);\nINSERT INTO people VALUES(\"Kriya\",32);"
},
{
"code": null,
"e": 3532,
"s": 3387,
"text": "To do the same in Java, one may use Prepared Statements and set the values in the ? holders, setXXX() of a prepared statement is used as shown: "
},
{
"code": null,
"e": 3720,
"s": 3532,
"text": "String query = \"INSERT INTO people(name, age)VALUES(?, ?)\";\nStatement pstmt = con.prepareStatement(query);\npstmt.setString(1,\"Ayan\");\nptstmt.setInt(2,25);\n// where pstmt is an object name"
},
{
"code": null,
"e": 3819,
"s": 3720,
"text": "Implementation: Once the PreparedStatement object is created, there are three ways to execute it: "
},
{
"code": null,
"e": 3945,
"s": 3819,
"text": "execute(): This returns a boolean value and executes a static SQL statement that is present in the prepared statement object."
},
{
"code": null,
"e": 4018,
"s": 3945,
"text": "executeQuery(): Returns a ResultSet from the current prepared statement."
},
{
"code": null,
"e": 4177,
"s": 4018,
"text": "executeUpdate(): Returns the number of rows affected by the DML statements such as INSERT, DELETE, and more that is present in the current Prepared Statement."
},
{
"code": null,
"e": 4187,
"s": 4177,
"text": "Example: "
},
{
"code": null,
"e": 4192,
"s": 4187,
"text": "Java"
},
{
"code": "// Java Program illustrating Prepared Statement in JDBC // Step 1: Importing DB(SQL here) classesimport java.sql.*;// Importing Scanner class to// take input from the userimport java.util.Scanner; // Main clasclass GFG { // Main driver method public static void main(String[] args) { // try block to check for exceptions try { // Step 2: Establish a connection // Step 3: Load and register drivers // Loading drivers using forName() method Class.forName(\"com.mysql.cj.jdbc.Driver\"); // Scanner class to take input from user Scanner sc = new Scanner(System.in); // Display message for ease for user System.out.println( \"What age do you want to search?? \"); // Reading age an primitive datatype from user // using nextInt() method int age = sc.nextInt(); // Registering drivers using DriverManager Connection con = DriverManager.getConnection( \"jdbc:mysql:///world\", \"root\", \"12345\"); // Step 4: Create a statement PreparedStatement ps = con.prepareStatement( \"select name from world.people where age = ?\"); // Step 5: Execute the query ps.setInt(1, age); ResultSet result = ps.executeQuery(); // Step 6: Process the results // Condition check using next() method // to check for element while (result.next()) { // Print and display elements(Names) System.out.println(\"Name : \" + result.getString(1)); } // Step 7: Closing the connections // (Optional but it is recommended to do so) } // Catch block to handle database exceptions catch (SQLException e) { // Display the DB exception if any System.out.println(e); } // Catch block to handle class exceptions catch (ClassNotFoundException e) { // Print the line number where exception occurred // using printStackTrace() method if any e.printStackTrace(); } }}",
"e": 6432,
"s": 4192,
"text": null
},
{
"code": null,
"e": 6441,
"s": 6432,
"text": "Output: "
},
{
"code": null,
"e": 6907,
"s": 6441,
"text": "3. Callable Statement are stored procedures which are a group of statements that we compile in the database for some task, they are beneficial when we are dealing with multiple tables with complex scenario & rather than sending multiple queries to the database, we can send the required data to the stored procedure & lower the logic executed in the database server itself. The Callable Statement interface provided by JDBC API helps in executing stored procedures."
},
{
"code": null,
"e": 6946,
"s": 6907,
"text": "Syntax: To prepare a CallableStatement"
},
{
"code": null,
"e": 7019,
"s": 6946,
"text": "CallableStatement cstmt = con.prepareCall(\"{call Procedure_name(?, ?}\");"
},
{
"code": null,
"e": 7081,
"s": 7019,
"text": "Implementation: Once the callable statement object is created"
},
{
"code": null,
"e": 7142,
"s": 7081,
"text": "execute() is used to perform the execution of the statement."
},
{
"code": null,
"e": 7151,
"s": 7142,
"text": "Example:"
},
{
"code": null,
"e": 7156,
"s": 7151,
"text": "Java"
},
{
"code": "// Java Program illustrating Callable Statement in JDBC // Step 1: Importing DB(SQL) classesimport java.sql.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Try block to check if any exceptions occurs try { // Step 2: Establish a connection // Step 3: Loading and registering drivers // Loading driver using forName() method Class.forName(\"com.mysql.cj.jdbc.Driver\"); // Registering driver using DriverManager Connection con = DriverManager.getConnection( \"jdbc:mysql:///world\", \"root\", \"12345\"); // Step 4: Create a statement Statement s = con.createStatement(); // Step 5: Execute the query // select * from people CallableStatement cs = con.prepareCall(\"{call peopleinfo(?,?)}\"); cs.setString(1, \"Bob\"); cs.setInt(2, 64); cs.execute(); ResultSet result = s.executeQuery(\"select * from people\"); // Step 6: Process the results // Condition check using next() method // to check for element while (result.next()) { // Print and display elements (Name and Age) System.out.println(\"Name : \" + result.getString(1)); System.out.println(\"Age : \" + result.getInt(2)); } } // Catch statement for DB exceptions catch (SQLException e) { // Print the exception System.out.println(e); } // Catch block for generic class exceptions catch (ClassNotFoundException e) { // Print the line number where exception occurred e.printStackTrace(); } }}",
"e": 9045,
"s": 7156,
"text": null
},
{
"code": null,
"e": 9055,
"s": 9045,
"text": "Output: "
},
{
"code": null,
"e": 9072,
"s": 9057,
"text": "adnanirshad158"
},
{
"code": null,
"e": 9081,
"s": 9072,
"text": "sooda367"
},
{
"code": null,
"e": 9098,
"s": 9081,
"text": "surinderdawra388"
},
{
"code": null,
"e": 9114,
"s": 9098,
"text": "simranarora5sos"
},
{
"code": null,
"e": 9130,
"s": 9114,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 9135,
"s": 9130,
"text": "JDBC"
},
{
"code": null,
"e": 9140,
"s": 9135,
"text": "Java"
},
{
"code": null,
"e": 9159,
"s": 9140,
"text": "Technical Scripter"
},
{
"code": null,
"e": 9164,
"s": 9159,
"text": "Java"
}
] |
KitHack – Hacking tools pack in Kali Linux
|
23 Sep, 2021
KitHack Framework is a free and open-source tool available on GitHub. It is designed to automate the process of downloading and installing different tools for penetration testing, with a special option that allows generating cross-platform backdoors using Metasploit Framework.
The framework has the following options as a menu in which the too provide different tools according to category:
Passwords Attacks
Web Attacks
Spoofing
Information Gathering
Others
Android
Windows
Phishing
WIFI Attacks
Others
Step 1: Open your kali Linux operating system and open the terminal in order to install the tool. Use the following command to install the tool.
git clone https://github.com/AdrMXR/KitHack.git
cd KitHack
Step 2: Now to list out the content of the tool use the following command.
ls
Step 3: Now Install the tool using the following command.
bash install.sh
Step 4: All the installation has been done now use the following command to run the tool.
python3 KitHack.py
The installation has been done now we will see examples to use the tool.
Example 1: Use the KitHack framework to install the information gathering tool.
Choose option:
08
Here we have chosen the 08 option to go into the information gathering submenu.
Now we are downloading a tool called gasmask from the menu so we have chosen 11
KitHack frameworks started downloading the tool from GitHub. This is how KitHack framework makes it easy to security researchers to download all the tools of need from a single place.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
nohup Command in Linux with Examples
mv command in Linux with examples
chmod command in Linux with examples
Array Basics in Shell Scripting | Set 1
Introduction to Linux Operating System
Basic Operators in Shell Scripting
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Sep, 2021"
},
{
"code": null,
"e": 306,
"s": 28,
"text": "KitHack Framework is a free and open-source tool available on GitHub. It is designed to automate the process of downloading and installing different tools for penetration testing, with a special option that allows generating cross-platform backdoors using Metasploit Framework."
},
{
"code": null,
"e": 420,
"s": 306,
"text": "The framework has the following options as a menu in which the too provide different tools according to category:"
},
{
"code": null,
"e": 438,
"s": 420,
"text": "Passwords Attacks"
},
{
"code": null,
"e": 450,
"s": 438,
"text": "Web Attacks"
},
{
"code": null,
"e": 459,
"s": 450,
"text": "Spoofing"
},
{
"code": null,
"e": 481,
"s": 459,
"text": "Information Gathering"
},
{
"code": null,
"e": 488,
"s": 481,
"text": "Others"
},
{
"code": null,
"e": 496,
"s": 488,
"text": "Android"
},
{
"code": null,
"e": 504,
"s": 496,
"text": "Windows"
},
{
"code": null,
"e": 513,
"s": 504,
"text": "Phishing"
},
{
"code": null,
"e": 526,
"s": 513,
"text": "WIFI Attacks"
},
{
"code": null,
"e": 533,
"s": 526,
"text": "Others"
},
{
"code": null,
"e": 678,
"s": 533,
"text": "Step 1: Open your kali Linux operating system and open the terminal in order to install the tool. Use the following command to install the tool."
},
{
"code": null,
"e": 737,
"s": 678,
"text": "git clone https://github.com/AdrMXR/KitHack.git\ncd KitHack"
},
{
"code": null,
"e": 812,
"s": 737,
"text": "Step 2: Now to list out the content of the tool use the following command."
},
{
"code": null,
"e": 815,
"s": 812,
"text": "ls"
},
{
"code": null,
"e": 873,
"s": 815,
"text": "Step 3: Now Install the tool using the following command."
},
{
"code": null,
"e": 890,
"s": 873,
"text": " bash install.sh"
},
{
"code": null,
"e": 980,
"s": 890,
"text": "Step 4: All the installation has been done now use the following command to run the tool."
},
{
"code": null,
"e": 999,
"s": 980,
"text": "python3 KitHack.py"
},
{
"code": null,
"e": 1072,
"s": 999,
"text": "The installation has been done now we will see examples to use the tool."
},
{
"code": null,
"e": 1152,
"s": 1072,
"text": "Example 1: Use the KitHack framework to install the information gathering tool."
},
{
"code": null,
"e": 1167,
"s": 1152,
"text": "Choose option:"
},
{
"code": null,
"e": 1170,
"s": 1167,
"text": "08"
},
{
"code": null,
"e": 1250,
"s": 1170,
"text": "Here we have chosen the 08 option to go into the information gathering submenu."
},
{
"code": null,
"e": 1330,
"s": 1250,
"text": "Now we are downloading a tool called gasmask from the menu so we have chosen 11"
},
{
"code": null,
"e": 1515,
"s": 1330,
"text": "KitHack frameworks started downloading the tool from GitHub. This is how KitHack framework makes it easy to security researchers to download all the tools of need from a single place. "
},
{
"code": null,
"e": 1526,
"s": 1515,
"text": "Kali-Linux"
},
{
"code": null,
"e": 1538,
"s": 1526,
"text": "Linux-Tools"
},
{
"code": null,
"e": 1549,
"s": 1538,
"text": "Linux-Unix"
},
{
"code": null,
"e": 1647,
"s": 1549,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1673,
"s": 1647,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 1708,
"s": 1673,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 1745,
"s": 1708,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 1774,
"s": 1745,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 1811,
"s": 1774,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 1845,
"s": 1811,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 1882,
"s": 1845,
"text": "chmod command in Linux with examples"
},
{
"code": null,
"e": 1922,
"s": 1882,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 1961,
"s": 1922,
"text": "Introduction to Linux Operating System"
}
] |
Selective Search for Object Detection | R-CNN
|
22 Jul, 2021
The problem of object localization is the most difficult part of object detection. One approach is that we use sliding window of different size to locate objects in the image. This approach is called Exhaustive search. This approach is computationally very expensive as we need to search for object in thousands of windows even for small image size. Some optimization has been done such as taking window sizes in different ratios (instead of increasing it by some pixels). But even after this due to number of windows it is not very efficient. This article looks into selective search algorithm which uses both Exhaustive search and segmentation (a method to separate objects of different shapes in the image by assigning them different colors).
Algorithm Of Selective Search :
Generate initial sub-segmentation of input image using the method describe by Felzenszwalb et al in his paper “Efficient Graph-Based Image Segmentation “.Recursively combine the smaller similar regions into larger ones. We use Greedy algorithm to combine similar regions to make larger regions. The algorithm is written below.Greedy Algorithm :
1. From set of regions, choose two that are most similar.
2. Combine them into a single, larger region.
3. Repeat the above steps for multiple iterations. Use the segmented region proposals to generate candidate object locations.
Generate initial sub-segmentation of input image using the method describe by Felzenszwalb et al in his paper “Efficient Graph-Based Image Segmentation “.
Recursively combine the smaller similar regions into larger ones. We use Greedy algorithm to combine similar regions to make larger regions. The algorithm is written below.Greedy Algorithm :
1. From set of regions, choose two that are most similar.
2. Combine them into a single, larger region.
3. Repeat the above steps for multiple iterations.
Greedy Algorithm :
1. From set of regions, choose two that are most similar.
2. Combine them into a single, larger region.
3. Repeat the above steps for multiple iterations.
Use the segmented region proposals to generate candidate object locations.
The selective search paper considers four types of similarity when combining the initial small segmentation into larger ones. These similarities are:
Color Similarity : Specifically for each region we generate the histogram of each channels of colors present in image .In this paper 25 bins are taken in histogram of each color channel. This gives us 75 bins (25 for each R, G and B) and all channels are combined into a vector (n = 75) for each region. Then we find similarity using equation below:
Texture Similarity : Texture similarity are calculated using generated 8 Gaussian derivatives of image and extracts histogram with 10 bins for each color channels. This gives us 10 x 8 x 3 = 240 dimensional vector for each region. We derive similarity using this equation.
Size Similarity : The basic idea of size similarity is to make smaller region merge easily. If this similarity is not taken into consideration then larger region keep merging with larger region and region proposals at multiple scales will be generated at this location only.
Fill Similarity : Fill Similarity measures how well two regions fit with each other. If two region fit well into one another (For Example one region is present in another) then they should be merged, if two region does not even touch each other then they should not be merged.Now, Above four similarities combined to form a final similarity.
To measure the performance of this method. The paper describes an evaluation parameter known as MABO (Mean Average Best Overlap).There are two version of selective search came Fast and Quality. The difference between them is Quality generated much more bounding boxes than Fast and so takes more time to compute but have higher recall and ABO(Average Best Overlap) and MABO (Mean Average Best overlap). We calculated ABO as follows.
As we can observe that when all the similarities are used in combination, It gives us best MABO. However, it can also be conclude RGB is not best color scheme to use in this method. HSV, Lab and rgI all performs better than RGB, this is because these are not sensitive to shadows and brightness changes.
But when we diversify and combine these different similarities, color scheme and threshold values (k),
In selective search paper, it applies greedy method based on MABO on different strategies to get above results. We can say that this method of combining different strategies although gives better MABO, but the run time also increases considerably.
In selective search paper, authors use this algorithm on object detection and train a model using by giving ground truth examples and sample hypothesis that overlaps 20-50% with ground truth(as negative example) into SVM classifier and train it to identify false positive . The architecture of model used in given below.
Object Recognition Architecture (Source : Selective Search paper)
The result generated on VOC 2007 test set is,
As we can see that it produces a very high recall and best MABO on VOC 2007 test Set and it requires much less number of windows to be processed as compared to other algorithms who achieve similar recall and MABO.
Applications :
Selective Search is widely used in early state-of-the-art architecture such as R-CNN, Fast R-CNN etc. However, Due to number of windows it processed, it takes anywhere from 1.8 to 3.7 seconds (Selective Search Fast) to generate region proposal which is not good enough for a real-time object detection system.
Reference:
Selective Search paper (Selective Search for Object Detection)
Stanford Computer Vision Slides
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Information Retrieval?
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
Sequential Covering Algorithm
ML | Expectation-Maximization Algorithm
Iterate over a list in Python
How to iterate through Excel rows in Python?
Read JSON file using Python
Python map() function
Rotate axis tick labels in Seaborn and Matplotlib
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Jul, 2021"
},
{
"code": null,
"e": 798,
"s": 52,
"text": "The problem of object localization is the most difficult part of object detection. One approach is that we use sliding window of different size to locate objects in the image. This approach is called Exhaustive search. This approach is computationally very expensive as we need to search for object in thousands of windows even for small image size. Some optimization has been done such as taking window sizes in different ratios (instead of increasing it by some pixels). But even after this due to number of windows it is not very efficient. This article looks into selective search algorithm which uses both Exhaustive search and segmentation (a method to separate objects of different shapes in the image by assigning them different colors)."
},
{
"code": null,
"e": 830,
"s": 798,
"text": "Algorithm Of Selective Search :"
},
{
"code": null,
"e": 1407,
"s": 830,
"text": "Generate initial sub-segmentation of input image using the method describe by Felzenszwalb et al in his paper “Efficient Graph-Based Image Segmentation “.Recursively combine the smaller similar regions into larger ones. We use Greedy algorithm to combine similar regions to make larger regions. The algorithm is written below.Greedy Algorithm : \n\n1. From set of regions, choose two that are most similar.\n2. Combine them into a single, larger region.\n3. Repeat the above steps for multiple iterations. Use the segmented region proposals to generate candidate object locations."
},
{
"code": null,
"e": 1562,
"s": 1407,
"text": "Generate initial sub-segmentation of input image using the method describe by Felzenszwalb et al in his paper “Efficient Graph-Based Image Segmentation “."
},
{
"code": null,
"e": 1911,
"s": 1562,
"text": "Recursively combine the smaller similar regions into larger ones. We use Greedy algorithm to combine similar regions to make larger regions. The algorithm is written below.Greedy Algorithm : \n\n1. From set of regions, choose two that are most similar.\n2. Combine them into a single, larger region.\n3. Repeat the above steps for multiple iterations. "
},
{
"code": null,
"e": 2087,
"s": 1911,
"text": "Greedy Algorithm : \n\n1. From set of regions, choose two that are most similar.\n2. Combine them into a single, larger region.\n3. Repeat the above steps for multiple iterations."
},
{
"code": null,
"e": 2164,
"s": 2089,
"text": "Use the segmented region proposals to generate candidate object locations."
},
{
"code": null,
"e": 2315,
"s": 2164,
"text": "The selective search paper considers four types of similarity when combining the initial small segmentation into larger ones. These similarities are: "
},
{
"code": null,
"e": 2666,
"s": 2315,
"text": "Color Similarity : Specifically for each region we generate the histogram of each channels of colors present in image .In this paper 25 bins are taken in histogram of each color channel. This gives us 75 bins (25 for each R, G and B) and all channels are combined into a vector (n = 75) for each region. Then we find similarity using equation below:"
},
{
"code": null,
"e": 2939,
"s": 2666,
"text": "Texture Similarity : Texture similarity are calculated using generated 8 Gaussian derivatives of image and extracts histogram with 10 bins for each color channels. This gives us 10 x 8 x 3 = 240 dimensional vector for each region. We derive similarity using this equation."
},
{
"code": null,
"e": 3216,
"s": 2939,
"text": "Size Similarity : The basic idea of size similarity is to make smaller region merge easily. If this similarity is not taken into consideration then larger region keep merging with larger region and region proposals at multiple scales will be generated at this location only. "
},
{
"code": null,
"e": 3558,
"s": 3216,
"text": "Fill Similarity : Fill Similarity measures how well two regions fit with each other. If two region fit well into one another (For Example one region is present in another) then they should be merged, if two region does not even touch each other then they should not be merged.Now, Above four similarities combined to form a final similarity."
},
{
"code": null,
"e": 3991,
"s": 3558,
"text": "To measure the performance of this method. The paper describes an evaluation parameter known as MABO (Mean Average Best Overlap).There are two version of selective search came Fast and Quality. The difference between them is Quality generated much more bounding boxes than Fast and so takes more time to compute but have higher recall and ABO(Average Best Overlap) and MABO (Mean Average Best overlap). We calculated ABO as follows."
},
{
"code": null,
"e": 4296,
"s": 3991,
"text": "As we can observe that when all the similarities are used in combination, It gives us best MABO. However, it can also be conclude RGB is not best color scheme to use in this method. HSV, Lab and rgI all performs better than RGB, this is because these are not sensitive to shadows and brightness changes. "
},
{
"code": null,
"e": 4399,
"s": 4296,
"text": "But when we diversify and combine these different similarities, color scheme and threshold values (k),"
},
{
"code": null,
"e": 4647,
"s": 4399,
"text": "In selective search paper, it applies greedy method based on MABO on different strategies to get above results. We can say that this method of combining different strategies although gives better MABO, but the run time also increases considerably."
},
{
"code": null,
"e": 4968,
"s": 4647,
"text": "In selective search paper, authors use this algorithm on object detection and train a model using by giving ground truth examples and sample hypothesis that overlaps 20-50% with ground truth(as negative example) into SVM classifier and train it to identify false positive . The architecture of model used in given below."
},
{
"code": null,
"e": 5034,
"s": 4968,
"text": "Object Recognition Architecture (Source : Selective Search paper)"
},
{
"code": null,
"e": 5080,
"s": 5034,
"text": "The result generated on VOC 2007 test set is,"
},
{
"code": null,
"e": 5294,
"s": 5080,
"text": "As we can see that it produces a very high recall and best MABO on VOC 2007 test Set and it requires much less number of windows to be processed as compared to other algorithms who achieve similar recall and MABO."
},
{
"code": null,
"e": 5311,
"s": 5296,
"text": "Applications :"
},
{
"code": null,
"e": 5622,
"s": 5311,
"text": "Selective Search is widely used in early state-of-the-art architecture such as R-CNN, Fast R-CNN etc. However, Due to number of windows it processed, it takes anywhere from 1.8 to 3.7 seconds (Selective Search Fast) to generate region proposal which is not good enough for a real-time object detection system. "
},
{
"code": null,
"e": 5635,
"s": 5624,
"text": "Reference:"
},
{
"code": null,
"e": 5698,
"s": 5635,
"text": "Selective Search paper (Selective Search for Object Detection)"
},
{
"code": null,
"e": 5730,
"s": 5698,
"text": "Stanford Computer Vision Slides"
},
{
"code": null,
"e": 5747,
"s": 5730,
"text": "Machine Learning"
},
{
"code": null,
"e": 5754,
"s": 5747,
"text": "Python"
},
{
"code": null,
"e": 5771,
"s": 5754,
"text": "Machine Learning"
},
{
"code": null,
"e": 5869,
"s": 5771,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5900,
"s": 5869,
"text": "What is Information Retrieval?"
},
{
"code": null,
"e": 5941,
"s": 5900,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 5974,
"s": 5941,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 6004,
"s": 5974,
"text": "Sequential Covering Algorithm"
},
{
"code": null,
"e": 6044,
"s": 6004,
"text": "ML | Expectation-Maximization Algorithm"
},
{
"code": null,
"e": 6074,
"s": 6044,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 6119,
"s": 6074,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 6147,
"s": 6119,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 6169,
"s": 6147,
"text": "Python map() function"
}
] |
How to make Flappy Bird Game in Pygame?
|
31 Aug, 2021
In this article, we are going to see how to make a flappy bird game in Pygame.
We all are familiar with this game. In this game, the main objective of the player is to gain the maximum points by defending the bird from hurdles. Here, we will build our own Flappy Bird game using Python.
We will be using Pygame(a Python library) to create this Flappy Bird game. Pygame is an open-source library that is designed for making video games. it helps us to create fully functional games and multimedia programs in python.
First of all, You have to install the Pygame library using the command:-
pip install pygame
Step 1: In this first step, we have to import libraries.
After that, we have to set the height and width of the screen to which the game will be played. Now we have to define some images which we shall use in our game like pipes as hurdles, birds images, and also a background image of the flappy bird game.
Python3
# For generating random height of pipesimport random import sys import pygamefrom pygame.locals import * # Global Variables for the gamewindow_width = 600window_height = 499 # set height and width of windowwindow = pygame.display.set_mode((window_width, window_height)) elevation = window_height * 0.8game_images = {} framepersecond = 32pipeimage = 'images/pipe.png'background_image = 'images/background.jpg'birdplayer_image = '/images/bird.png'sealevel_image = '/images/base.jfif'
Step 2: After declaring game variables and importing libraries we have to initialize the Pygame
The used file can be downloaded from here.
Initialize the program using pygame.init() and set the caption of the window. Here pygame.time.Clock() will be used further in the main loop of the game to alter the speed the bird. Load the images from the system in pygame using pygame.image.load().
Python3
# program where the game startsif __name__ == "__main__": # For initializing modules of pygame library pygame.init() framepersecond_clock = pygame.time.Clock() # Sets the title on top of game window pygame.display.set_caption('Flappy Bird Game') # Load all the images which we will use in the game # images for displaying score game_images['scoreimages'] = ( pygame.image.load('images/0.png').convert_alpha(), pygame.image.load('images/1.png').convert_alpha(), pygame.image.load('images/2.png').convert_alpha(), pygame.image.load('images/3.png').convert_alpha(), pygame.image.load('images/4.png').convert_alpha(), pygame.image.load('images/5.png').convert_alpha(), pygame.image.load('images/6.png').convert_alpha(), pygame.image.load('images/7.png').convert_alpha(), pygame.image.load('images/8.png').convert_alpha(), pygame.image.load('images/9.png').convert_alpha() ) game_images['flappybird'] = pygame.image.load(birdplayer_image).convert_alpha() game_images['sea_level'] = pygame.image.load(sealevel_image).convert_alpha() game_images['background'] = pygame.image.load(background_image).convert_alpha() game_images['pipeimage'] = (pygame.transform.rotate(pygame.image.load(pipeimage) .convert_alpha(), 180), pygame.image.load(pipeimage).convert_alpha()) print("WELCOME TO THE FLAPPY BIRD GAME") print("Press space or enter to start the game")
Step 3: Initialize the position of the bird and starting the game loop
Initialize the position of bird and sea level to the ground. Adding conditions in the loop defines the game conditions. The variable horizontal and vertical is used to set the position of the bird. We have to run the program until the user stops or exits (using sys.exit())if the program so, we create an infinite while loop.
Python3
while True: # sets the coordinates of flappy bird horizontal = int(window_width/5) vertical = int((window_height - game_images['flappybird'].get_height())/2) # for selevel ground = 0 while True: for event in pygame.event.get(): # if user clicks on cross button, close the game if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): pygame.quit() # Exit the program sys.exit() # If the user presses space or up key, # start the game for them elif event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP): flappygame() # if user doesn't press anykey Nothing happen else: window.blit(game_images['background'], (0, 0)) window.blit(game_images['flappybird'], (horizontal, vertical)) window.blit(game_images['sea_level'], (ground, elevation)) # Just Refresh the screen pygame.display.update() # set the rate of frame per second framepersecond_clock.tick(framepersecond)
Step 4: Create a function that generates a new pipe of random height
First of all, we have to fetch the height of the pipe using getheight() function. After this generates a random number between 0 to a number (such that the height of the pipe should be adjustable to our window height). After that, we create a list of dictionaries that contains coordinates of upper and lower pipes and return it.
Python3
def createPipe(): offset = window_height/3 pipeHeight = game_images['pipeimage'][0].get_height() # generating random height of pipes y2 = offset + random.randrange( 0, int(window_height - game_images['sea_level'].get_height() - 1.2 * offset)) pipeX = window_width + 10 y1 = pipeHeight - y2 + offset pipe = [ # upper Pipe {'x': pipeX, 'y': -y1}, # lower Pipe {'x': pipeX, 'y': y2} ] return pipe
Step 5: Now we create a GameOver() function which represents whether the bird has hit the pipes or fall into the sea.
According to my thought, three conditions lead to a situation of the game over. if the difference between our elevation and a certain height is less than vertical it means the bird has crossed its boundaries resulting in a game over and if the bird hits any of the lower and upper pip then this will also lead to game over condition.
Python3
# Checking if bird is above the sealevel.def isGameOver(horizontal, vertical, up_pipes, down_pipes): if vertical > elevation - 25 or vertical < 0: return True # Checking if bird hits the upper pipe or not for pipe in up_pipes: pipeHeight = game_images['pipeimage'][0].get_height() if(vertical < pipeHeight + pipe['y'] and abs(horizontal - pipe['x']) < game_images['pipeimage'][0].get_width()): return True # Checking if bird hits the lower pipe or not for pipe in down_pipes: if (vertical + game_images['flappybird'].get_height() > pipe['y']) and abs(horizontal - pipe['x']) < game_images['pipeimage'][0].get_width(): return True return False
Step 6: Now we will be creating our main function (flappygame()) that will do the following things:
Initialize the variables and creating two pipes by createPipe() function. Create two lists first is of lower pipes and the other is of lower pipes. Defining the bird velocity, minimum bird velocity, maximum bird velocity, and pipes velocity. Handle the key events using pygame.event.get() and checking for the game is over or not if it is over return from the function. Updating the score and blit game images such as background, pipe, and bird on the window.
Python3
def flappygame(): your_score = 0 horizontal = int(window_width/5) vertical = int(window_width/2) ground = 0 mytempheight = 100 # Generating two pipes for blitting on window first_pipe = createPipe() second_pipe = createPipe() # List containing lower pipes down_pipes = [ {'x': window_width+300-mytempheight, 'y': first_pipe[1]['y']}, {'x': window_width+300-mytempheight+(window_width/2), 'y': second_pipe[1]['y']}, ] # List Containing upper pipes up_pipes = [ {'x': window_width+300-mytempheight, 'y': first_pipe[0]['y']}, {'x': window_width+200-mytempheight+(window_width/2), 'y': second_pipe[0]['y']}, ] pipeVelX = -4 #pipe velocity along x bird_velocity_y = -9 # bird velocity bird_Max_Vel_Y = 10 bird_Min_Vel_Y = -8 birdAccY = 1 # velocity while flapping bird_flap_velocity = -8 # It is true only when the bird is flapping bird_flapped = False while True: # Handling the key pressing events for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): pygame.quit() sys.exit() if event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP): if vertical > 0: bird_velocity_y = bird_flap_velocity bird_flapped = True # This function will return true if the flappybird is crashed game_over = isGameOver(horizontal, vertical, up_pipes, down_pipes) if game_over: return # check for your_score playerMidPos = horizontal + game_images['flappybird'].get_width()/2 for pipe in up_pipes: pipeMidPos = pipe['x'] + game_images['pipeimage'][0].get_width()/2 if pipeMidPos <= playerMidPos < pipeMidPos + 4: # Printing the score your_score += 1 print(f"Your your_score is {your_score}") if bird_velocity_y < bird_Max_Vel_Y and not bird_flapped: bird_velocity_y += birdAccY if bird_flapped: bird_flapped = False playerHeight = game_images['flappybird'].get_height() vertical = vertical + min(bird_velocity_y, elevation - vertical - playerHeight) # move pipes to the left for upperPipe, lowerPipe in zip(up_pipes, down_pipes): upperPipe['x'] += pipeVelX lowerPipe['x'] += pipeVelX # Add a new pipe when the first is about # to cross the leftmost part of the screen if 0 < up_pipes[0]['x'] < 5: newpipe = createPipe() up_pipes.append(newpipe[0]) down_pipes.append(newpipe[1]) # if the pipe is out of the screen, remove it if up_pipes[0]['x'] < -game_images['pipeimage'][0].get_width(): up_pipes.pop(0) down_pipes.pop(0) # Lets blit our game images now window.blit(game_images['background'], (0, 0)) for upperPipe, lowerPipe in zip(up_pipes, down_pipes): window.blit(game_images['pipeimage'][0], (upperPipe['x'], upperPipe['y'])) window.blit(game_images['pipeimage'][1], (lowerPipe['x'], lowerPipe['y'])) window.blit(game_images['sea_level'], (ground, elevation)) window.blit(game_images['flappybird'], (horizontal, vertical)) # Fetching the digits of score. numbers = [int(x) for x in list(str(your_score))] width = 0 # finding the width of score images from numbers. for num in numbers: width += game_images['scoreimages'][num].get_width() Xoffset = (window_width - width)/1.1 # Blitting the images on the window. for num in numbers: window.blit(game_images['scoreimages'][num], (Xoffset, window_width*0.02)) Xoffset += game_images['scoreimages'][num].get_width() # Refreshing the game window and displaying the score. pygame.display.update() # Set the framepersecond framepersecond_clock.tick(framepersecond)
Python3
# Import moduleimport randomimport sysimport pygamefrom pygame.locals import * # All the Game Variableswindow_width = 600window_height = 499 # set height and width of windowwindow = pygame.display.set_mode((window_width, window_height))elevation = window_height * 0.8game_images = {}framepersecond = 32pipeimage = 'images/pipe.png'background_image = 'images/background.jpg'birdplayer_image = 'images/bird.png'sealevel_image = 'images/base.jfif' def flappygame(): your_score = 0 horizontal = int(window_width/5) vertical = int(window_width/2) ground = 0 mytempheight = 100 # Generating two pipes for blitting on window first_pipe = createPipe() second_pipe = createPipe() # List containing lower pipes down_pipes = [ {'x': window_width+300-mytempheight, 'y': first_pipe[1]['y']}, {'x': window_width+300-mytempheight+(window_width/2), 'y': second_pipe[1]['y']}, ] # List Containing upper pipes up_pipes = [ {'x': window_width+300-mytempheight, 'y': first_pipe[0]['y']}, {'x': window_width+200-mytempheight+(window_width/2), 'y': second_pipe[0]['y']}, ] # pipe velocity along x pipeVelX = -4 # bird velocity bird_velocity_y = -9 bird_Max_Vel_Y = 10 bird_Min_Vel_Y = -8 birdAccY = 1 bird_flap_velocity = -8 bird_flapped = False while True: for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): pygame.quit() sys.exit() if event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP): if vertical > 0: bird_velocity_y = bird_flap_velocity bird_flapped = True # This function will return true # if the flappybird is crashed game_over = isGameOver(horizontal, vertical, up_pipes, down_pipes) if game_over: return # check for your_score playerMidPos = horizontal + game_images['flappybird'].get_width()/2 for pipe in up_pipes: pipeMidPos = pipe['x'] + game_images['pipeimage'][0].get_width()/2 if pipeMidPos <= playerMidPos < pipeMidPos + 4: your_score += 1 print(f"Your your_score is {your_score}") if bird_velocity_y < bird_Max_Vel_Y and not bird_flapped: bird_velocity_y += birdAccY if bird_flapped: bird_flapped = False playerHeight = game_images['flappybird'].get_height() vertical = vertical + \ min(bird_velocity_y, elevation - vertical - playerHeight) # move pipes to the left for upperPipe, lowerPipe in zip(up_pipes, down_pipes): upperPipe['x'] += pipeVelX lowerPipe['x'] += pipeVelX # Add a new pipe when the first is # about to cross the leftmost part of the screen if 0 < up_pipes[0]['x'] < 5: newpipe = createPipe() up_pipes.append(newpipe[0]) down_pipes.append(newpipe[1]) # if the pipe is out of the screen, remove it if up_pipes[0]['x'] < -game_images['pipeimage'][0].get_width(): up_pipes.pop(0) down_pipes.pop(0) # Lets blit our game images now window.blit(game_images['background'], (0, 0)) for upperPipe, lowerPipe in zip(up_pipes, down_pipes): window.blit(game_images['pipeimage'][0], (upperPipe['x'], upperPipe['y'])) window.blit(game_images['pipeimage'][1], (lowerPipe['x'], lowerPipe['y'])) window.blit(game_images['sea_level'], (ground, elevation)) window.blit(game_images['flappybird'], (horizontal, vertical)) # Fetching the digits of score. numbers = [int(x) for x in list(str(your_score))] width = 0 # finding the width of score images from numbers. for num in numbers: width += game_images['scoreimages'][num].get_width() Xoffset = (window_width - width)/1.1 # Blitting the images on the window. for num in numbers: window.blit(game_images['scoreimages'][num], (Xoffset, window_width*0.02)) Xoffset += game_images['scoreimages'][num].get_width() # Refreshing the game window and displaying the score. pygame.display.update() framepersecond_clock.tick(framepersecond) def isGameOver(horizontal, vertical, up_pipes, down_pipes): if vertical > elevation - 25 or vertical < 0: return True for pipe in up_pipes: pipeHeight = game_images['pipeimage'][0].get_height() if(vertical < pipeHeight + pipe['y'] and\ abs(horizontal - pipe['x']) < game_images['pipeimage'][0].get_width()): return True for pipe in down_pipes: if (vertical + game_images['flappybird'].get_height() > pipe['y']) and\ abs(horizontal - pipe['x']) < game_images['pipeimage'][0].get_width(): return True return False def createPipe(): offset = window_height/3 pipeHeight = game_images['pipeimage'][0].get_height() y2 = offset + \ random.randrange( 0, int(window_height - game_images['sea_level'].get_height() - 1.2 * offset)) pipeX = window_width + 10 y1 = pipeHeight - y2 + offset pipe = [ # upper Pipe {'x': pipeX, 'y': -y1}, # lower Pipe {'x': pipeX, 'y': y2} ] return pipe # program where the game startsif __name__ == "__main__": # For initializing modules of pygame library pygame.init() framepersecond_clock = pygame.time.Clock() # Sets the title on top of game window pygame.display.set_caption('Flappy Bird Game') # Load all the images which we will use in the game # images for displaying score game_images['scoreimages'] = ( pygame.image.load('images/0.png').convert_alpha(), pygame.image.load('images/1.png').convert_alpha(), pygame.image.load('images/2.png').convert_alpha(), pygame.image.load('images/3.png').convert_alpha(), pygame.image.load('images/4.png').convert_alpha(), pygame.image.load('images/5.png').convert_alpha(), pygame.image.load('images/6.png').convert_alpha(), pygame.image.load('images/7.png').convert_alpha(), pygame.image.load('images/8.png').convert_alpha(), pygame.image.load('images/9.png').convert_alpha() ) game_images['flappybird'] = pygame.image.load( birdplayer_image).convert_alpha() game_images['sea_level'] = pygame.image.load( sealevel_image).convert_alpha() game_images['background'] = pygame.image.load( background_image).convert_alpha() game_images['pipeimage'] = (pygame.transform.rotate(pygame.image.load( pipeimage).convert_alpha(), 180), pygame.image.load( pipeimage).convert_alpha()) print("WELCOME TO THE FLAPPY BIRD GAME") print("Press space or enter to start the game") # Here starts the main game while True: # sets the coordinates of flappy bird horizontal = int(window_width/5) vertical = int( (window_height - game_images['flappybird'].get_height())/2) ground = 0 while True: for event in pygame.event.get(): # if user clicks on cross button, close the game if event.type == QUIT or (event.type == KEYDOWN and \ event.key == K_ESCAPE): pygame.quit() sys.exit() # If the user presses space or # up key, start the game for them elif event.type == KEYDOWN and (event.key == K_SPACE or\ event.key == K_UP): flappygame() # if user doesn't press anykey Nothing happen else: window.blit(game_images['background'], (0, 0)) window.blit(game_images['flappybird'], (horizontal, vertical)) window.blit(game_images['sea_level'], (ground, elevation)) pygame.display.update() framepersecond_clock.tick(framepersecond)
Output:
Picked
Python-projects
Python-PyGame
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
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 | Get unique values from a list
Create a directory in Python
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n31 Aug, 2021"
},
{
"code": null,
"e": 133,
"s": 54,
"text": "In this article, we are going to see how to make a flappy bird game in Pygame."
},
{
"code": null,
"e": 341,
"s": 133,
"text": "We all are familiar with this game. In this game, the main objective of the player is to gain the maximum points by defending the bird from hurdles. Here, we will build our own Flappy Bird game using Python."
},
{
"code": null,
"e": 570,
"s": 341,
"text": "We will be using Pygame(a Python library) to create this Flappy Bird game. Pygame is an open-source library that is designed for making video games. it helps us to create fully functional games and multimedia programs in python."
},
{
"code": null,
"e": 643,
"s": 570,
"text": "First of all, You have to install the Pygame library using the command:-"
},
{
"code": null,
"e": 662,
"s": 643,
"text": "pip install pygame"
},
{
"code": null,
"e": 719,
"s": 662,
"text": "Step 1: In this first step, we have to import libraries."
},
{
"code": null,
"e": 970,
"s": 719,
"text": "After that, we have to set the height and width of the screen to which the game will be played. Now we have to define some images which we shall use in our game like pipes as hurdles, birds images, and also a background image of the flappy bird game."
},
{
"code": null,
"e": 978,
"s": 970,
"text": "Python3"
},
{
"code": "# For generating random height of pipesimport random import sys import pygamefrom pygame.locals import * # Global Variables for the gamewindow_width = 600window_height = 499 # set height and width of windowwindow = pygame.display.set_mode((window_width, window_height)) elevation = window_height * 0.8game_images = {} framepersecond = 32pipeimage = 'images/pipe.png'background_image = 'images/background.jpg'birdplayer_image = '/images/bird.png'sealevel_image = '/images/base.jfif'",
"e": 1471,
"s": 978,
"text": null
},
{
"code": null,
"e": 1568,
"s": 1471,
"text": "Step 2: After declaring game variables and importing libraries we have to initialize the Pygame "
},
{
"code": null,
"e": 1611,
"s": 1568,
"text": "The used file can be downloaded from here."
},
{
"code": null,
"e": 1862,
"s": 1611,
"text": "Initialize the program using pygame.init() and set the caption of the window. Here pygame.time.Clock() will be used further in the main loop of the game to alter the speed the bird. Load the images from the system in pygame using pygame.image.load()."
},
{
"code": null,
"e": 1870,
"s": 1862,
"text": "Python3"
},
{
"code": "# program where the game startsif __name__ == \"__main__\": # For initializing modules of pygame library pygame.init() framepersecond_clock = pygame.time.Clock() # Sets the title on top of game window pygame.display.set_caption('Flappy Bird Game') # Load all the images which we will use in the game # images for displaying score game_images['scoreimages'] = ( pygame.image.load('images/0.png').convert_alpha(), pygame.image.load('images/1.png').convert_alpha(), pygame.image.load('images/2.png').convert_alpha(), pygame.image.load('images/3.png').convert_alpha(), pygame.image.load('images/4.png').convert_alpha(), pygame.image.load('images/5.png').convert_alpha(), pygame.image.load('images/6.png').convert_alpha(), pygame.image.load('images/7.png').convert_alpha(), pygame.image.load('images/8.png').convert_alpha(), pygame.image.load('images/9.png').convert_alpha() ) game_images['flappybird'] = pygame.image.load(birdplayer_image).convert_alpha() game_images['sea_level'] = pygame.image.load(sealevel_image).convert_alpha() game_images['background'] = pygame.image.load(background_image).convert_alpha() game_images['pipeimage'] = (pygame.transform.rotate(pygame.image.load(pipeimage) .convert_alpha(), 180), pygame.image.load(pipeimage).convert_alpha()) print(\"WELCOME TO THE FLAPPY BIRD GAME\") print(\"Press space or enter to start the game\")",
"e": 3533,
"s": 1870,
"text": null
},
{
"code": null,
"e": 3604,
"s": 3533,
"text": "Step 3: Initialize the position of the bird and starting the game loop"
},
{
"code": null,
"e": 3930,
"s": 3604,
"text": "Initialize the position of bird and sea level to the ground. Adding conditions in the loop defines the game conditions. The variable horizontal and vertical is used to set the position of the bird. We have to run the program until the user stops or exits (using sys.exit())if the program so, we create an infinite while loop."
},
{
"code": null,
"e": 3938,
"s": 3930,
"text": "Python3"
},
{
"code": "while True: # sets the coordinates of flappy bird horizontal = int(window_width/5) vertical = int((window_height - game_images['flappybird'].get_height())/2) # for selevel ground = 0 while True: for event in pygame.event.get(): # if user clicks on cross button, close the game if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): pygame.quit() # Exit the program sys.exit() # If the user presses space or up key, # start the game for them elif event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP): flappygame() # if user doesn't press anykey Nothing happen else: window.blit(game_images['background'], (0, 0)) window.blit(game_images['flappybird'], (horizontal, vertical)) window.blit(game_images['sea_level'], (ground, elevation)) # Just Refresh the screen pygame.display.update() # set the rate of frame per second framepersecond_clock.tick(framepersecond)",
"e": 5317,
"s": 3938,
"text": null
},
{
"code": null,
"e": 5386,
"s": 5317,
"text": "Step 4: Create a function that generates a new pipe of random height"
},
{
"code": null,
"e": 5716,
"s": 5386,
"text": "First of all, we have to fetch the height of the pipe using getheight() function. After this generates a random number between 0 to a number (such that the height of the pipe should be adjustable to our window height). After that, we create a list of dictionaries that contains coordinates of upper and lower pipes and return it."
},
{
"code": null,
"e": 5724,
"s": 5716,
"text": "Python3"
},
{
"code": "def createPipe(): offset = window_height/3 pipeHeight = game_images['pipeimage'][0].get_height() # generating random height of pipes y2 = offset + random.randrange( 0, int(window_height - game_images['sea_level'].get_height() - 1.2 * offset)) pipeX = window_width + 10 y1 = pipeHeight - y2 + offset pipe = [ # upper Pipe {'x': pipeX, 'y': -y1}, # lower Pipe {'x': pipeX, 'y': y2} ] return pipe",
"e": 6206,
"s": 5724,
"text": null
},
{
"code": null,
"e": 6324,
"s": 6206,
"text": "Step 5: Now we create a GameOver() function which represents whether the bird has hit the pipes or fall into the sea."
},
{
"code": null,
"e": 6658,
"s": 6324,
"text": "According to my thought, three conditions lead to a situation of the game over. if the difference between our elevation and a certain height is less than vertical it means the bird has crossed its boundaries resulting in a game over and if the bird hits any of the lower and upper pip then this will also lead to game over condition."
},
{
"code": null,
"e": 6666,
"s": 6658,
"text": "Python3"
},
{
"code": "# Checking if bird is above the sealevel.def isGameOver(horizontal, vertical, up_pipes, down_pipes): if vertical > elevation - 25 or vertical < 0: return True # Checking if bird hits the upper pipe or not for pipe in up_pipes: pipeHeight = game_images['pipeimage'][0].get_height() if(vertical < pipeHeight + pipe['y'] and abs(horizontal - pipe['x']) < game_images['pipeimage'][0].get_width()): return True # Checking if bird hits the lower pipe or not for pipe in down_pipes: if (vertical + game_images['flappybird'].get_height() > pipe['y']) and abs(horizontal - pipe['x']) < game_images['pipeimage'][0].get_width(): return True return False",
"e": 7415,
"s": 6666,
"text": null
},
{
"code": null,
"e": 7516,
"s": 7415,
"text": "Step 6: Now we will be creating our main function (flappygame()) that will do the following things:"
},
{
"code": null,
"e": 7976,
"s": 7516,
"text": "Initialize the variables and creating two pipes by createPipe() function. Create two lists first is of lower pipes and the other is of lower pipes. Defining the bird velocity, minimum bird velocity, maximum bird velocity, and pipes velocity. Handle the key events using pygame.event.get() and checking for the game is over or not if it is over return from the function. Updating the score and blit game images such as background, pipe, and bird on the window."
},
{
"code": null,
"e": 7984,
"s": 7976,
"text": "Python3"
},
{
"code": "def flappygame(): your_score = 0 horizontal = int(window_width/5) vertical = int(window_width/2) ground = 0 mytempheight = 100 # Generating two pipes for blitting on window first_pipe = createPipe() second_pipe = createPipe() # List containing lower pipes down_pipes = [ {'x': window_width+300-mytempheight, 'y': first_pipe[1]['y']}, {'x': window_width+300-mytempheight+(window_width/2), 'y': second_pipe[1]['y']}, ] # List Containing upper pipes up_pipes = [ {'x': window_width+300-mytempheight, 'y': first_pipe[0]['y']}, {'x': window_width+200-mytempheight+(window_width/2), 'y': second_pipe[0]['y']}, ] pipeVelX = -4 #pipe velocity along x bird_velocity_y = -9 # bird velocity bird_Max_Vel_Y = 10 bird_Min_Vel_Y = -8 birdAccY = 1 # velocity while flapping bird_flap_velocity = -8 # It is true only when the bird is flapping bird_flapped = False while True: # Handling the key pressing events for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): pygame.quit() sys.exit() if event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP): if vertical > 0: bird_velocity_y = bird_flap_velocity bird_flapped = True # This function will return true if the flappybird is crashed game_over = isGameOver(horizontal, vertical, up_pipes, down_pipes) if game_over: return # check for your_score playerMidPos = horizontal + game_images['flappybird'].get_width()/2 for pipe in up_pipes: pipeMidPos = pipe['x'] + game_images['pipeimage'][0].get_width()/2 if pipeMidPos <= playerMidPos < pipeMidPos + 4: # Printing the score your_score += 1 print(f\"Your your_score is {your_score}\") if bird_velocity_y < bird_Max_Vel_Y and not bird_flapped: bird_velocity_y += birdAccY if bird_flapped: bird_flapped = False playerHeight = game_images['flappybird'].get_height() vertical = vertical + min(bird_velocity_y, elevation - vertical - playerHeight) # move pipes to the left for upperPipe, lowerPipe in zip(up_pipes, down_pipes): upperPipe['x'] += pipeVelX lowerPipe['x'] += pipeVelX # Add a new pipe when the first is about # to cross the leftmost part of the screen if 0 < up_pipes[0]['x'] < 5: newpipe = createPipe() up_pipes.append(newpipe[0]) down_pipes.append(newpipe[1]) # if the pipe is out of the screen, remove it if up_pipes[0]['x'] < -game_images['pipeimage'][0].get_width(): up_pipes.pop(0) down_pipes.pop(0) # Lets blit our game images now window.blit(game_images['background'], (0, 0)) for upperPipe, lowerPipe in zip(up_pipes, down_pipes): window.blit(game_images['pipeimage'][0], (upperPipe['x'], upperPipe['y'])) window.blit(game_images['pipeimage'][1], (lowerPipe['x'], lowerPipe['y'])) window.blit(game_images['sea_level'], (ground, elevation)) window.blit(game_images['flappybird'], (horizontal, vertical)) # Fetching the digits of score. numbers = [int(x) for x in list(str(your_score))] width = 0 # finding the width of score images from numbers. for num in numbers: width += game_images['scoreimages'][num].get_width() Xoffset = (window_width - width)/1.1 # Blitting the images on the window. for num in numbers: window.blit(game_images['scoreimages'][num], (Xoffset, window_width*0.02)) Xoffset += game_images['scoreimages'][num].get_width() # Refreshing the game window and displaying the score. pygame.display.update() # Set the framepersecond framepersecond_clock.tick(framepersecond)",
"e": 12219,
"s": 7984,
"text": null
},
{
"code": null,
"e": 12227,
"s": 12219,
"text": "Python3"
},
{
"code": "# Import moduleimport randomimport sysimport pygamefrom pygame.locals import * # All the Game Variableswindow_width = 600window_height = 499 # set height and width of windowwindow = pygame.display.set_mode((window_width, window_height))elevation = window_height * 0.8game_images = {}framepersecond = 32pipeimage = 'images/pipe.png'background_image = 'images/background.jpg'birdplayer_image = 'images/bird.png'sealevel_image = 'images/base.jfif' def flappygame(): your_score = 0 horizontal = int(window_width/5) vertical = int(window_width/2) ground = 0 mytempheight = 100 # Generating two pipes for blitting on window first_pipe = createPipe() second_pipe = createPipe() # List containing lower pipes down_pipes = [ {'x': window_width+300-mytempheight, 'y': first_pipe[1]['y']}, {'x': window_width+300-mytempheight+(window_width/2), 'y': second_pipe[1]['y']}, ] # List Containing upper pipes up_pipes = [ {'x': window_width+300-mytempheight, 'y': first_pipe[0]['y']}, {'x': window_width+200-mytempheight+(window_width/2), 'y': second_pipe[0]['y']}, ] # pipe velocity along x pipeVelX = -4 # bird velocity bird_velocity_y = -9 bird_Max_Vel_Y = 10 bird_Min_Vel_Y = -8 birdAccY = 1 bird_flap_velocity = -8 bird_flapped = False while True: for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): pygame.quit() sys.exit() if event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP): if vertical > 0: bird_velocity_y = bird_flap_velocity bird_flapped = True # This function will return true # if the flappybird is crashed game_over = isGameOver(horizontal, vertical, up_pipes, down_pipes) if game_over: return # check for your_score playerMidPos = horizontal + game_images['flappybird'].get_width()/2 for pipe in up_pipes: pipeMidPos = pipe['x'] + game_images['pipeimage'][0].get_width()/2 if pipeMidPos <= playerMidPos < pipeMidPos + 4: your_score += 1 print(f\"Your your_score is {your_score}\") if bird_velocity_y < bird_Max_Vel_Y and not bird_flapped: bird_velocity_y += birdAccY if bird_flapped: bird_flapped = False playerHeight = game_images['flappybird'].get_height() vertical = vertical + \\ min(bird_velocity_y, elevation - vertical - playerHeight) # move pipes to the left for upperPipe, lowerPipe in zip(up_pipes, down_pipes): upperPipe['x'] += pipeVelX lowerPipe['x'] += pipeVelX # Add a new pipe when the first is # about to cross the leftmost part of the screen if 0 < up_pipes[0]['x'] < 5: newpipe = createPipe() up_pipes.append(newpipe[0]) down_pipes.append(newpipe[1]) # if the pipe is out of the screen, remove it if up_pipes[0]['x'] < -game_images['pipeimage'][0].get_width(): up_pipes.pop(0) down_pipes.pop(0) # Lets blit our game images now window.blit(game_images['background'], (0, 0)) for upperPipe, lowerPipe in zip(up_pipes, down_pipes): window.blit(game_images['pipeimage'][0], (upperPipe['x'], upperPipe['y'])) window.blit(game_images['pipeimage'][1], (lowerPipe['x'], lowerPipe['y'])) window.blit(game_images['sea_level'], (ground, elevation)) window.blit(game_images['flappybird'], (horizontal, vertical)) # Fetching the digits of score. numbers = [int(x) for x in list(str(your_score))] width = 0 # finding the width of score images from numbers. for num in numbers: width += game_images['scoreimages'][num].get_width() Xoffset = (window_width - width)/1.1 # Blitting the images on the window. for num in numbers: window.blit(game_images['scoreimages'][num], (Xoffset, window_width*0.02)) Xoffset += game_images['scoreimages'][num].get_width() # Refreshing the game window and displaying the score. pygame.display.update() framepersecond_clock.tick(framepersecond) def isGameOver(horizontal, vertical, up_pipes, down_pipes): if vertical > elevation - 25 or vertical < 0: return True for pipe in up_pipes: pipeHeight = game_images['pipeimage'][0].get_height() if(vertical < pipeHeight + pipe['y'] and\\ abs(horizontal - pipe['x']) < game_images['pipeimage'][0].get_width()): return True for pipe in down_pipes: if (vertical + game_images['flappybird'].get_height() > pipe['y']) and\\ abs(horizontal - pipe['x']) < game_images['pipeimage'][0].get_width(): return True return False def createPipe(): offset = window_height/3 pipeHeight = game_images['pipeimage'][0].get_height() y2 = offset + \\ random.randrange( 0, int(window_height - game_images['sea_level'].get_height() - 1.2 * offset)) pipeX = window_width + 10 y1 = pipeHeight - y2 + offset pipe = [ # upper Pipe {'x': pipeX, 'y': -y1}, # lower Pipe {'x': pipeX, 'y': y2} ] return pipe # program where the game startsif __name__ == \"__main__\": # For initializing modules of pygame library pygame.init() framepersecond_clock = pygame.time.Clock() # Sets the title on top of game window pygame.display.set_caption('Flappy Bird Game') # Load all the images which we will use in the game # images for displaying score game_images['scoreimages'] = ( pygame.image.load('images/0.png').convert_alpha(), pygame.image.load('images/1.png').convert_alpha(), pygame.image.load('images/2.png').convert_alpha(), pygame.image.load('images/3.png').convert_alpha(), pygame.image.load('images/4.png').convert_alpha(), pygame.image.load('images/5.png').convert_alpha(), pygame.image.load('images/6.png').convert_alpha(), pygame.image.load('images/7.png').convert_alpha(), pygame.image.load('images/8.png').convert_alpha(), pygame.image.load('images/9.png').convert_alpha() ) game_images['flappybird'] = pygame.image.load( birdplayer_image).convert_alpha() game_images['sea_level'] = pygame.image.load( sealevel_image).convert_alpha() game_images['background'] = pygame.image.load( background_image).convert_alpha() game_images['pipeimage'] = (pygame.transform.rotate(pygame.image.load( pipeimage).convert_alpha(), 180), pygame.image.load( pipeimage).convert_alpha()) print(\"WELCOME TO THE FLAPPY BIRD GAME\") print(\"Press space or enter to start the game\") # Here starts the main game while True: # sets the coordinates of flappy bird horizontal = int(window_width/5) vertical = int( (window_height - game_images['flappybird'].get_height())/2) ground = 0 while True: for event in pygame.event.get(): # if user clicks on cross button, close the game if event.type == QUIT or (event.type == KEYDOWN and \\ event.key == K_ESCAPE): pygame.quit() sys.exit() # If the user presses space or # up key, start the game for them elif event.type == KEYDOWN and (event.key == K_SPACE or\\ event.key == K_UP): flappygame() # if user doesn't press anykey Nothing happen else: window.blit(game_images['background'], (0, 0)) window.blit(game_images['flappybird'], (horizontal, vertical)) window.blit(game_images['sea_level'], (ground, elevation)) pygame.display.update() framepersecond_clock.tick(framepersecond)",
"e": 20634,
"s": 12227,
"text": null
},
{
"code": null,
"e": 20642,
"s": 20634,
"text": "Output:"
},
{
"code": null,
"e": 20649,
"s": 20642,
"text": "Picked"
},
{
"code": null,
"e": 20665,
"s": 20649,
"text": "Python-projects"
},
{
"code": null,
"e": 20679,
"s": 20665,
"text": "Python-PyGame"
},
{
"code": null,
"e": 20686,
"s": 20679,
"text": "Python"
},
{
"code": null,
"e": 20784,
"s": 20686,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 20816,
"s": 20784,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 20843,
"s": 20816,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 20874,
"s": 20843,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 20897,
"s": 20874,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 20918,
"s": 20897,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 20974,
"s": 20918,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 21016,
"s": 20974,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 21058,
"s": 21016,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 21097,
"s": 21058,
"text": "Python | Get unique values from a list"
}
] |
JavaFX | Point3D Class
|
13 Aug, 2021
Point3D class is a part of JavaFX. This class defines a 3-dimensional point in a 3D space. The Point3D class represents a 3D point by its x, y, z coordinates.
Constructor of the class is:
Point3D(double x, double y, double z): Creates a Point3D object using the specified coordinates.
Commonly Used Methods:
Below programs will illustrate the use of the Point3D class:
1. Java program to create a Point3D object and display its coordinates and find its distance from the origin: In this program we create a Point3D object named point3d_1 by passing its x, y, z coordinates as arguments. We get the x, y, z argument using the getX(), getY(), getZ() function and display it. We also calculate the distance of the point from the origin and also display it.
Java
// Java program to create a point 3D// object and display its coordinates// and find its distance from originimport javafx.geometry.Point3D; public class Point3D_1 { // Main Method public static void main(String args[]) { // Create a point3D object Point3D point3d_1 = new Point3D(20.0f, 50.0f, 70.0f); double x, y, z; // get the coordinates of the point x = point3d_1.getX(); y = point3d_1.getY(); z = point3d_1.getZ(); // display the coordinates of the point System.out.println("x coordinate = " + x + ", y coordinate = " + y + ", z coordinate = " + z); // print its distance from origin System.out.println("Distance From Origin = " + point3d_1.distance(0, 0, 0)); }}
Output:
x coordinate = 20.0, y coordinate = 50.0, z coordinate = 70.0
Distance From Origin = 88.31760866327846
2. Java program to create 3 Point3D objects and display their coordinates and distance from the origin and check which of the 3 points are similar and their distances between two points: In this program we create 3 Point3D objects named point3d_1, point3d_2, point3d_3 by passing its x, y, z coordinates as arguments. we get the x, y, z argument using the getX(), getY(), getZ() function and display it. We also calculate the distance of the point from the origin and also display it for each of the three points. We also display whether any two points are equal or not using equals() function and also display the distance between two points using the distance function.
Java
// Java program to create 3 Point3D objects and// display their coordinates and distance from// origin and check which of the 3 points are// similar and their distances between two pointsimport javafx.geometry.Point3D; public class Point3D_2 { // Main Method public static void main(String args[]) { // create three point3D objects Point3D point3d_1 = new Point3D(20.0f, 50.0f, 70.0f); Point3D point3d_2 = new Point3D(20.0f, 50.0f, 70.0f); Point3D point3d_3 = new Point3D(200.0f, 20.0f, 90.0f); // display the coordinates of the 3 points display(point3d_1); display(point3d_2); display(point3d_3); // check whether any point is equal to other or not System.out.println("Point 1 equals point 2 = " + point3d_1.equals(point3d_2)); System.out.println("Point 2 equals point 3 = " + point3d_2.equals(point3d_3)); System.out.println("Point 3 equals point 1 = " + point3d_3.equals(point3d_1)); // distance between two points System.out.println("Distance between point 1 and point 2 = " + point3d_1.distance(point3d_2)); System.out.println("Distance between point 2 and point 3 = " + point3d_2.distance(point3d_3)); System.out.println("Distance between point 3 and point 1 = " + point3d_3.distance(point3d_1)); } // Display Method public static void display(Point3D point3d) { double x, y, z; // get the coordinates of the point x = point3d.getX(); y = point3d.getY(); z = point3d.getZ(); // display the coordinates of the point System.out.println("x coordinate = " + x + ", y coordinate = " + y + ", z coordinate = " + z); // print its distance from origin System.out.println("Distance From Origin = " + point3d.distance(0, 0, 0)); }}
Output:
x coordinate = 20.0, y coordinate = 50.0, z coordinate = 70.0
Distance From Origin = 88.31760866327846
x coordinate = 20.0, y coordinate = 50.0, z coordinate = 70.0
Distance From Origin = 88.31760866327846
x coordinate = 200.0, y coordinate = 20.0, z coordinate = 90.0
Distance From Origin = 220.22715545545242
Point 1 equals point 2 = true
Point 2 equals point 3 = false
Point 3 equals point 1 = false
Distance between point 1 and point 2 = 0.0
Distance between point 2 and point 3 = 183.5755975068582
Distance between point 3 and point 1 = 183.5755975068582
Note: The above programs might not run in an online IDE. Please use an offline compiler.
Reference: https://docs.oracle.com/javafx/2/api/javafx/geometry/Point3D.html
simmytarika5
JavaFX
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Aug, 2021"
},
{
"code": null,
"e": 187,
"s": 28,
"text": "Point3D class is a part of JavaFX. This class defines a 3-dimensional point in a 3D space. The Point3D class represents a 3D point by its x, y, z coordinates."
},
{
"code": null,
"e": 217,
"s": 187,
"text": "Constructor of the class is: "
},
{
"code": null,
"e": 314,
"s": 217,
"text": "Point3D(double x, double y, double z): Creates a Point3D object using the specified coordinates."
},
{
"code": null,
"e": 338,
"s": 314,
"text": "Commonly Used Methods: "
},
{
"code": null,
"e": 401,
"s": 338,
"text": "Below programs will illustrate the use of the Point3D class: "
},
{
"code": null,
"e": 786,
"s": 401,
"text": "1. Java program to create a Point3D object and display its coordinates and find its distance from the origin: In this program we create a Point3D object named point3d_1 by passing its x, y, z coordinates as arguments. We get the x, y, z argument using the getX(), getY(), getZ() function and display it. We also calculate the distance of the point from the origin and also display it."
},
{
"code": null,
"e": 791,
"s": 786,
"text": "Java"
},
{
"code": "// Java program to create a point 3D// object and display its coordinates// and find its distance from originimport javafx.geometry.Point3D; public class Point3D_1 { // Main Method public static void main(String args[]) { // Create a point3D object Point3D point3d_1 = new Point3D(20.0f, 50.0f, 70.0f); double x, y, z; // get the coordinates of the point x = point3d_1.getX(); y = point3d_1.getY(); z = point3d_1.getZ(); // display the coordinates of the point System.out.println(\"x coordinate = \" + x + \", y coordinate = \" + y + \", z coordinate = \" + z); // print its distance from origin System.out.println(\"Distance From Origin = \" + point3d_1.distance(0, 0, 0)); }}",
"e": 1630,
"s": 791,
"text": null
},
{
"code": null,
"e": 1639,
"s": 1630,
"text": "Output: "
},
{
"code": null,
"e": 1742,
"s": 1639,
"text": "x coordinate = 20.0, y coordinate = 50.0, z coordinate = 70.0\nDistance From Origin = 88.31760866327846"
},
{
"code": null,
"e": 2414,
"s": 1742,
"text": "2. Java program to create 3 Point3D objects and display their coordinates and distance from the origin and check which of the 3 points are similar and their distances between two points: In this program we create 3 Point3D objects named point3d_1, point3d_2, point3d_3 by passing its x, y, z coordinates as arguments. we get the x, y, z argument using the getX(), getY(), getZ() function and display it. We also calculate the distance of the point from the origin and also display it for each of the three points. We also display whether any two points are equal or not using equals() function and also display the distance between two points using the distance function."
},
{
"code": null,
"e": 2419,
"s": 2414,
"text": "Java"
},
{
"code": "// Java program to create 3 Point3D objects and// display their coordinates and distance from// origin and check which of the 3 points are// similar and their distances between two pointsimport javafx.geometry.Point3D; public class Point3D_2 { // Main Method public static void main(String args[]) { // create three point3D objects Point3D point3d_1 = new Point3D(20.0f, 50.0f, 70.0f); Point3D point3d_2 = new Point3D(20.0f, 50.0f, 70.0f); Point3D point3d_3 = new Point3D(200.0f, 20.0f, 90.0f); // display the coordinates of the 3 points display(point3d_1); display(point3d_2); display(point3d_3); // check whether any point is equal to other or not System.out.println(\"Point 1 equals point 2 = \" + point3d_1.equals(point3d_2)); System.out.println(\"Point 2 equals point 3 = \" + point3d_2.equals(point3d_3)); System.out.println(\"Point 3 equals point 1 = \" + point3d_3.equals(point3d_1)); // distance between two points System.out.println(\"Distance between point 1 and point 2 = \" + point3d_1.distance(point3d_2)); System.out.println(\"Distance between point 2 and point 3 = \" + point3d_2.distance(point3d_3)); System.out.println(\"Distance between point 3 and point 1 = \" + point3d_3.distance(point3d_1)); } // Display Method public static void display(Point3D point3d) { double x, y, z; // get the coordinates of the point x = point3d.getX(); y = point3d.getY(); z = point3d.getZ(); // display the coordinates of the point System.out.println(\"x coordinate = \" + x + \", y coordinate = \" + y + \", z coordinate = \" + z); // print its distance from origin System.out.println(\"Distance From Origin = \" + point3d.distance(0, 0, 0)); }}",
"e": 4506,
"s": 2419,
"text": null
},
{
"code": null,
"e": 4515,
"s": 4506,
"text": "Output: "
},
{
"code": null,
"e": 5075,
"s": 4515,
"text": "x coordinate = 20.0, y coordinate = 50.0, z coordinate = 70.0\nDistance From Origin = 88.31760866327846\nx coordinate = 20.0, y coordinate = 50.0, z coordinate = 70.0\nDistance From Origin = 88.31760866327846\nx coordinate = 200.0, y coordinate = 20.0, z coordinate = 90.0\nDistance From Origin = 220.22715545545242\nPoint 1 equals point 2 = true\nPoint 2 equals point 3 = false\nPoint 3 equals point 1 = false\nDistance between point 1 and point 2 = 0.0\nDistance between point 2 and point 3 = 183.5755975068582\nDistance between point 3 and point 1 = 183.5755975068582"
},
{
"code": null,
"e": 5164,
"s": 5075,
"text": "Note: The above programs might not run in an online IDE. Please use an offline compiler."
},
{
"code": null,
"e": 5242,
"s": 5164,
"text": "Reference: https://docs.oracle.com/javafx/2/api/javafx/geometry/Point3D.html "
},
{
"code": null,
"e": 5255,
"s": 5242,
"text": "simmytarika5"
},
{
"code": null,
"e": 5262,
"s": 5255,
"text": "JavaFX"
},
{
"code": null,
"e": 5267,
"s": 5262,
"text": "Java"
},
{
"code": null,
"e": 5281,
"s": 5267,
"text": "Java Programs"
},
{
"code": null,
"e": 5286,
"s": 5281,
"text": "Java"
},
{
"code": null,
"e": 5384,
"s": 5286,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5399,
"s": 5384,
"text": "Stream In Java"
},
{
"code": null,
"e": 5420,
"s": 5399,
"text": "Introduction to Java"
},
{
"code": null,
"e": 5441,
"s": 5420,
"text": "Constructors in Java"
},
{
"code": null,
"e": 5460,
"s": 5441,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 5477,
"s": 5460,
"text": "Generics in Java"
},
{
"code": null,
"e": 5503,
"s": 5477,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 5537,
"s": 5503,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 5584,
"s": 5537,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 5622,
"s": 5584,
"text": "Factory method design pattern in Java"
}
] |
Insertion at Specific Position in a Circular Doubly Linked List
|
23 Jun, 2022
Prerequisite:
Insert Element Circular Doubly Linked List.
Convert an Array to a Circular Doubly Linked List.
Given the start pointer pointing to the start of a Circular Doubly Linked List, an element and a position. The task is to insert the element at the specified position in the given Circular Doubly Linked List.
The idea is to count the total number of elements in the list. Check whether the specified location is valid or not, i.e. location is within the count.
If location is valid:
Create a newNode in the memory.Traverse in the list using a temporary pointer(temp) till the node just before the given position at which a new node is needed to be inserted.Insert the new node by performing below operations: Assign newNode->next = temp->nextAssign newNode->prev as temp->nextAssign temp->next as newNodeAssign (temp->next)->prev as newNode->next
Create a newNode in the memory.
Traverse in the list using a temporary pointer(temp) till the node just before the given position at which a new node is needed to be inserted.
Insert the new node by performing below operations: Assign newNode->next = temp->nextAssign newNode->prev as temp->nextAssign temp->next as newNodeAssign (temp->next)->prev as newNode->next
Assign newNode->next = temp->next
Assign newNode->prev as temp->next
Assign temp->next as newNode
Assign (temp->next)->prev as newNode->next
Below is the implementation of the above idea:
C++
Java
Python3
C#
Javascript
// CPP program to convert insert an element at a specific// position in a circular doubly linked list #include <bits/stdc++.h>using namespace std; // Doubly linked list nodestruct node { int data; struct node* next; struct node* prev;}; // Utility function to create a node in memorystruct node* getNode(){ return ((struct node*)malloc(sizeof(struct node)));} // Function to display the listint displayList(struct node* temp){ struct node* t = temp; if (temp == NULL) return 0; else { cout << "The list is: "; while (temp->next != t) { cout << temp->data << " "; temp = temp->next; } cout << temp->data << endl; return 1; }} // Function to count number of// elements in the listint countList(struct node* start){ // Declare temp pointer to // traverse the list struct node* temp = start; // Variable to store the count int count = 0; // Iterate the list and increment the count while (temp->next != start) { temp = temp->next; count++; } // As the list is circular, increment the // counter at last count++; return count;} // Function to insert a node at a given position// in the circular doubly linked listbool insertAtLocation(struct node* start, int data, int loc){ // Declare two pointers struct node *temp, *newNode; int i, count; // Create a new node in memory newNode = getNode(); // Point temp to start temp = start; // count of total elements in the list count = countList(start); // If list is empty or the position is // not valid, return false if (temp == NULL || count < loc) return false; else { // Assign the data newNode->data = data; // Iterate till the loc for (i = 1; i < loc - 1; i++) { temp = temp->next; } // See in Image, circle 1 newNode->next = temp->next; // See in Image, Circle 2 (temp->next)->prev = newNode; // See in Image, Circle 3 temp->next = newNode; // See in Image, Circle 4 newNode->prev = temp; return true; } return false;} // Function to create circular doubly linked list// from array elementsvoid createList(int arr[], int n, struct node** start){ // Declare newNode and temporary pointer struct node *newNode, *temp; int i; // Iterate the loop until array length for (i = 0; i < n; i++) { // Create new node newNode = getNode(); // Assign the array data newNode->data = arr[i]; // If it is first element // Put that node prev and next as start // as it is circular if (i == 0) { *start = newNode; newNode->prev = *start; newNode->next = *start; } else { // Find the last node temp = (*start)->prev; // Add the last node to make them // in circular fashion temp->next = newNode; newNode->next = *start; newNode->prev = temp; temp = *start; temp->prev = newNode; } }} // Driver Codeint main(){ // Array elements to create // circular doubly linked list int arr[] = { 1, 2, 3, 4, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); // Start Pointer struct node* start = NULL; // Create the List createList(arr, n, &start); // Display the list before insertion displayList(start); // Inserting 8 at 3rd position insertAtLocation(start, 8, 3); // Display the list after insertion displayList(start); return 0;}
// Java program to convert insert// an element at a specific position// in a circular doubly linked listing,// end and middleclass GFG{ // Doubly linked list nodestatic class node{ int data; node next; node prev;}; // Utility function to create a node in memorystatic node getNode(){ return new node();} // Function to display the liststatic int displayList( node temp){ node t = temp; if (temp == null) return 0; else { System.out.println( "The list is: "); while (temp.next != t) { System.out.print( temp.data + " "); temp = temp.next; } System.out.println( temp.data ); return 1; }} // Function to count number of// elements in the liststatic int countList( node start){ // Declare temp pointer to // traverse the list node temp = start; // Variable to store the count int count = 0; // Iterate the list and // increment the count while (temp.next != start) { temp = temp.next; count++; } // As the list is circular, increment // the counter at last count++; return count;} // Function to insert a node at// a given position in the// circular doubly linked liststatic node insertAtLocation( node start, int data, int loc){ // Declare two pointers node temp, newNode; int i, count; // Create a new node in memory newNode = getNode(); // Point temp to start temp = start; // count of total elements in the list count = countList(start); // If list is empty or the position is // not valid, return false if (temp == null || count < loc) return start; else { // Assign the data newNode.data = data; // Iterate till the loc for (i = 1; i < loc - 1; i++) { temp = temp.next; } // See in Image, circle 1 newNode.next = temp.next; // See in Image, Circle 2 (temp.next).prev = newNode; // See in Image, Circle 3 temp.next = newNode; // See in Image, Circle 4 newNode.prev = temp; return start; } } // Function to create circular doubly // linked list from array elementsstatic node createList(int arr[], int n, node start){ // Declare newNode and temporary pointer node newNode, temp; int i; // Iterate the loop until array length for (i = 0; i < n; i++) { // Create new node newNode = getNode(); // Assign the array data newNode.data = arr[i]; // If it is first element // Put that node prev and next as start // as it is circular if (i == 0) { start = newNode; newNode.prev = start; newNode.next = start; } else { // Find the last node temp = (start).prev; // Add the last node to make them // in circular fashion temp.next = newNode; newNode.next = start; newNode.prev = temp; temp = start; temp.prev = newNode; } } return start;} // Driver Codepublic static void main(String args[]){ // Array elements to create // circular doubly linked list int arr[] = { 1, 2, 3, 4, 5, 6 }; int n = arr.length; // Start Pointer node start = null; // Create the List start = createList(arr, n, start); // Display the list before insertion displayList(start); // Inserting 8 at 3rd position start = insertAtLocation(start, 8, 3); // Display the list after insertion displayList(start);}} // This code is contributed by Arnab Kundu
# Python3 program to insert an element# at a specific position in a# circular doubly linked list # Node of the doubly linked listclass Node: def __init__(self, data): self.data = data self.prev = None self.next = None # Utility function to create# a node in memorydef getNode(): return (Node(0)) # Function to display the listdef displayList(temp): t = temp if (temp == None): return 0 else : print("The list is: ", end = " ") while (temp.next != t): print( temp.data, end = " ") temp = temp.next print(temp.data ) return 1 # Function to count number of# elements in the listdef countList( start): # Declare temp pointer to # traverse the list temp = start # Variable to store the count count = 0 # Iterate the list and increment the count while (temp.next != start) : temp = temp.next count = count + 1 # As the list is circular, increment the # counter at last count = count + 1 return count # Function to insert a node at a given position# in the circular doubly linked listdef insertAtLocation(start, data, loc): # Declare two pointers temp = None newNode = None i = 0 count = 0 # Create a new node in memory newNode = getNode() # Point temp to start temp = start # count of total elements in the list count = countList(start) # If list is empty or the position is # not valid, return False if (temp == None or count < loc): return start else : # Assign the data newNode.data = data # Iterate till the loc i = 1; while(i < loc - 1) : temp = temp.next i = i + 1 # See in Image, circle 1 newNode.next = temp.next # See in Image, Circle 2 (temp.next).prev = newNode # See in Image, Circle 3 temp.next = newNode # See in Image, Circle 4 newNode.prev = temp return start return start # Function to create circular# doubly linked list from array elementsdef createList(arr, n, start): # Declare newNode and temporary pointer newNode = None temp = None i = 0 # Iterate the loop until array length while (i < n) : # Create new node newNode = getNode() # Assign the array data newNode.data = arr[i] # If it is first element # Put that node prev and next as start # as it is circular if (i == 0) : start = newNode newNode.prev = start newNode.next = start else : # Find the last node temp = (start).prev # Add the last node to make them # in circular fashion temp.next = newNode newNode.next = start newNode.prev = temp temp = start temp.prev = newNode i = i + 1; return start # Driver Codeif __name__ == "__main__": # Array elements to create # circular doubly linked list arr = [ 1, 2, 3, 4, 5, 6] n = len(arr) # Start Pointer start = None # Create the List start = createList(arr, n, start) # Display the list before insertion displayList(start) # Inserting 8 at 3rd position start = insertAtLocation(start, 8, 3) # Display the list after insertion displayList(start) # This code is contributed by Arnab Kundu
// C# program to convert insert// an element at a specific position// in a circular doubly linked listing,// end and middleusing System; class GFG{ // Doubly linked list nodepublic class node{ public int data; public node next; public node prev;}; // Utility function to create a node in memorystatic node getNode(){ return new node();} // Function to display the liststatic int displayList( node temp){ node t = temp; if (temp == null) return 0; else { Console.WriteLine( "The list is: "); while (temp.next != t) { Console.Write( temp.data + " "); temp = temp.next; } Console.WriteLine( temp.data ); return 1; }} // Function to count number of// elements in the liststatic int countList( node start){ // Declare temp pointer to // traverse the list node temp = start; // Variable to store the count int count = 0; // Iterate the list and // increment the count while (temp.next != start) { temp = temp.next; count++; } // As the list is circular, increment // the counter at last count++; return count;} // Function to insert a node at// a given position in the// circular doubly linked liststatic node insertAtLocation( node start, int data, int loc){ // Declare two pointers node temp, newNode; int i, count; // Create a new node in memory newNode = getNode(); // Point temp to start temp = start; // count of total elements in the list count = countList(start); // If list is empty or the position is // not valid, return false if (temp == null || count < loc) return start; else { // Assign the data newNode.data = data; // Iterate till the loc for (i = 1; i < loc - 1; i++) { temp = temp.next; } // See in Image, circle 1 newNode.next = temp.next; // See in Image, Circle 2 (temp.next).prev = newNode; // See in Image, Circle 3 temp.next = newNode; // See in Image, Circle 4 newNode.prev = temp; return start; } } // Function to create circular doubly// linked list from array elementsstatic node createList(int []arr, int n, node start){ // Declare newNode and temporary pointer node newNode, temp; int i; // Iterate the loop until array length for (i = 0; i < n; i++) { // Create new node newNode = getNode(); // Assign the array data newNode.data = arr[i]; // If it is first element // Put that node prev and next as start // as it is circular if (i == 0) { start = newNode; newNode.prev = start; newNode.next = start; } else { // Find the last node temp = (start).prev; // Add the last node to make them // in circular fashion temp.next = newNode; newNode.next = start; newNode.prev = temp; temp = start; temp.prev = newNode; } } return start;} // Driver Codepublic static void Main(){ // Array elements to create // circular doubly linked list int []arr = { 1, 2, 3, 4, 5, 6 }; int n = arr.Length; // Start Pointer node start = null; // Create the List start = createList(arr, n, start); // Display the list before insertion displayList(start); // Inserting 8 at 3rd position start = insertAtLocation(start, 8, 3); // Display the list after insertion displayList(start);}} /* This code contributed by PrinciRaj1992 */
<script> // JavaScript program to convert insert // an element at a specific position // in a circular doubly linked listing, // end and middle // Doubly linked list node class node { constructor() { this.data = 0; this.next = null; this.prev = null; } } // Utility function to create a node in memory function getNode() { return new node(); } // Function to display the list function displayList(temp) { var t = temp; if (temp == null) return 0; else { document.write("The list is: "); while (temp.next != t) { document.write(temp.data + " "); temp = temp.next; } document.write(temp.data + "<br>"); return 1; } } // Function to count number of // elements in the list function countList(start) { // Declare temp pointer to // traverse the list var temp = start; // Variable to store the count var count = 0; // Iterate the list and // increment the count while (temp.next != start) { temp = temp.next; count++; } // As the list is circular, increment // the counter at last count++; return count; } // Function to insert a node at // a given position in the // circular doubly linked list function insertAtLocation(start, data, loc) { // Declare two pointers var temp, newNode; var i, count; // Create a new node in memory newNode = getNode(); // Point temp to start temp = start; // count of total elements in the list count = countList(start); // If list is empty or the position is // not valid, return false if (temp == null || count < loc) return start; else { // Assign the data newNode.data = data; // Iterate till the loc for (i = 1; i < loc - 1; i++) { temp = temp.next; } // See in Image, circle 1 newNode.next = temp.next; // See in Image, Circle 2 temp.next.prev = newNode; // See in Image, Circle 3 temp.next = newNode; // See in Image, Circle 4 newNode.prev = temp; return start; } } // Function to create circular doubly // linked list from array elements function createList(arr, n, start) { // Declare newNode and temporary pointer var newNode, temp; var i; // Iterate the loop until array length for (i = 0; i < n; i++) { // Create new node newNode = getNode(); // Assign the array data newNode.data = arr[i]; // If it is first element // Put that node prev and next as start // as it is circular if (i == 0) { start = newNode; newNode.prev = start; newNode.next = start; } else { // Find the last node temp = start.prev; // Add the last node to make them // in circular fashion temp.next = newNode; newNode.next = start; newNode.prev = temp; temp = start; temp.prev = newNode; } } return start; } // Driver Code // Array elements to create // circular doubly linked list var arr = [1, 2, 3, 4, 5, 6]; var n = arr.length; // Start Pointer var start = null; // Create the List start = createList(arr, n, start); // Display the list before insertion displayList(start); // Inserting 8 at 3rd position start = insertAtLocation(start, 8, 3); // Display the list after insertion displayList(start); // This code is contributed by rdtank. </script>
The list is: 1 2 3 4 5 6
The list is: 1 2 8 3 4 5 6
Time Complexity: O(n) => for counting the list as we are using a loop to traverse linearly, O(n) => Inserting the elements, as we are using a loop to traverse linearly. So, total complexity is O(n + n) = O(n). Where n is the number of nodes in the linked list.
Auxiliary Space: O(1), as we are not using any extra space.
andrew1234
princiraj1992
nidhi_biet
rdtank
sagar0719kumar
abhishek0719kadiyan
rohan07
circular linked list
doubly linked list
Linked Lists
Traversal
Advanced Data Structure
Linked List
Linked List
Traversal
circular linked list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Overview of Data Structures | Set 3 (Graph, Trie, Segment Tree and Suffix Tree)
Ordered Set and GNU C++ PBDS
2-3 Trees | (Search, Insert and Deletion)
Extendible Hashing (Dynamic approach to DBMS)
Segment Tree | Set 2 (Range Minimum Query)
Linked List | Set 1 (Introduction)
Linked List | Set 2 (Inserting a node)
Reverse a linked list
Stack Data Structure (Introduction and Program)
Linked List | Set 3 (Deleting a node)
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 67,
"s": 52,
"text": "Prerequisite: "
},
{
"code": null,
"e": 111,
"s": 67,
"text": "Insert Element Circular Doubly Linked List."
},
{
"code": null,
"e": 162,
"s": 111,
"text": "Convert an Array to a Circular Doubly Linked List."
},
{
"code": null,
"e": 372,
"s": 162,
"text": "Given the start pointer pointing to the start of a Circular Doubly Linked List, an element and a position. The task is to insert the element at the specified position in the given Circular Doubly Linked List. "
},
{
"code": null,
"e": 524,
"s": 372,
"text": "The idea is to count the total number of elements in the list. Check whether the specified location is valid or not, i.e. location is within the count."
},
{
"code": null,
"e": 548,
"s": 524,
"text": "If location is valid: "
},
{
"code": null,
"e": 912,
"s": 548,
"text": "Create a newNode in the memory.Traverse in the list using a temporary pointer(temp) till the node just before the given position at which a new node is needed to be inserted.Insert the new node by performing below operations: Assign newNode->next = temp->nextAssign newNode->prev as temp->nextAssign temp->next as newNodeAssign (temp->next)->prev as newNode->next"
},
{
"code": null,
"e": 944,
"s": 912,
"text": "Create a newNode in the memory."
},
{
"code": null,
"e": 1088,
"s": 944,
"text": "Traverse in the list using a temporary pointer(temp) till the node just before the given position at which a new node is needed to be inserted."
},
{
"code": null,
"e": 1278,
"s": 1088,
"text": "Insert the new node by performing below operations: Assign newNode->next = temp->nextAssign newNode->prev as temp->nextAssign temp->next as newNodeAssign (temp->next)->prev as newNode->next"
},
{
"code": null,
"e": 1312,
"s": 1278,
"text": "Assign newNode->next = temp->next"
},
{
"code": null,
"e": 1347,
"s": 1312,
"text": "Assign newNode->prev as temp->next"
},
{
"code": null,
"e": 1376,
"s": 1347,
"text": "Assign temp->next as newNode"
},
{
"code": null,
"e": 1419,
"s": 1376,
"text": "Assign (temp->next)->prev as newNode->next"
},
{
"code": null,
"e": 1468,
"s": 1419,
"text": "Below is the implementation of the above idea: "
},
{
"code": null,
"e": 1472,
"s": 1468,
"text": "C++"
},
{
"code": null,
"e": 1477,
"s": 1472,
"text": "Java"
},
{
"code": null,
"e": 1485,
"s": 1477,
"text": "Python3"
},
{
"code": null,
"e": 1488,
"s": 1485,
"text": "C#"
},
{
"code": null,
"e": 1499,
"s": 1488,
"text": "Javascript"
},
{
"code": "// CPP program to convert insert an element at a specific// position in a circular doubly linked list #include <bits/stdc++.h>using namespace std; // Doubly linked list nodestruct node { int data; struct node* next; struct node* prev;}; // Utility function to create a node in memorystruct node* getNode(){ return ((struct node*)malloc(sizeof(struct node)));} // Function to display the listint displayList(struct node* temp){ struct node* t = temp; if (temp == NULL) return 0; else { cout << \"The list is: \"; while (temp->next != t) { cout << temp->data << \" \"; temp = temp->next; } cout << temp->data << endl; return 1; }} // Function to count number of// elements in the listint countList(struct node* start){ // Declare temp pointer to // traverse the list struct node* temp = start; // Variable to store the count int count = 0; // Iterate the list and increment the count while (temp->next != start) { temp = temp->next; count++; } // As the list is circular, increment the // counter at last count++; return count;} // Function to insert a node at a given position// in the circular doubly linked listbool insertAtLocation(struct node* start, int data, int loc){ // Declare two pointers struct node *temp, *newNode; int i, count; // Create a new node in memory newNode = getNode(); // Point temp to start temp = start; // count of total elements in the list count = countList(start); // If list is empty or the position is // not valid, return false if (temp == NULL || count < loc) return false; else { // Assign the data newNode->data = data; // Iterate till the loc for (i = 1; i < loc - 1; i++) { temp = temp->next; } // See in Image, circle 1 newNode->next = temp->next; // See in Image, Circle 2 (temp->next)->prev = newNode; // See in Image, Circle 3 temp->next = newNode; // See in Image, Circle 4 newNode->prev = temp; return true; } return false;} // Function to create circular doubly linked list// from array elementsvoid createList(int arr[], int n, struct node** start){ // Declare newNode and temporary pointer struct node *newNode, *temp; int i; // Iterate the loop until array length for (i = 0; i < n; i++) { // Create new node newNode = getNode(); // Assign the array data newNode->data = arr[i]; // If it is first element // Put that node prev and next as start // as it is circular if (i == 0) { *start = newNode; newNode->prev = *start; newNode->next = *start; } else { // Find the last node temp = (*start)->prev; // Add the last node to make them // in circular fashion temp->next = newNode; newNode->next = *start; newNode->prev = temp; temp = *start; temp->prev = newNode; } }} // Driver Codeint main(){ // Array elements to create // circular doubly linked list int arr[] = { 1, 2, 3, 4, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); // Start Pointer struct node* start = NULL; // Create the List createList(arr, n, &start); // Display the list before insertion displayList(start); // Inserting 8 at 3rd position insertAtLocation(start, 8, 3); // Display the list after insertion displayList(start); return 0;}",
"e": 5145,
"s": 1499,
"text": null
},
{
"code": "// Java program to convert insert// an element at a specific position// in a circular doubly linked listing,// end and middleclass GFG{ // Doubly linked list nodestatic class node{ int data; node next; node prev;}; // Utility function to create a node in memorystatic node getNode(){ return new node();} // Function to display the liststatic int displayList( node temp){ node t = temp; if (temp == null) return 0; else { System.out.println( \"The list is: \"); while (temp.next != t) { System.out.print( temp.data + \" \"); temp = temp.next; } System.out.println( temp.data ); return 1; }} // Function to count number of// elements in the liststatic int countList( node start){ // Declare temp pointer to // traverse the list node temp = start; // Variable to store the count int count = 0; // Iterate the list and // increment the count while (temp.next != start) { temp = temp.next; count++; } // As the list is circular, increment // the counter at last count++; return count;} // Function to insert a node at// a given position in the// circular doubly linked liststatic node insertAtLocation( node start, int data, int loc){ // Declare two pointers node temp, newNode; int i, count; // Create a new node in memory newNode = getNode(); // Point temp to start temp = start; // count of total elements in the list count = countList(start); // If list is empty or the position is // not valid, return false if (temp == null || count < loc) return start; else { // Assign the data newNode.data = data; // Iterate till the loc for (i = 1; i < loc - 1; i++) { temp = temp.next; } // See in Image, circle 1 newNode.next = temp.next; // See in Image, Circle 2 (temp.next).prev = newNode; // See in Image, Circle 3 temp.next = newNode; // See in Image, Circle 4 newNode.prev = temp; return start; } } // Function to create circular doubly // linked list from array elementsstatic node createList(int arr[], int n, node start){ // Declare newNode and temporary pointer node newNode, temp; int i; // Iterate the loop until array length for (i = 0; i < n; i++) { // Create new node newNode = getNode(); // Assign the array data newNode.data = arr[i]; // If it is first element // Put that node prev and next as start // as it is circular if (i == 0) { start = newNode; newNode.prev = start; newNode.next = start; } else { // Find the last node temp = (start).prev; // Add the last node to make them // in circular fashion temp.next = newNode; newNode.next = start; newNode.prev = temp; temp = start; temp.prev = newNode; } } return start;} // Driver Codepublic static void main(String args[]){ // Array elements to create // circular doubly linked list int arr[] = { 1, 2, 3, 4, 5, 6 }; int n = arr.length; // Start Pointer node start = null; // Create the List start = createList(arr, n, start); // Display the list before insertion displayList(start); // Inserting 8 at 3rd position start = insertAtLocation(start, 8, 3); // Display the list after insertion displayList(start);}} // This code is contributed by Arnab Kundu",
"e": 8821,
"s": 5145,
"text": null
},
{
"code": "# Python3 program to insert an element# at a specific position in a# circular doubly linked list # Node of the doubly linked listclass Node: def __init__(self, data): self.data = data self.prev = None self.next = None # Utility function to create# a node in memorydef getNode(): return (Node(0)) # Function to display the listdef displayList(temp): t = temp if (temp == None): return 0 else : print(\"The list is: \", end = \" \") while (temp.next != t): print( temp.data, end = \" \") temp = temp.next print(temp.data ) return 1 # Function to count number of# elements in the listdef countList( start): # Declare temp pointer to # traverse the list temp = start # Variable to store the count count = 0 # Iterate the list and increment the count while (temp.next != start) : temp = temp.next count = count + 1 # As the list is circular, increment the # counter at last count = count + 1 return count # Function to insert a node at a given position# in the circular doubly linked listdef insertAtLocation(start, data, loc): # Declare two pointers temp = None newNode = None i = 0 count = 0 # Create a new node in memory newNode = getNode() # Point temp to start temp = start # count of total elements in the list count = countList(start) # If list is empty or the position is # not valid, return False if (temp == None or count < loc): return start else : # Assign the data newNode.data = data # Iterate till the loc i = 1; while(i < loc - 1) : temp = temp.next i = i + 1 # See in Image, circle 1 newNode.next = temp.next # See in Image, Circle 2 (temp.next).prev = newNode # See in Image, Circle 3 temp.next = newNode # See in Image, Circle 4 newNode.prev = temp return start return start # Function to create circular# doubly linked list from array elementsdef createList(arr, n, start): # Declare newNode and temporary pointer newNode = None temp = None i = 0 # Iterate the loop until array length while (i < n) : # Create new node newNode = getNode() # Assign the array data newNode.data = arr[i] # If it is first element # Put that node prev and next as start # as it is circular if (i == 0) : start = newNode newNode.prev = start newNode.next = start else : # Find the last node temp = (start).prev # Add the last node to make them # in circular fashion temp.next = newNode newNode.next = start newNode.prev = temp temp = start temp.prev = newNode i = i + 1; return start # Driver Codeif __name__ == \"__main__\": # Array elements to create # circular doubly linked list arr = [ 1, 2, 3, 4, 5, 6] n = len(arr) # Start Pointer start = None # Create the List start = createList(arr, n, start) # Display the list before insertion displayList(start) # Inserting 8 at 3rd position start = insertAtLocation(start, 8, 3) # Display the list after insertion displayList(start) # This code is contributed by Arnab Kundu",
"e": 12308,
"s": 8821,
"text": null
},
{
"code": "// C# program to convert insert// an element at a specific position// in a circular doubly linked listing,// end and middleusing System; class GFG{ // Doubly linked list nodepublic class node{ public int data; public node next; public node prev;}; // Utility function to create a node in memorystatic node getNode(){ return new node();} // Function to display the liststatic int displayList( node temp){ node t = temp; if (temp == null) return 0; else { Console.WriteLine( \"The list is: \"); while (temp.next != t) { Console.Write( temp.data + \" \"); temp = temp.next; } Console.WriteLine( temp.data ); return 1; }} // Function to count number of// elements in the liststatic int countList( node start){ // Declare temp pointer to // traverse the list node temp = start; // Variable to store the count int count = 0; // Iterate the list and // increment the count while (temp.next != start) { temp = temp.next; count++; } // As the list is circular, increment // the counter at last count++; return count;} // Function to insert a node at// a given position in the// circular doubly linked liststatic node insertAtLocation( node start, int data, int loc){ // Declare two pointers node temp, newNode; int i, count; // Create a new node in memory newNode = getNode(); // Point temp to start temp = start; // count of total elements in the list count = countList(start); // If list is empty or the position is // not valid, return false if (temp == null || count < loc) return start; else { // Assign the data newNode.data = data; // Iterate till the loc for (i = 1; i < loc - 1; i++) { temp = temp.next; } // See in Image, circle 1 newNode.next = temp.next; // See in Image, Circle 2 (temp.next).prev = newNode; // See in Image, Circle 3 temp.next = newNode; // See in Image, Circle 4 newNode.prev = temp; return start; } } // Function to create circular doubly// linked list from array elementsstatic node createList(int []arr, int n, node start){ // Declare newNode and temporary pointer node newNode, temp; int i; // Iterate the loop until array length for (i = 0; i < n; i++) { // Create new node newNode = getNode(); // Assign the array data newNode.data = arr[i]; // If it is first element // Put that node prev and next as start // as it is circular if (i == 0) { start = newNode; newNode.prev = start; newNode.next = start; } else { // Find the last node temp = (start).prev; // Add the last node to make them // in circular fashion temp.next = newNode; newNode.next = start; newNode.prev = temp; temp = start; temp.prev = newNode; } } return start;} // Driver Codepublic static void Main(){ // Array elements to create // circular doubly linked list int []arr = { 1, 2, 3, 4, 5, 6 }; int n = arr.Length; // Start Pointer node start = null; // Create the List start = createList(arr, n, start); // Display the list before insertion displayList(start); // Inserting 8 at 3rd position start = insertAtLocation(start, 8, 3); // Display the list after insertion displayList(start);}} /* This code contributed by PrinciRaj1992 */",
"e": 15999,
"s": 12308,
"text": null
},
{
"code": "<script> // JavaScript program to convert insert // an element at a specific position // in a circular doubly linked listing, // end and middle // Doubly linked list node class node { constructor() { this.data = 0; this.next = null; this.prev = null; } } // Utility function to create a node in memory function getNode() { return new node(); } // Function to display the list function displayList(temp) { var t = temp; if (temp == null) return 0; else { document.write(\"The list is: \"); while (temp.next != t) { document.write(temp.data + \" \"); temp = temp.next; } document.write(temp.data + \"<br>\"); return 1; } } // Function to count number of // elements in the list function countList(start) { // Declare temp pointer to // traverse the list var temp = start; // Variable to store the count var count = 0; // Iterate the list and // increment the count while (temp.next != start) { temp = temp.next; count++; } // As the list is circular, increment // the counter at last count++; return count; } // Function to insert a node at // a given position in the // circular doubly linked list function insertAtLocation(start, data, loc) { // Declare two pointers var temp, newNode; var i, count; // Create a new node in memory newNode = getNode(); // Point temp to start temp = start; // count of total elements in the list count = countList(start); // If list is empty or the position is // not valid, return false if (temp == null || count < loc) return start; else { // Assign the data newNode.data = data; // Iterate till the loc for (i = 1; i < loc - 1; i++) { temp = temp.next; } // See in Image, circle 1 newNode.next = temp.next; // See in Image, Circle 2 temp.next.prev = newNode; // See in Image, Circle 3 temp.next = newNode; // See in Image, Circle 4 newNode.prev = temp; return start; } } // Function to create circular doubly // linked list from array elements function createList(arr, n, start) { // Declare newNode and temporary pointer var newNode, temp; var i; // Iterate the loop until array length for (i = 0; i < n; i++) { // Create new node newNode = getNode(); // Assign the array data newNode.data = arr[i]; // If it is first element // Put that node prev and next as start // as it is circular if (i == 0) { start = newNode; newNode.prev = start; newNode.next = start; } else { // Find the last node temp = start.prev; // Add the last node to make them // in circular fashion temp.next = newNode; newNode.next = start; newNode.prev = temp; temp = start; temp.prev = newNode; } } return start; } // Driver Code // Array elements to create // circular doubly linked list var arr = [1, 2, 3, 4, 5, 6]; var n = arr.length; // Start Pointer var start = null; // Create the List start = createList(arr, n, start); // Display the list before insertion displayList(start); // Inserting 8 at 3rd position start = insertAtLocation(start, 8, 3); // Display the list after insertion displayList(start); // This code is contributed by rdtank. </script>",
"e": 20050,
"s": 15999,
"text": null
},
{
"code": null,
"e": 20102,
"s": 20050,
"text": "The list is: 1 2 3 4 5 6\nThe list is: 1 2 8 3 4 5 6"
},
{
"code": null,
"e": 20365,
"s": 20104,
"text": "Time Complexity: O(n) => for counting the list as we are using a loop to traverse linearly, O(n) => Inserting the elements, as we are using a loop to traverse linearly. So, total complexity is O(n + n) = O(n). Where n is the number of nodes in the linked list."
},
{
"code": null,
"e": 20426,
"s": 20365,
"text": "Auxiliary Space: O(1), as we are not using any extra space. "
},
{
"code": null,
"e": 20437,
"s": 20426,
"text": "andrew1234"
},
{
"code": null,
"e": 20451,
"s": 20437,
"text": "princiraj1992"
},
{
"code": null,
"e": 20462,
"s": 20451,
"text": "nidhi_biet"
},
{
"code": null,
"e": 20469,
"s": 20462,
"text": "rdtank"
},
{
"code": null,
"e": 20484,
"s": 20469,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 20504,
"s": 20484,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 20512,
"s": 20504,
"text": "rohan07"
},
{
"code": null,
"e": 20533,
"s": 20512,
"text": "circular linked list"
},
{
"code": null,
"e": 20552,
"s": 20533,
"text": "doubly linked list"
},
{
"code": null,
"e": 20565,
"s": 20552,
"text": "Linked Lists"
},
{
"code": null,
"e": 20575,
"s": 20565,
"text": "Traversal"
},
{
"code": null,
"e": 20599,
"s": 20575,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 20611,
"s": 20599,
"text": "Linked List"
},
{
"code": null,
"e": 20623,
"s": 20611,
"text": "Linked List"
},
{
"code": null,
"e": 20633,
"s": 20623,
"text": "Traversal"
},
{
"code": null,
"e": 20654,
"s": 20633,
"text": "circular linked list"
},
{
"code": null,
"e": 20752,
"s": 20654,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 20832,
"s": 20752,
"text": "Overview of Data Structures | Set 3 (Graph, Trie, Segment Tree and Suffix Tree)"
},
{
"code": null,
"e": 20861,
"s": 20832,
"text": "Ordered Set and GNU C++ PBDS"
},
{
"code": null,
"e": 20903,
"s": 20861,
"text": "2-3 Trees | (Search, Insert and Deletion)"
},
{
"code": null,
"e": 20949,
"s": 20903,
"text": "Extendible Hashing (Dynamic approach to DBMS)"
},
{
"code": null,
"e": 20992,
"s": 20949,
"text": "Segment Tree | Set 2 (Range Minimum Query)"
},
{
"code": null,
"e": 21027,
"s": 20992,
"text": "Linked List | Set 1 (Introduction)"
},
{
"code": null,
"e": 21066,
"s": 21027,
"text": "Linked List | Set 2 (Inserting a node)"
},
{
"code": null,
"e": 21088,
"s": 21066,
"text": "Reverse a linked list"
},
{
"code": null,
"e": 21136,
"s": 21088,
"text": "Stack Data Structure (Introduction and Program)"
}
] |
How to use the recyclerview with a database in Android using Kotlin?
|
This example demonstrates how to use the recyclerview with a database in Android using Kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="4dp"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/myContactList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="50dp"
android:paddingBottom="8dp" />
<Button
android:id="@+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginEnd="16dp"
android:layout_marginBottom="4dp"
android:padding="2dp"
android:text="ADD" />
</FrameLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
class MainActivity : AppCompatActivity() {
private lateinit var dataBase: SqliteDatabase
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
val contactView: RecyclerView = findViewById(R.id.myContactList)
val linearLayoutManager = LinearLayoutManager(this)
contactView.layoutManager = linearLayoutManager
contactView.setHasFixedSize(true)
dataBase = SqliteDatabase(<Contacts>= dataBase.listContacts()
if (allContacts.size > 0) {
contactView.visibility = View.VISIBLE
val mAdapter = ContactAdapter(this, allContacts)
contactView.adapter = mAdapter
}
else {
contactView.visibility = View.GONE
Toast.makeText(
this,
"There is no contact in the database. Start adding now",
Toast.LENGTH_LONG
).show()
}
val btnAdd: Button = findViewById(R.id.btnAdd)
btnAdd.setOnClickListener { addTaskDialog() }
}
private fun addTaskDialog() {
val inflater = LayoutInflater.from(this)
val subView = inflater.inflate(R.layout.add_contacts, null)
val nameField: EditText = subView.findViewById(R.id.enterName)
val noField: EditText = subView.findViewById(R.id.enterPhoneNum)
val builder = AlertDialog.Builder(this)
builder.setTitle("Add new CONTACT")
builder.setView(subView)
builder.create()
builder.setPositiveButton("ADD CONTACT") { _, _ ->
val name = nameField.text.toString()
val phoneNum = noField.text.toString()
if (TextUtils.isEmpty(name)) {
Toast.makeText(
this@MainActivity,
"Something went wrong. Check your input values",
Toast.LENGTH_LONG
).show()
}
else {
val newContact = Contacts(name, phoneNum)
dataBase.addContacts(newContact)
finish()
startActivity(intent)
}
}
builder.setNegativeButton("CANCEL") { _, _ -> Toast.makeText(this@MainActivity, "Task cancelled",
Toast.LENGTH_LONG).show()}
builder.show()
}
override fun onDestroy() {
super.onDestroy()
dataBase.close()
}
}
Step 4 − Create kotlin class files as mentioned below and add the respective codes
Contacts.kt −
class Contacts {
var id = 0
var name: String
var phno: String
internal constructor(name: String, phno: String) {
this.name = name
this.phno = phno
}
internal constructor(id: Int, name: String, phno: String) {
this.id = id
this.name = name
this.phno = phno
}
}
ContactViewHolder.kt −
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class ContactViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var tvName: TextView = itemView.findViewById(R.id.contactName)
var tvPhoneNum: TextView = itemView.findViewById(R.id.phoneNum)
var deleteContact: ImageView = itemView.findViewById(R.id.deleteContact)
var editContact: ImageView = itemView.findViewById(R.id.editContact)
}
ContactAdapter.kt −
import android.app.Activity
import android.content.Context
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.EditText
import android.widget.Filter
import android.widget.Filterable
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.RecyclerView
import java.util.*
internal class ContactAdapter(private val context: Context, listContacts: ArrayList<Contacts>) :
RecyclerView.Adapter<ContactViewHolder>(), Filterable {
private var listContacts: ArrayList<Contacts>
private val mArrayList: ArrayList<Contacts>
private val mDatabase: SqliteDatabase
init {
this.listContacts = listContacts
this.mArrayList = listContacts
mDatabase = SqliteDatabase(context)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ContactViewHolder {
val view =
LayoutInflater.from(parent.context).inflate(R.layout.contact_list_layout, parent, false)
return ContactViewHolder(view)
}
override fun onBindViewHolder(holder: ContactViewHolder, position: Int) {
val contacts = listContacts[position]
holder.tvName.text = contacts.name
holder.tvPhoneNum.text = contacts.phno
holder.editContact.setOnClickListener { editTaskDialog(contacts) }
holder.deleteContact.setOnClickListener {
mDatabase.deleteContact(contacts.id)
(context as Activity).finish()
context.startActivity(context.intent)
}
}
override fun getFilter(): Filter {
return object : Filter() {
override fun performFiltering(charSequence: CharSequence): FilterResults {
val charString = charSequence.toString()
listContacts = if (charString.isEmpty()) {
mArrayList
}
else {
val filteredList = ArrayList<Contacts>()
for (contacts in mArrayList) {
if (contacts.name.toLowerCase().contains(charString)) {
filteredList.add(contacts)
}
}
filteredList
}
val filterResults = FilterResults()
filterResults.values = listContacts
return filterResults
}
override fun publishResults(
charSequence: CharSequence,
filterResults: FilterResults
)
{
listContacts =
filterResults.values as ArrayList<Contacts>
notifyDataSetChanged()
}
}
}
override fun getItemCount(): Int {
return listContacts.size
}
private fun editTaskDialog(contacts: Contacts) {
val inflater = LayoutInflater.from(context)
val subView = inflater.inflate(R.layout.add_contacts, null)
val nameField: EditText = subView.findViewById(R.id.enterName)
val contactField: EditText = subView.findViewById(R.id.enterPhoneNum)
nameField.setText(contacts.name)
contactField.setText(contacts.phno)
val builder = AlertDialog.Builder(context)
builder.setTitle("Edit contact")
builder.setView(subView)
builder.create()
builder.setPositiveButton(
"EDIT CONTACT"
) { _, _ ->
val name = nameField.text.toString()
val phNo = contactField.text.toString()
if (TextUtils.isEmpty(name)) {
Toast.makeText(
context,
"Something went wrong. Check your input values",
Toast.LENGTH_LONG
).show()
}
else {
mDatabase.updateContacts(
Contacts(
Objects.requireNonNull<Any>(contacts.id) as Int,
name,
phNo
)
)
(context as Activity).finish()
context.startActivity(context.intent)
}
}
builder.setNegativeButton(
"CANCEL"
) { _, _ -> Toast.makeText(context, "Task cancelled", Toast.LENGTH_LONG).show() }
builder.show()
}
}
SqliteDatabase.kt −
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import java.util.*
class SqliteDatabase internal constructor(context: Context?) :
SQLiteOpenHelper(
context,
DATABASE_NAME,
null,
DATABASE_VERSION
) {
override fun onCreate(db: SQLiteDatabase) {
val createContactTable = ("CREATE TABLE "
+ TABLE_CONTACTS + "(" + COLUMN_ID
+ " INTEGER PRIMARY KEY,"
+ COLUMN_NAME + " TEXT,"
+ COLUMN_NO + " INTEGER" + ")")
db.execSQL(createContactTable)
}
override fun onUpgrade(
db: SQLiteDatabase,
oldVersion: Int,
newVersion: Int
) {
db.execSQL("DROP TABLE IF EXISTS $TABLE_CONTACTS")
onCreate(db)
}
fun listContacts(): ArrayList<Contacts> {
val sql = "select * from $TABLE_CONTACTS"
val db = this.readableDatabase
val storeContacts =
ArrayList<Contacts>()
val cursor = db.rawQuery(sql, null)
if (cursor.moveToFirst()) {
do {
val id = cursor.getString(0).toInt()
val name = cursor.getString(1)
val phno = cursor.getString(2)
storeContacts.add(Contacts(id, name, phno))
}
while (cursor.moveToNext())
}
cursor.close()
return storeContacts
}
fun addContacts(contacts: Contacts) {
val values = ContentValues()
values.put(COLUMN_NAME, contacts.name)
values.put(COLUMN_NO, contacts.phno)
val db = this.writableDatabase
db.insert(TABLE_CONTACTS, null, values)
}
fun updateContacts(contacts: Contacts) {
val values = ContentValues()
values.put(COLUMN_NAME, contacts.name)
values.put(COLUMN_NO, contacts.phno)
val db = this.writableDatabase
db.update(
TABLE_CONTACTS,
values,
"$COLUMN_ID = ?",
arrayOf(contacts.id.toString())
)
}
fun deleteContact(id: Int) {
val db = this.writableDatabase
db.delete(
TABLE_CONTACTS,
"$COLUMN_ID = ?",
arrayOf(id.toString())
)
}
companion object {
private const val DATABASE_VERSION = 5
private const val DATABASE_NAME = "Contacts"
private const val TABLE_CONTACTS = "Contacts"
private const val COLUMN_ID = "_id"
private const val COLUMN_NAME = "contactName"
private const val COLUMN_NO = "phoneNumber"
}
}
Step 5 − Create a layout resource files (add_contacts.xml & contact_list_layout.xml) and add the following code
add_contacts.xml −
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/enterName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:hint="Enter Name"
android:inputType="text"
android:maxLines="1"
android:padding="12dp"
android:textSize="12dp" />
<EditText
android:id="@+id/enterPhoneNum"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginEnd="8dp"
android:hint="Enter Number"
android:inputType="phone"
android:maxLines="1"
android:padding="12dp"
android:textSize="12sp" />
</LinearLayout>
contact_list_layout.xml −
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="1dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="12dp">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/contactName"
android:layout_width="220dp"
android:layout_height="wrap_content"
android:textSize="12sp"
android:textStyle="bold" />
<TextView
android:id="@+id/phoneNum"
android:layout_width="220dp"
android:layout_height="wrap_content"
android:layout_below="@+id/contactName"
android:textSize="12sp"
android:textStyle="bold" />
</RelativeLayout>
<ImageView
android:id="@+id/editContact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:contentDescription="TODO"
android:src="@drawable/ic_baseline_edit_24" />
<ImageView
android:id="@+id/deleteContact"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:contentDescription="TODO"
android:src="@drawable/ic_baseline_remove_24" />
</LinearLayout>
</androidx.cardview.widget.CardView>
Step 6 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.q11">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
|
[
{
"code": null,
"e": 1282,
"s": 1187,
"text": "This example demonstrates how to use the recyclerview with a database in Android using Kotlin."
},
{
"code": null,
"e": 1411,
"s": 1282,
"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": 1476,
"s": 1411,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2340,
"s": 1476,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<FrameLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"4dp\"\n tools:context=\".MainActivity\">\n <androidx.recyclerview.widget.RecyclerView\n android:id=\"@+id/myContactList\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:layout_marginBottom=\"50dp\"\n android:paddingBottom=\"8dp\" />\n <Button\n android:id=\"@+id/btnAdd\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_gravity=\"bottom|end\"\n android:layout_marginEnd=\"16dp\"\n android:layout_marginBottom=\"4dp\"\n android:padding=\"2dp\"\n android:text=\"ADD\" />\n</FrameLayout>"
},
{
"code": null,
"e": 2395,
"s": 2340,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 5056,
"s": 2395,
"text": "import android.os.Bundle\nimport android.text.TextUtils\nimport android.view.LayoutInflater\nimport android.view.View\nimport android.widget.Button\nimport android.widget.EditText\nimport android.widget.Toast\nimport androidx.appcompat.app.AlertDialog\nimport androidx.appcompat.app.AppCompatActivity\nimport androidx.recyclerview.widget.LinearLayoutManager\nimport androidx.recyclerview.widget.RecyclerView\nclass MainActivity : AppCompatActivity() {\n private lateinit var dataBase: SqliteDatabase\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n val contactView: RecyclerView = findViewById(R.id.myContactList)\n val linearLayoutManager = LinearLayoutManager(this)\n contactView.layoutManager = linearLayoutManager\n contactView.setHasFixedSize(true)\n dataBase = SqliteDatabase(<Contacts>= dataBase.listContacts()\n if (allContacts.size > 0) {\n contactView.visibility = View.VISIBLE\n val mAdapter = ContactAdapter(this, allContacts)\n contactView.adapter = mAdapter\n }\n else {\n contactView.visibility = View.GONE\n Toast.makeText(\n this,\n \"There is no contact in the database. Start adding now\",\n Toast.LENGTH_LONG\n ).show()\n }\n val btnAdd: Button = findViewById(R.id.btnAdd)\n btnAdd.setOnClickListener { addTaskDialog() }\n }\n private fun addTaskDialog() {\n val inflater = LayoutInflater.from(this)\n val subView = inflater.inflate(R.layout.add_contacts, null)\n val nameField: EditText = subView.findViewById(R.id.enterName)\n val noField: EditText = subView.findViewById(R.id.enterPhoneNum)\n val builder = AlertDialog.Builder(this)\n builder.setTitle(\"Add new CONTACT\")\n builder.setView(subView)\n builder.create()\n builder.setPositiveButton(\"ADD CONTACT\") { _, _ ->\n val name = nameField.text.toString()\n val phoneNum = noField.text.toString()\n if (TextUtils.isEmpty(name)) {\n Toast.makeText(\n this@MainActivity,\n \"Something went wrong. Check your input values\",\n Toast.LENGTH_LONG\n ).show()\n }\n else {\n val newContact = Contacts(name, phoneNum)\n dataBase.addContacts(newContact)\n finish()\n startActivity(intent)\n }\n }\n builder.setNegativeButton(\"CANCEL\") { _, _ -> Toast.makeText(this@MainActivity, \"Task cancelled\",\nToast.LENGTH_LONG).show()}\n builder.show()\n }\n override fun onDestroy() {\n super.onDestroy()\n dataBase.close()\n }\n}"
},
{
"code": null,
"e": 5139,
"s": 5056,
"text": "Step 4 − Create kotlin class files as mentioned below and add the respective codes"
},
{
"code": null,
"e": 5153,
"s": 5139,
"text": "Contacts.kt −"
},
{
"code": null,
"e": 5464,
"s": 5153,
"text": "class Contacts {\n var id = 0\n var name: String\n var phno: String\n internal constructor(name: String, phno: String) {\n this.name = name\n this.phno = phno\n }\n internal constructor(id: Int, name: String, phno: String) {\n this.id = id\n this.name = name\n this.phno = phno\n }\n}"
},
{
"code": null,
"e": 5487,
"s": 5464,
"text": "ContactViewHolder.kt −"
},
{
"code": null,
"e": 5985,
"s": 5487,
"text": "import android.view.View\nimport android.widget.ImageView\nimport android.widget.TextView\nimport androidx.recyclerview.widget.RecyclerView\nclass ContactViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {\n var tvName: TextView = itemView.findViewById(R.id.contactName)\n var tvPhoneNum: TextView = itemView.findViewById(R.id.phoneNum)\n var deleteContact: ImageView = itemView.findViewById(R.id.deleteContact)\n var editContact: ImageView = itemView.findViewById(R.id.editContact)\n}"
},
{
"code": null,
"e": 6005,
"s": 5985,
"text": "ContactAdapter.kt −"
},
{
"code": null,
"e": 10083,
"s": 6005,
"text": "import android.app.Activity\nimport android.content.Context\nimport android.text.TextUtils\nimport android.view.LayoutInflater\nimport android.view.ViewGroup\nimport android.widget.EditText\nimport android.widget.Filter\nimport android.widget.Filterable\nimport android.widget.Toast\nimport androidx.appcompat.app.AlertDialog\nimport androidx.recyclerview.widget.RecyclerView\nimport java.util.*\ninternal class ContactAdapter(private val context: Context, listContacts: ArrayList<Contacts>) :\nRecyclerView.Adapter<ContactViewHolder>(), Filterable {\n private var listContacts: ArrayList<Contacts>\n private val mArrayList: ArrayList<Contacts>\n private val mDatabase: SqliteDatabase\n init {\n this.listContacts = listContacts\n this.mArrayList = listContacts\n mDatabase = SqliteDatabase(context)\n }\n override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ContactViewHolder {\n val view =\n LayoutInflater.from(parent.context).inflate(R.layout.contact_list_layout, parent, false)\n return ContactViewHolder(view)\n }\n override fun onBindViewHolder(holder: ContactViewHolder, position: Int) {\n val contacts = listContacts[position]\n holder.tvName.text = contacts.name\n holder.tvPhoneNum.text = contacts.phno\n holder.editContact.setOnClickListener { editTaskDialog(contacts) }\n holder.deleteContact.setOnClickListener {\n mDatabase.deleteContact(contacts.id)\n (context as Activity).finish()\n context.startActivity(context.intent)\n }\n }\n override fun getFilter(): Filter {\n return object : Filter() {\n override fun performFiltering(charSequence: CharSequence): FilterResults {\n val charString = charSequence.toString()\n listContacts = if (charString.isEmpty()) {\n mArrayList\n }\n else {\n val filteredList = ArrayList<Contacts>()\n for (contacts in mArrayList) {\n if (contacts.name.toLowerCase().contains(charString)) {\n filteredList.add(contacts)\n }\n }\n filteredList\n }\n val filterResults = FilterResults()\n filterResults.values = listContacts\n return filterResults\n }\n override fun publishResults(\n charSequence: CharSequence,\n filterResults: FilterResults\n )\n {\n listContacts =\n filterResults.values as ArrayList<Contacts>\n notifyDataSetChanged()\n }\n }\n }\n override fun getItemCount(): Int {\n return listContacts.size\n }\n private fun editTaskDialog(contacts: Contacts) {\n val inflater = LayoutInflater.from(context)\n val subView = inflater.inflate(R.layout.add_contacts, null)\n val nameField: EditText = subView.findViewById(R.id.enterName)\n val contactField: EditText = subView.findViewById(R.id.enterPhoneNum)\n nameField.setText(contacts.name)\n contactField.setText(contacts.phno)\n val builder = AlertDialog.Builder(context)\n builder.setTitle(\"Edit contact\")\n builder.setView(subView)\n builder.create()\n builder.setPositiveButton(\n \"EDIT CONTACT\"\n ) { _, _ ->\n val name = nameField.text.toString()\n val phNo = contactField.text.toString()\n if (TextUtils.isEmpty(name)) {\n Toast.makeText(\n context,\n \"Something went wrong. Check your input values\",\n Toast.LENGTH_LONG\n ).show()\n }\n else {\n mDatabase.updateContacts(\n Contacts(\n Objects.requireNonNull<Any>(contacts.id) as Int,\n name,\n phNo\n )\n )\n (context as Activity).finish()\n context.startActivity(context.intent)\n }\n }\n builder.setNegativeButton(\n \"CANCEL\"\n ) { _, _ -> Toast.makeText(context, \"Task cancelled\", Toast.LENGTH_LONG).show() }\n builder.show()\n }\n}"
},
{
"code": null,
"e": 10103,
"s": 10083,
"text": "SqliteDatabase.kt −"
},
{
"code": null,
"e": 12567,
"s": 10103,
"text": "import android.content.ContentValues\nimport android.content.Context\nimport android.database.sqlite.SQLiteDatabase\nimport android.database.sqlite.SQLiteOpenHelper\nimport java.util.*\nclass SqliteDatabase internal constructor(context: Context?) :\nSQLiteOpenHelper(\n context,\n DATABASE_NAME,\n null,\n DATABASE_VERSION\n) {\n override fun onCreate(db: SQLiteDatabase) {\n val createContactTable = (\"CREATE TABLE \"\n + TABLE_CONTACTS + \"(\" + COLUMN_ID\n + \" INTEGER PRIMARY KEY,\"\n + COLUMN_NAME + \" TEXT,\"\n + COLUMN_NO + \" INTEGER\" + \")\")\n db.execSQL(createContactTable)\n }\n override fun onUpgrade(\n db: SQLiteDatabase,\n oldVersion: Int,\n newVersion: Int\n ) {\n db.execSQL(\"DROP TABLE IF EXISTS $TABLE_CONTACTS\")\n onCreate(db)\n }\n fun listContacts(): ArrayList<Contacts> {\n val sql = \"select * from $TABLE_CONTACTS\"\n val db = this.readableDatabase\n val storeContacts =\n ArrayList<Contacts>()\n val cursor = db.rawQuery(sql, null)\n if (cursor.moveToFirst()) {\n do {\n val id = cursor.getString(0).toInt()\n val name = cursor.getString(1)\n val phno = cursor.getString(2)\n storeContacts.add(Contacts(id, name, phno))\n }\n while (cursor.moveToNext())\n }\n cursor.close()\n return storeContacts\n }\n fun addContacts(contacts: Contacts) {\n val values = ContentValues()\n values.put(COLUMN_NAME, contacts.name)\n values.put(COLUMN_NO, contacts.phno)\n val db = this.writableDatabase\n db.insert(TABLE_CONTACTS, null, values)\n }\n fun updateContacts(contacts: Contacts) {\n val values = ContentValues()\n values.put(COLUMN_NAME, contacts.name)\n values.put(COLUMN_NO, contacts.phno)\n val db = this.writableDatabase\n db.update(\n TABLE_CONTACTS,\n values,\n \"$COLUMN_ID = ?\",\n arrayOf(contacts.id.toString())\n )\n }\n fun deleteContact(id: Int) {\n val db = this.writableDatabase\n db.delete(\n TABLE_CONTACTS,\n \"$COLUMN_ID = ?\",\n arrayOf(id.toString())\n )\n }\n companion object {\n private const val DATABASE_VERSION = 5\n private const val DATABASE_NAME = \"Contacts\"\n private const val TABLE_CONTACTS = \"Contacts\"\n private const val COLUMN_ID = \"_id\"\n private const val COLUMN_NAME = \"contactName\"\n private const val COLUMN_NO = \"phoneNumber\"\n }\n}"
},
{
"code": null,
"e": 12679,
"s": 12567,
"text": "Step 5 − Create a layout resource files (add_contacts.xml & contact_list_layout.xml) and add the following code"
},
{
"code": null,
"e": 12698,
"s": 12679,
"text": "add_contacts.xml −"
},
{
"code": null,
"e": 13627,
"s": 12698,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\">\n <EditText\n android:id=\"@+id/enterName\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_marginEnd=\"8dp\"\n android:hint=\"Enter Name\"\n android:inputType=\"text\"\n android:maxLines=\"1\"\n android:padding=\"12dp\"\n android:textSize=\"12dp\" />\n <EditText\n android:id=\"@+id/enterPhoneNum\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"10dp\"\n android:layout_marginEnd=\"8dp\"\n android:hint=\"Enter Number\"\n android:inputType=\"phone\"\n android:maxLines=\"1\"\n android:padding=\"12dp\"\n android:textSize=\"12sp\" />\n</LinearLayout>"
},
{
"code": null,
"e": 13653,
"s": 13627,
"text": "contact_list_layout.xml −"
},
{
"code": null,
"e": 15315,
"s": 13653,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<androidx.cardview.widget.CardView xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_marginBottom=\"1dp\"\n android:orientation=\"vertical\">\n <LinearLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:orientation=\"horizontal\"\n android:padding=\"12dp\">\n <RelativeLayout\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\">\n <TextView\n android:id=\"@+id/contactName\"\n android:layout_width=\"220dp\"\n android:layout_height=\"wrap_content\"\n android:textSize=\"12sp\"\n android:textStyle=\"bold\" />\n <TextView\n android:id=\"@+id/phoneNum\"\n android:layout_width=\"220dp\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@+id/contactName\"\n android:textSize=\"12sp\"\n android:textStyle=\"bold\" />\n </RelativeLayout>\n <ImageView\n android:id=\"@+id/editContact\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_gravity=\"center_vertical\"\n android:layout_weight=\"1\"\n android:contentDescription=\"TODO\"\n android:src=\"@drawable/ic_baseline_edit_24\" />\n <ImageView\n android:id=\"@+id/deleteContact\"\n android:layout_width=\"0dp\"\n android:layout_height=\"wrap_content\"\n android:layout_gravity=\"center\"\n android:layout_weight=\"1\"\n android:contentDescription=\"TODO\"\n android:src=\"@drawable/ic_baseline_remove_24\" />\n </LinearLayout>\n</androidx.cardview.widget.CardView>"
},
{
"code": null,
"e": 15370,
"s": 15315,
"text": "Step 6 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 16044,
"s": 15370,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 16393,
"s": 16044,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen"
}
] |
Node.js NPM shortid Module
|
08 Apr, 2022
NPM(Node Package Manager) is a package manager of Node.js packages. There is a NPM package called ‘shortid’ used to create short non-sequential url-friendly unique ids. By default, it uses 7-14 url-friendly characters: A-Z, a-z, 0-9, _-. It Supports cluster (automatically), custom seeds, custom alphabet. It Can generate any number of ids without duplication.
Command to install:
npm install shortid
Syntax to import the package in local file-
const shortid = require('shortid')
Syntax to create unique id-
const newId = shortid.generate()
There are some methods defined on shortid modules to create unique ids and customize the ids. some of the methods are illustrated below.
shortid.generate() – Used to create unique id.
Example:
users.insert({
_id: shortid.generate(),
name: '...',
email: '...'
});
shortid.isValid(id) – Used to check if id is valid or not.
Example:
shortid.isValid('41GHDbE');
// true
shortid.isValid('i have spaces');
// false
shortid.characters(characters) – Used to customize the ids.
Example:
shortid.characters('ABCDEFGHIJKLNOPQRST'
+ 'UVWXYZabcdefghijklmnopqrstuv'
+ 'wxyz123456789101112');
Example 1: This example illustrates how to generate and use shortid package to create unique ids.
filename-index.js : This file contains all the logic to create short id and attach it with user information and save to the database.
javascript
const express = require('express')const bodyParser = require('body-parser')const shortid = require('shortid')const formTemplet = require('./form')const repo = require('./repository') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML formapp.get('/', (req, res) => { res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.post('/', (req, res) => { // Fetching user inputs const {name, email} = req.body // Creating new unique id const userId = shortid.generate() // Saving record to the database // with attaching userid to each record repo.create({ userId, name, email }) res.send('Information submitted!')}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)})
filename – repository.js: This file contain all the logic to create database and interact with it.
javascript
// Importing node.js file system moduleconst fs = require('fs') class Repository { constructor(filename) { // Filename where data are going to store if(!filename) { throw new Error('Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch(err) { // If file not exist it is created // with empty array fs.writeFileSync(this.filename, '[]') } } // Get all existing records async getAll(){ return JSON.parse( await fs.promises.readFile(this.filename, { encoding : 'utf8' }) ) } // Create new record async create(attrs){ // Fetch all existing records const records = await this.getAll() // All the existing records with new // record push back to database records.push(attrs) await fs.promises.writeFile( this.filename, JSON.stringify(records, null, 2) ) return attrs }} // The 'datastore.json' file created// at runtime and all the information// provided via signup form store in// this file in JSON format.module.exports = new Repository('datastore.json')
filename – form.js: This file contain all the logic to render form.
javascript
module.exports = ({errors}) => { return `<!DOCTYPE html><html> <head> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns { margin-top: 100px; } .button { margin-top: 10px } </style></head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <form action='/' method='POST'> <div> <div> <label class='label' id='str'> Name </label> </div> <input class='input' type='text' name='name' placeholder='Name' for='name'> </div> <div> <div> <label class='label' id='email'> Email </label> </div> <input class='input' type='email' name='email' placeholder='Email' for='email'> </div> <div> <button class='button is-info'> Submit </button> </div> </form> </div> </div> </div></body> </html> `}
Output:
Submitting information1
Submitting information2
Submitting information3
Database:
Database after submitting the informations
Example 2: This example illustrates how to customize and use shortid package to create unique ids.
filename-index.js: This file contains all the logic to create short id and attach it with user information and save to the database.
javascript
const express = require('express')const bodyParser = require('body-parser')const shortid = require('shortid')const formTemplet = require('./form')const repo = require('./repository') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML formapp.get('/', (req, res) => { res.send(formTemplet({}))}) // Post route to handle form// submission logic andapp.post('/', (req, res) => { // Fetching user inputs const {name, email} = req.body // Customising id creation shortid.characters('ABCDEFGHI' + 'JKLmNOPQRSTUVWXYZ' + 'abcdefghijklmnopq' + 'rstuvwxyz123456789101112') // Creating new unique id const userId = shortid.generate() // Saving record to the database // with attaching userid to each record repo.create({ userId, name, email }) res.send('Information submitted!')}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)})
filename – repository.js: This file contain all the logic to create database and interact with it.
javascript
// Importing node.js file system moduleconst fs = require('fs') class Repository { constructor(filename) { // Filename where data are going to store if(!filename) { throw new Error('Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch(err) { // If file not exist it is // created with empty array fs.writeFileSync(this.filename, '[]') } } // Get all existing records async getAll(){ return JSON.parse( await fs.promises.readFile(this.filename, { encoding : 'utf8' }) ) } // Create new record async create(attrs){ // Fetch all existing records const records = await this.getAll() // All the existing records with new // record push back to database records.push(attrs) await fs.promises.writeFile( this.filename, JSON.stringify(records, null, 2) ) return attrs }} // The 'datastore.json' file created// at runtime and all the information// provided via signup form store in// this file in JSON format.module.exports = new Repository('datastore.json')
filename – form.js: This file contain all the logic to render form
javascript
const getError = (errors, prop) => { try { return errors.mapped()[prop].msg } catch (error) { return '' }} module.exports = ({errors}) => { return `<!DOCTYPE html><html> <head> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns { margin-top: 100px; } .button { margin-top: 10px } </style></head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <form action='/' method='POST'> <div> <div> <label class='label' id='str'> Name </label> </div> <input class='input' type='text' name='name' placeholder='Name' for='name'> </div> <div> <div> <label class='label' id='email'> Email </label> </div> <input class='input' type='email' name='email' placeholder='Email' for='email'> </div> <div> <button class='button is-info'> Submit </button> </div> </form> </div> </div> </div></body> </html> `}
Output:
Submitting information1
Submitting information 2
Submitting information 3
Database:
Database after submitting the informations
Note: We have used some Bulma classes in form.js file to design our content.
rkbhola5
Node.js-Misc
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Apr, 2022"
},
{
"code": null,
"e": 389,
"s": 28,
"text": "NPM(Node Package Manager) is a package manager of Node.js packages. There is a NPM package called ‘shortid’ used to create short non-sequential url-friendly unique ids. By default, it uses 7-14 url-friendly characters: A-Z, a-z, 0-9, _-. It Supports cluster (automatically), custom seeds, custom alphabet. It Can generate any number of ids without duplication."
},
{
"code": null,
"e": 409,
"s": 389,
"text": "Command to install:"
},
{
"code": null,
"e": 429,
"s": 409,
"text": "npm install shortid"
},
{
"code": null,
"e": 473,
"s": 429,
"text": "Syntax to import the package in local file-"
},
{
"code": null,
"e": 508,
"s": 473,
"text": "const shortid = require('shortid')"
},
{
"code": null,
"e": 536,
"s": 508,
"text": "Syntax to create unique id-"
},
{
"code": null,
"e": 569,
"s": 536,
"text": "const newId = shortid.generate()"
},
{
"code": null,
"e": 706,
"s": 569,
"text": "There are some methods defined on shortid modules to create unique ids and customize the ids. some of the methods are illustrated below."
},
{
"code": null,
"e": 753,
"s": 706,
"text": "shortid.generate() – Used to create unique id."
},
{
"code": null,
"e": 762,
"s": 753,
"text": "Example:"
},
{
"code": null,
"e": 838,
"s": 762,
"text": "users.insert({\n _id: shortid.generate(),\n name: '...',\n email: '...'\n});"
},
{
"code": null,
"e": 897,
"s": 838,
"text": "shortid.isValid(id) – Used to check if id is valid or not."
},
{
"code": null,
"e": 906,
"s": 897,
"text": "Example:"
},
{
"code": null,
"e": 985,
"s": 906,
"text": "shortid.isValid('41GHDbE');\n// true\nshortid.isValid('i have spaces');\n// false"
},
{
"code": null,
"e": 1045,
"s": 985,
"text": "shortid.characters(characters) – Used to customize the ids."
},
{
"code": null,
"e": 1054,
"s": 1045,
"text": "Example:"
},
{
"code": null,
"e": 1154,
"s": 1054,
"text": "shortid.characters('ABCDEFGHIJKLNOPQRST'\n+ 'UVWXYZabcdefghijklmnopqrstuv'\n+ 'wxyz123456789101112');"
},
{
"code": null,
"e": 1252,
"s": 1154,
"text": "Example 1: This example illustrates how to generate and use shortid package to create unique ids."
},
{
"code": null,
"e": 1386,
"s": 1252,
"text": "filename-index.js : This file contains all the logic to create short id and attach it with user information and save to the database."
},
{
"code": null,
"e": 1397,
"s": 1386,
"text": "javascript"
},
{
"code": "const express = require('express')const bodyParser = require('body-parser')const shortid = require('shortid')const formTemplet = require('./form')const repo = require('./repository') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML formapp.get('/', (req, res) => { res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.post('/', (req, res) => { // Fetching user inputs const {name, email} = req.body // Creating new unique id const userId = shortid.generate() // Saving record to the database // with attaching userid to each record repo.create({ userId, name, email }) res.send('Information submitted!')}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)})",
"e": 2279,
"s": 1397,
"text": null
},
{
"code": null,
"e": 2378,
"s": 2279,
"text": "filename – repository.js: This file contain all the logic to create database and interact with it."
},
{
"code": null,
"e": 2389,
"s": 2378,
"text": "javascript"
},
{
"code": "// Importing node.js file system moduleconst fs = require('fs') class Repository { constructor(filename) { // Filename where data are going to store if(!filename) { throw new Error('Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch(err) { // If file not exist it is created // with empty array fs.writeFileSync(this.filename, '[]') } } // Get all existing records async getAll(){ return JSON.parse( await fs.promises.readFile(this.filename, { encoding : 'utf8' }) ) } // Create new record async create(attrs){ // Fetch all existing records const records = await this.getAll() // All the existing records with new // record push back to database records.push(attrs) await fs.promises.writeFile( this.filename, JSON.stringify(records, null, 2) ) return attrs }} // The 'datastore.json' file created// at runtime and all the information// provided via signup form store in// this file in JSON format.module.exports = new Repository('datastore.json')",
"e": 3533,
"s": 2389,
"text": null
},
{
"code": null,
"e": 3601,
"s": 3533,
"text": "filename – form.js: This file contain all the logic to render form."
},
{
"code": null,
"e": 3612,
"s": 3601,
"text": "javascript"
},
{
"code": "module.exports = ({errors}) => { return `<!DOCTYPE html><html> <head> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns { margin-top: 100px; } .button { margin-top: 10px } </style></head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <form action='/' method='POST'> <div> <div> <label class='label' id='str'> Name </label> </div> <input class='input' type='text' name='name' placeholder='Name' for='name'> </div> <div> <div> <label class='label' id='email'> Email </label> </div> <input class='input' type='email' name='email' placeholder='Email' for='email'> </div> <div> <button class='button is-info'> Submit </button> </div> </form> </div> </div> </div></body> </html> `}",
"e": 4752,
"s": 3612,
"text": null
},
{
"code": null,
"e": 4760,
"s": 4752,
"text": "Output:"
},
{
"code": null,
"e": 4784,
"s": 4760,
"text": "Submitting information1"
},
{
"code": null,
"e": 4808,
"s": 4784,
"text": "Submitting information2"
},
{
"code": null,
"e": 4832,
"s": 4808,
"text": "Submitting information3"
},
{
"code": null,
"e": 4842,
"s": 4832,
"text": "Database:"
},
{
"code": null,
"e": 4885,
"s": 4842,
"text": "Database after submitting the informations"
},
{
"code": null,
"e": 4984,
"s": 4885,
"text": "Example 2: This example illustrates how to customize and use shortid package to create unique ids."
},
{
"code": null,
"e": 5117,
"s": 4984,
"text": "filename-index.js: This file contains all the logic to create short id and attach it with user information and save to the database."
},
{
"code": null,
"e": 5128,
"s": 5117,
"text": "javascript"
},
{
"code": "const express = require('express')const bodyParser = require('body-parser')const shortid = require('shortid')const formTemplet = require('./form')const repo = require('./repository') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML formapp.get('/', (req, res) => { res.send(formTemplet({}))}) // Post route to handle form// submission logic andapp.post('/', (req, res) => { // Fetching user inputs const {name, email} = req.body // Customising id creation shortid.characters('ABCDEFGHI' + 'JKLmNOPQRSTUVWXYZ' + 'abcdefghijklmnopq' + 'rstuvwxyz123456789101112') // Creating new unique id const userId = shortid.generate() // Saving record to the database // with attaching userid to each record repo.create({ userId, name, email }) res.send('Information submitted!')}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)})",
"e": 6154,
"s": 5128,
"text": null
},
{
"code": null,
"e": 6253,
"s": 6154,
"text": "filename – repository.js: This file contain all the logic to create database and interact with it."
},
{
"code": null,
"e": 6264,
"s": 6253,
"text": "javascript"
},
{
"code": "// Importing node.js file system moduleconst fs = require('fs') class Repository { constructor(filename) { // Filename where data are going to store if(!filename) { throw new Error('Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch(err) { // If file not exist it is // created with empty array fs.writeFileSync(this.filename, '[]') } } // Get all existing records async getAll(){ return JSON.parse( await fs.promises.readFile(this.filename, { encoding : 'utf8' }) ) } // Create new record async create(attrs){ // Fetch all existing records const records = await this.getAll() // All the existing records with new // record push back to database records.push(attrs) await fs.promises.writeFile( this.filename, JSON.stringify(records, null, 2) ) return attrs }} // The 'datastore.json' file created// at runtime and all the information// provided via signup form store in// this file in JSON format.module.exports = new Repository('datastore.json')",
"e": 7400,
"s": 6264,
"text": null
},
{
"code": null,
"e": 7467,
"s": 7400,
"text": "filename – form.js: This file contain all the logic to render form"
},
{
"code": null,
"e": 7478,
"s": 7467,
"text": "javascript"
},
{
"code": "const getError = (errors, prop) => { try { return errors.mapped()[prop].msg } catch (error) { return '' }} module.exports = ({errors}) => { return `<!DOCTYPE html><html> <head> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns { margin-top: 100px; } .button { margin-top: 10px } </style></head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <form action='/' method='POST'> <div> <div> <label class='label' id='str'> Name </label> </div> <input class='input' type='text' name='name' placeholder='Name' for='name'> </div> <div> <div> <label class='label' id='email'> Email </label> </div> <input class='input' type='email' name='email' placeholder='Email' for='email'> </div> <div> <button class='button is-info'> Submit </button> </div> </form> </div> </div> </div></body> </html> `}",
"e": 8735,
"s": 7478,
"text": null
},
{
"code": null,
"e": 8743,
"s": 8735,
"text": "Output:"
},
{
"code": null,
"e": 8767,
"s": 8743,
"text": "Submitting information1"
},
{
"code": null,
"e": 8792,
"s": 8767,
"text": "Submitting information 2"
},
{
"code": null,
"e": 8817,
"s": 8792,
"text": "Submitting information 3"
},
{
"code": null,
"e": 8827,
"s": 8817,
"text": "Database:"
},
{
"code": null,
"e": 8870,
"s": 8827,
"text": "Database after submitting the informations"
},
{
"code": null,
"e": 8947,
"s": 8870,
"text": "Note: We have used some Bulma classes in form.js file to design our content."
},
{
"code": null,
"e": 8956,
"s": 8947,
"text": "rkbhola5"
},
{
"code": null,
"e": 8969,
"s": 8956,
"text": "Node.js-Misc"
},
{
"code": null,
"e": 8977,
"s": 8969,
"text": "Node.js"
},
{
"code": null,
"e": 8994,
"s": 8977,
"text": "Web Technologies"
}
] |
PHP | strcasecmp() Function
|
28 Nov, 2018
The strcasecmp() function is a built-in function in PHP and is used to compare two given strings. It is case-insensitive. This function is similar to strncasecmp(), the only difference is that the strncasecmp() provides the provision to specify the number of characters to be used from each string for the comparison.
Syntax:
strcasecmp($string1, $string2)
Parameters: This function accepts two mandatory parameters as shown in the above syntax and are described below:
$string1, $string2: These parameters specify the strings to be compared.
Return Value:This function returns an integer based on the conditions as described below:
strcasecmp() returns 0 – if the two strings are equal.
strcasecmp() returns < 0 – if string1 is less than string2
strcasecmp() returns > 0 – if string1 is greater than string2
Examples:
Input : $str1 = "Geeks for Geeks "
$str2 = "Geeks for Geeks "
Output : 0
Input : $str1 = "Geeks for Geeks"
$str2 = "Hello Geek!"
Output : -1
Below programs illustrate the strcasecmp() function in PHP:
Program 1: When the two strings are identical:
<?php// PHP program to demonstrate the use// of strcasecmp() function $str1 = "Geeks for Geeks ";$str2 = "Geeks for Geeks "; // Both the strings are equal$test=strcasecmp($str1, $str2); echo "$test"; ?>
Output:
0
Program 2: When the two strings are not identical:
<?php// PHP program to demonstrate the use// of strcasecmp() function $str1 = "Geeks for Geeks";$str2 = "Hello Geek!"; // Both the strings are not equal// str1 < str2 $test = strcasecmp($str1, $str2); echo "$test"; ?>
Output:
-1
Program 3: When the two strings are not identical:
<?php// PHP program to demonstrate the use// of strcasecmp() function$str1 = "Hello Geek!";$str2 = "Geeks for Geeks"; // Both the strings are not equal// str1 > str2 $test = strcasecmp($str1, $str2); echo "$test"; ?>
Output:
1
Reference:http://php.net/manual/en/function.strcasecmp.php
anupamsworld
PHP-string
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Nov, 2018"
},
{
"code": null,
"e": 346,
"s": 28,
"text": "The strcasecmp() function is a built-in function in PHP and is used to compare two given strings. It is case-insensitive. This function is similar to strncasecmp(), the only difference is that the strncasecmp() provides the provision to specify the number of characters to be used from each string for the comparison."
},
{
"code": null,
"e": 354,
"s": 346,
"text": "Syntax:"
},
{
"code": null,
"e": 385,
"s": 354,
"text": "strcasecmp($string1, $string2)"
},
{
"code": null,
"e": 498,
"s": 385,
"text": "Parameters: This function accepts two mandatory parameters as shown in the above syntax and are described below:"
},
{
"code": null,
"e": 571,
"s": 498,
"text": "$string1, $string2: These parameters specify the strings to be compared."
},
{
"code": null,
"e": 661,
"s": 571,
"text": "Return Value:This function returns an integer based on the conditions as described below:"
},
{
"code": null,
"e": 716,
"s": 661,
"text": "strcasecmp() returns 0 – if the two strings are equal."
},
{
"code": null,
"e": 775,
"s": 716,
"text": "strcasecmp() returns < 0 – if string1 is less than string2"
},
{
"code": null,
"e": 837,
"s": 775,
"text": "strcasecmp() returns > 0 – if string1 is greater than string2"
},
{
"code": null,
"e": 847,
"s": 837,
"text": "Examples:"
},
{
"code": null,
"e": 1006,
"s": 847,
"text": "Input : $str1 = \"Geeks for Geeks \"\n $str2 = \"Geeks for Geeks \"\nOutput : 0\n\nInput : $str1 = \"Geeks for Geeks\"\n $str2 = \"Hello Geek!\"\nOutput : -1\n"
},
{
"code": null,
"e": 1066,
"s": 1006,
"text": "Below programs illustrate the strcasecmp() function in PHP:"
},
{
"code": null,
"e": 1113,
"s": 1066,
"text": "Program 1: When the two strings are identical:"
},
{
"code": "<?php// PHP program to demonstrate the use// of strcasecmp() function $str1 = \"Geeks for Geeks \";$str2 = \"Geeks for Geeks \"; // Both the strings are equal$test=strcasecmp($str1, $str2); echo \"$test\"; ?>",
"e": 1325,
"s": 1113,
"text": null
},
{
"code": null,
"e": 1333,
"s": 1325,
"text": "Output:"
},
{
"code": null,
"e": 1335,
"s": 1333,
"text": "0"
},
{
"code": null,
"e": 1386,
"s": 1335,
"text": "Program 2: When the two strings are not identical:"
},
{
"code": "<?php// PHP program to demonstrate the use// of strcasecmp() function $str1 = \"Geeks for Geeks\";$str2 = \"Hello Geek!\"; // Both the strings are not equal// str1 < str2 $test = strcasecmp($str1, $str2); echo \"$test\"; ?>",
"e": 1616,
"s": 1386,
"text": null
},
{
"code": null,
"e": 1624,
"s": 1616,
"text": "Output:"
},
{
"code": null,
"e": 1627,
"s": 1624,
"text": "-1"
},
{
"code": null,
"e": 1678,
"s": 1627,
"text": "Program 3: When the two strings are not identical:"
},
{
"code": "<?php// PHP program to demonstrate the use// of strcasecmp() function$str1 = \"Hello Geek!\";$str2 = \"Geeks for Geeks\"; // Both the strings are not equal// str1 > str2 $test = strcasecmp($str1, $str2); echo \"$test\"; ?>",
"e": 1906,
"s": 1678,
"text": null
},
{
"code": null,
"e": 1914,
"s": 1906,
"text": "Output:"
},
{
"code": null,
"e": 1916,
"s": 1914,
"text": "1"
},
{
"code": null,
"e": 1975,
"s": 1916,
"text": "Reference:http://php.net/manual/en/function.strcasecmp.php"
},
{
"code": null,
"e": 1988,
"s": 1975,
"text": "anupamsworld"
},
{
"code": null,
"e": 1999,
"s": 1988,
"text": "PHP-string"
},
{
"code": null,
"e": 2003,
"s": 1999,
"text": "PHP"
},
{
"code": null,
"e": 2020,
"s": 2003,
"text": "Web Technologies"
},
{
"code": null,
"e": 2024,
"s": 2020,
"text": "PHP"
}
] |
Convert PySpark dataframe to list of tuples
|
18 Jul, 2021
In this article, we are going to convert the Pyspark dataframe into a list of tuples.
The rows in the dataframe are stored in the list separated by a comma operator. So we are going to create a dataframe by using a nested list
Creating Dataframe for demonstration:
Python3
# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of students datadata = [["1", "sravan", "vignan", 67, 89], ["2", "ojaswi", "vvit", 78, 89], ["3", "rohith", "vvit", 100, 80], ["4", "sridevi", "vignan", 78, 80], ["1", "sravan", "vignan", 89, 98], ["5", "gnanesh", "iit", 94, 98]] # specify column namescolumns = ['student ID', 'student NAME', 'college', 'subject1', 'subject2'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # displaydataframe.show()
Output:
By converting each row into a tuple and by appending the rows to a list, we can get the data in the list of tuple format.
tuple(): It is used to convert data into tuple format
Syntax: tuple(rows)
Example: Converting dataframe into a list of tuples.
Python3
# define a listl=[] # collect data from the dataframefor i in dataframe.collect(): l.append(tuple(i)) # convert to tuple and append to list # print list of dataprint(l)
Output:
[(‘1’, ‘sravan’, ‘vignan’, 67, 89), (‘2’, ‘ojaswi’, ‘vvit’, 78, 89),
(‘3’, ‘rohith’, ‘vvit’, 100, 80), (‘4’, ‘sridevi’, ‘vignan’, 78, 80),
(‘1’, ‘sravan’, ‘vignan’, 89, 98), (‘5’, ‘gnanesh’, ‘iit’, 94, 98)]
Convert rdd to a tuple using map() function, we are using map() and tuple() functions to convert from rdd
Syntax: rdd.map(tuple)
Example: Using RDD
Python3
# convert dataframe to rddrdd = dataframe.rdd # convert rdd to tupledata = rdd.map(tuple) # display datadata.collect()
Output:
[('1', 'sravan', 'vignan', 67, 89),
('2', 'ojaswi', 'vvit', 78, 89),
('3', 'rohith', 'vvit', 100, 80),
('4', 'sridevi', 'vignan', 78, 80),
('1', 'sravan', 'vignan', 89, 98),
('5', 'gnanesh', 'iit', 94, 98)]
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jul, 2021"
},
{
"code": null,
"e": 114,
"s": 28,
"text": "In this article, we are going to convert the Pyspark dataframe into a list of tuples."
},
{
"code": null,
"e": 255,
"s": 114,
"text": "The rows in the dataframe are stored in the list separated by a comma operator. So we are going to create a dataframe by using a nested list"
},
{
"code": null,
"e": 293,
"s": 255,
"text": "Creating Dataframe for demonstration:"
},
{
"code": null,
"e": 301,
"s": 293,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of students datadata = [[\"1\", \"sravan\", \"vignan\", 67, 89], [\"2\", \"ojaswi\", \"vvit\", 78, 89], [\"3\", \"rohith\", \"vvit\", 100, 80], [\"4\", \"sridevi\", \"vignan\", 78, 80], [\"1\", \"sravan\", \"vignan\", 89, 98], [\"5\", \"gnanesh\", \"iit\", 94, 98]] # specify column namescolumns = ['student ID', 'student NAME', 'college', 'subject1', 'subject2'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # displaydataframe.show()",
"e": 1035,
"s": 301,
"text": null
},
{
"code": null,
"e": 1044,
"s": 1035,
"text": "Output: "
},
{
"code": null,
"e": 1166,
"s": 1044,
"text": "By converting each row into a tuple and by appending the rows to a list, we can get the data in the list of tuple format."
},
{
"code": null,
"e": 1220,
"s": 1166,
"text": "tuple(): It is used to convert data into tuple format"
},
{
"code": null,
"e": 1240,
"s": 1220,
"text": "Syntax: tuple(rows)"
},
{
"code": null,
"e": 1293,
"s": 1240,
"text": "Example: Converting dataframe into a list of tuples."
},
{
"code": null,
"e": 1301,
"s": 1293,
"text": "Python3"
},
{
"code": "# define a listl=[] # collect data from the dataframefor i in dataframe.collect(): l.append(tuple(i)) # convert to tuple and append to list # print list of dataprint(l)",
"e": 1480,
"s": 1301,
"text": null
},
{
"code": null,
"e": 1488,
"s": 1480,
"text": "Output:"
},
{
"code": null,
"e": 1558,
"s": 1488,
"text": "[(‘1’, ‘sravan’, ‘vignan’, 67, 89), (‘2’, ‘ojaswi’, ‘vvit’, 78, 89), "
},
{
"code": null,
"e": 1628,
"s": 1558,
"text": "(‘3’, ‘rohith’, ‘vvit’, 100, 80), (‘4’, ‘sridevi’, ‘vignan’, 78, 80),"
},
{
"code": null,
"e": 1697,
"s": 1628,
"text": " (‘1’, ‘sravan’, ‘vignan’, 89, 98), (‘5’, ‘gnanesh’, ‘iit’, 94, 98)]"
},
{
"code": null,
"e": 1803,
"s": 1697,
"text": "Convert rdd to a tuple using map() function, we are using map() and tuple() functions to convert from rdd"
},
{
"code": null,
"e": 1826,
"s": 1803,
"text": "Syntax: rdd.map(tuple)"
},
{
"code": null,
"e": 1845,
"s": 1826,
"text": "Example: Using RDD"
},
{
"code": null,
"e": 1853,
"s": 1845,
"text": "Python3"
},
{
"code": "# convert dataframe to rddrdd = dataframe.rdd # convert rdd to tupledata = rdd.map(tuple) # display datadata.collect()",
"e": 1974,
"s": 1853,
"text": null
},
{
"code": null,
"e": 1982,
"s": 1974,
"text": "Output:"
},
{
"code": null,
"e": 2189,
"s": 1982,
"text": "[('1', 'sravan', 'vignan', 67, 89),\n('2', 'ojaswi', 'vvit', 78, 89),\n('3', 'rohith', 'vvit', 100, 80),\n('4', 'sridevi', 'vignan', 78, 80),\n('1', 'sravan', 'vignan', 89, 98),\n('5', 'gnanesh', 'iit', 94, 98)]"
},
{
"code": null,
"e": 2196,
"s": 2189,
"text": "Picked"
},
{
"code": null,
"e": 2211,
"s": 2196,
"text": "Python-Pyspark"
},
{
"code": null,
"e": 2218,
"s": 2211,
"text": "Python"
}
] |
Using a variable as format specifier in C
|
29 May, 2017
It is known that, printf() function is an inbuilt library function in C programming language in the header file stdio.h. It is used to print a character, string, float, integer etc. onto the output screen. However, while printing the float values, the number of digits following the decimal point can be controlled by the user. One of the ways to do that is by using formats like %.2f etc. But variables can also be used for formatting format specifiers.
Below example shows how this can be done.
// C program to demonstrate use of variable// in format specifier.#include <stdio.h> int main(){ float b = 6.412355; // using the format specifier %.*f // a = 3 will print value of b upto // 3 decimal places int a = 3; printf("%.*f\n", a, b); // a = 5 will print value of b upto // 3 decimal places a = 5; printf("%.*f\n", a, b); return 0;}
Output:
6.412
6.41235
This article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
cpp-input-output
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
std::string class in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
Queue in C++ Standard Template Library (STL)
Unordered Sets in C++ Standard Template Library
List in C++ Standard Template Library (STL)
std::find in C++
Inline Functions in C++
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n29 May, 2017"
},
{
"code": null,
"e": 509,
"s": 54,
"text": "It is known that, printf() function is an inbuilt library function in C programming language in the header file stdio.h. It is used to print a character, string, float, integer etc. onto the output screen. However, while printing the float values, the number of digits following the decimal point can be controlled by the user. One of the ways to do that is by using formats like %.2f etc. But variables can also be used for formatting format specifiers."
},
{
"code": null,
"e": 551,
"s": 509,
"text": "Below example shows how this can be done."
},
{
"code": "// C program to demonstrate use of variable// in format specifier.#include <stdio.h> int main(){ float b = 6.412355; // using the format specifier %.*f // a = 3 will print value of b upto // 3 decimal places int a = 3; printf(\"%.*f\\n\", a, b); // a = 5 will print value of b upto // 3 decimal places a = 5; printf(\"%.*f\\n\", a, b); return 0;}",
"e": 930,
"s": 551,
"text": null
},
{
"code": null,
"e": 938,
"s": 930,
"text": "Output:"
},
{
"code": null,
"e": 953,
"s": 938,
"text": "6.412\n6.41235\n"
},
{
"code": null,
"e": 1257,
"s": 953,
"text": "This article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 1382,
"s": 1257,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 1399,
"s": 1382,
"text": "cpp-input-output"
},
{
"code": null,
"e": 1403,
"s": 1399,
"text": "C++"
},
{
"code": null,
"e": 1407,
"s": 1403,
"text": "CPP"
},
{
"code": null,
"e": 1505,
"s": 1407,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1529,
"s": 1505,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 1549,
"s": 1529,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 1574,
"s": 1549,
"text": "std::string class in C++"
},
{
"code": null,
"e": 1607,
"s": 1574,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 1651,
"s": 1607,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1696,
"s": 1651,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1744,
"s": 1696,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 1788,
"s": 1744,
"text": "List in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1805,
"s": 1788,
"text": "std::find in C++"
}
] |
How to set the div height to auto-adjust to background size?
|
08 Jun, 2020
Sometimes, while creating a website, it is required to make a div adjust its height automatically according to the background without having the need to set a specific height or min-height. It makes it convenient for the developer while writing the code.
We’ll create an img element inside our div and will set its src same as that of our background image. It’s visibility will be set as hidden so that only the background image will appear. Set the background-repeat property of the div element to “no-repeat” so as not to repeat the image.
Example: Since the image is the background image of the div, therefore, the heading GeeksforGeeks appears over the image.
html
<!DOCTYPE html><html> <head> <title>Title of the document</title> <style> div { background-image: url(https://media.geeksforgeeks.org/wp-content/uploads/20200602195146/0.jpeg); background-repeat: no-repeat; } img { visibility: hidden; } h1 { position: absolute; left: 35%; top: 30%; color: white; } </style> </head> <body> <div> <h1>GeeksforGeeks</h1> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200602195146/0.jpeg" alt="Image" /> </div> </body></html>
Output:
CSS-Properties
Picked
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Form validation using jQuery
Design a web page using HTML and CSS
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
HTTP headers | Content-Type
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Jun, 2020"
},
{
"code": null,
"e": 284,
"s": 28,
"text": "Sometimes, while creating a website, it is required to make a div adjust its height automatically according to the background without having the need to set a specific height or min-height. It makes it convenient for the developer while writing the code. "
},
{
"code": null,
"e": 572,
"s": 284,
"text": "We’ll create an img element inside our div and will set its src same as that of our background image. It’s visibility will be set as hidden so that only the background image will appear. Set the background-repeat property of the div element to “no-repeat” so as not to repeat the image. "
},
{
"code": null,
"e": 695,
"s": 572,
"text": "Example: Since the image is the background image of the div, therefore, the heading GeeksforGeeks appears over the image."
},
{
"code": null,
"e": 700,
"s": 695,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Title of the document</title> <style> div { background-image: url(https://media.geeksforgeeks.org/wp-content/uploads/20200602195146/0.jpeg); background-repeat: no-repeat; } img { visibility: hidden; } h1 { position: absolute; left: 35%; top: 30%; color: white; } </style> </head> <body> <div> <h1>GeeksforGeeks</h1> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200602195146/0.jpeg\" alt=\"Image\" /> </div> </body></html>",
"e": 1430,
"s": 700,
"text": null
},
{
"code": null,
"e": 1439,
"s": 1430,
"text": "Output: "
},
{
"code": null,
"e": 1454,
"s": 1439,
"text": "CSS-Properties"
},
{
"code": null,
"e": 1461,
"s": 1454,
"text": "Picked"
},
{
"code": null,
"e": 1465,
"s": 1461,
"text": "CSS"
},
{
"code": null,
"e": 1470,
"s": 1465,
"text": "HTML"
},
{
"code": null,
"e": 1487,
"s": 1470,
"text": "Web Technologies"
},
{
"code": null,
"e": 1514,
"s": 1487,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 1519,
"s": 1514,
"text": "HTML"
},
{
"code": null,
"e": 1617,
"s": 1519,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1656,
"s": 1617,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 1695,
"s": 1656,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 1734,
"s": 1695,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 1763,
"s": 1734,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 1800,
"s": 1763,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 1824,
"s": 1800,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 1877,
"s": 1824,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 1937,
"s": 1877,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 1998,
"s": 1937,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Python | dtype object length of Numpy array of strings
|
14 Mar, 2019
In this post, we are going to see the datatype of the numpy object when the underlying data is of string type. In numpy, if the underlying data type of the given object is string then the dtype of object is the length of the longest string in the array. This is so because we cannot create variable length string in numpy since numpy needs to know how much space should be allocated for string.
Problem #1 : Given a numpy array whose underlying data is of string type. Find the dtype.
Solution : We will use numpy.dtype attribute to check the dtype of the given object.
# importing the numpy library as npimport numpy as np # Create a numpy arrayarr = np.array(['Ela', 'Ed', 'Brook', 'Sia', 'Katherine']) # Print the arrayprint(arr)
Output :
Now we will check the dtype of the given array object whose underlying data is of string type.
# Print the dtypeprint(arr.dtype)
Output :As we can see in the output, the dtype of the given array object is '<U9' where 9 is the length of the longest string in the given array object.
Let’s verify this by checking the length of the longest string in the given object.
# Use vectorize function of numpylength_checker = np.vectorize(len) # Find the length of each elementarr_len = length_checker(arr) # Print the length of each elementprint(arr_len) # Print the maximum valueprint(arr_len.max())
Output : Problem #2 : Given a numpy array whose underlying data is of string type. Find the dtype.
Solution : We will use numpy.dtype attribute to check the dtype of the given object.
# importing the numpy library as npimport numpy as np # Create a numpy arrayarr = np.array(['New York', 'Lisbon', 'Beijing', 'Quebec']) # Print the arrayprint(arr)
Output :
Now we will check the dtype of the given array object whose underlying data is of string type.
# Print the dtypeprint(arr.dtype)
Output :As we can see in the output, the dtype of the given array object is '<U8' where 8 is the length of the longest string in the given array object.
Let’s verify this by checking the length of the longest string in the given object.
# Use vectorize function of numpylength_checker = np.vectorize(len) # Find the length of each elementarr_len = length_checker(arr) # Print the length of each elementprint(arr_len) # Print the maximum valueprint(arr_len.max())
Output :
Python numpy-program
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Mar, 2019"
},
{
"code": null,
"e": 423,
"s": 28,
"text": "In this post, we are going to see the datatype of the numpy object when the underlying data is of string type. In numpy, if the underlying data type of the given object is string then the dtype of object is the length of the longest string in the array. This is so because we cannot create variable length string in numpy since numpy needs to know how much space should be allocated for string."
},
{
"code": null,
"e": 513,
"s": 423,
"text": "Problem #1 : Given a numpy array whose underlying data is of string type. Find the dtype."
},
{
"code": null,
"e": 598,
"s": 513,
"text": "Solution : We will use numpy.dtype attribute to check the dtype of the given object."
},
{
"code": "# importing the numpy library as npimport numpy as np # Create a numpy arrayarr = np.array(['Ela', 'Ed', 'Brook', 'Sia', 'Katherine']) # Print the arrayprint(arr)",
"e": 763,
"s": 598,
"text": null
},
{
"code": null,
"e": 772,
"s": 763,
"text": "Output :"
},
{
"code": null,
"e": 867,
"s": 772,
"text": "Now we will check the dtype of the given array object whose underlying data is of string type."
},
{
"code": "# Print the dtypeprint(arr.dtype)",
"e": 901,
"s": 867,
"text": null
},
{
"code": null,
"e": 1054,
"s": 901,
"text": "Output :As we can see in the output, the dtype of the given array object is '<U9' where 9 is the length of the longest string in the given array object."
},
{
"code": null,
"e": 1138,
"s": 1054,
"text": "Let’s verify this by checking the length of the longest string in the given object."
},
{
"code": "# Use vectorize function of numpylength_checker = np.vectorize(len) # Find the length of each elementarr_len = length_checker(arr) # Print the length of each elementprint(arr_len) # Print the maximum valueprint(arr_len.max())",
"e": 1367,
"s": 1138,
"text": null
},
{
"code": null,
"e": 1466,
"s": 1367,
"text": "Output : Problem #2 : Given a numpy array whose underlying data is of string type. Find the dtype."
},
{
"code": null,
"e": 1551,
"s": 1466,
"text": "Solution : We will use numpy.dtype attribute to check the dtype of the given object."
},
{
"code": "# importing the numpy library as npimport numpy as np # Create a numpy arrayarr = np.array(['New York', 'Lisbon', 'Beijing', 'Quebec']) # Print the arrayprint(arr)",
"e": 1717,
"s": 1551,
"text": null
},
{
"code": null,
"e": 1726,
"s": 1717,
"text": "Output :"
},
{
"code": null,
"e": 1821,
"s": 1726,
"text": "Now we will check the dtype of the given array object whose underlying data is of string type."
},
{
"code": "# Print the dtypeprint(arr.dtype)",
"e": 1855,
"s": 1821,
"text": null
},
{
"code": null,
"e": 2008,
"s": 1855,
"text": "Output :As we can see in the output, the dtype of the given array object is '<U8' where 8 is the length of the longest string in the given array object."
},
{
"code": null,
"e": 2092,
"s": 2008,
"text": "Let’s verify this by checking the length of the longest string in the given object."
},
{
"code": "# Use vectorize function of numpylength_checker = np.vectorize(len) # Find the length of each elementarr_len = length_checker(arr) # Print the length of each elementprint(arr_len) # Print the maximum valueprint(arr_len.max())",
"e": 2321,
"s": 2092,
"text": null
},
{
"code": null,
"e": 2330,
"s": 2321,
"text": "Output :"
},
{
"code": null,
"e": 2351,
"s": 2330,
"text": "Python numpy-program"
},
{
"code": null,
"e": 2358,
"s": 2351,
"text": "Python"
}
] |
JSTL - Core <fmt:formatDate> Tag
|
The <fmt:formatDate> tag is used to format dates in a variety of ways.
The <fmt:formatDate> tag has the following attributes −
The pattern attribute is used to specify even more precise handling of the date −
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
<title>JSTL fmt:dateNumber Tag</title>
</head>
<body>
<h3>Number Format:</h3>
<c:set var = "now" value = "<% = new java.util.Date()%>" />
<p>Formatted Date (1): <fmt:formatDate type = "time"
value = "${now}" /></p>
<p>Formatted Date (2): <fmt:formatDate type = "date"
value = "${now}" /></p>
<p>Formatted Date (3): <fmt:formatDate type = "both"
value = "${now}" /></p>
<p>Formatted Date (4): <fmt:formatDate type = "both"
dateStyle = "short" timeStyle = "short" value = "${now}" /></p>
<p>Formatted Date (5): <fmt:formatDate type = "both"
dateStyle = "medium" timeStyle = "medium" value = "${now}" /></p>
<p>Formatted Date (6): <fmt:formatDate type = "both"
dateStyle = "long" timeStyle = "long" value = "${now}" /></p>
<p>Formatted Date (7): <fmt:formatDate pattern = "yyyy-MM-dd"
value = "${now}" /></p>
</body>
</html>
The above code will generate the following result −
Date Format:
Formatted Date (1): 14:27:18
Formatted Date (2): 23-Sep-2010
Formatted Date (3): 23-Sep-2010 14:27:18
Formatted Date (4): 23/09/10 14:27
Formatted Date (5): 23-Sep-2010 14:27:18
Formatted Date (6): 23 September 2010 14:27:18 GST
Formatted Date (7): 2010-09-23
Formatted Date (1): 14:27:18
Formatted Date (2): 23-Sep-2010
Formatted Date (3): 23-Sep-2010 14:27:18
Formatted Date (4): 23/09/10 14:27
Formatted Date (5): 23-Sep-2010 14:27:18
Formatted Date (6): 23 September 2010 14:27:18 GST
Formatted Date (7): 2010-09-23
|
[
{
"code": null,
"e": 2445,
"s": 2373,
"text": "The <fmt:formatDate> tag is used to format dates in a variety of ways."
},
{
"code": null,
"e": 2501,
"s": 2445,
"text": "The <fmt:formatDate> tag has the following attributes −"
},
{
"code": null,
"e": 2583,
"s": 2501,
"text": "The pattern attribute is used to specify even more precise handling of the date −"
},
{
"code": null,
"e": 3746,
"s": 2583,
"text": "<%@ taglib prefix = \"c\" uri = \"http://java.sun.com/jsp/jstl/core\" %>\n<%@ taglib prefix = \"fmt\" uri = \"http://java.sun.com/jsp/jstl/fmt\" %>\n\n<html>\n <head>\n <title>JSTL fmt:dateNumber Tag</title>\n </head>\n\n <body>\n <h3>Number Format:</h3>\n <c:set var = \"now\" value = \"<% = new java.util.Date()%>\" />\n\n <p>Formatted Date (1): <fmt:formatDate type = \"time\" \n value = \"${now}\" /></p>\n \n <p>Formatted Date (2): <fmt:formatDate type = \"date\" \n value = \"${now}\" /></p>\n \n <p>Formatted Date (3): <fmt:formatDate type = \"both\" \n value = \"${now}\" /></p>\n \n <p>Formatted Date (4): <fmt:formatDate type = \"both\" \n dateStyle = \"short\" timeStyle = \"short\" value = \"${now}\" /></p>\n \n <p>Formatted Date (5): <fmt:formatDate type = \"both\" \n dateStyle = \"medium\" timeStyle = \"medium\" value = \"${now}\" /></p>\n \n <p>Formatted Date (6): <fmt:formatDate type = \"both\" \n dateStyle = \"long\" timeStyle = \"long\" value = \"${now}\" /></p>\n \n <p>Formatted Date (7): <fmt:formatDate pattern = \"yyyy-MM-dd\" \n value = \"${now}\" /></p>\n\n </body>\n</html>"
},
{
"code": null,
"e": 3798,
"s": 3746,
"text": "The above code will generate the following result −"
},
{
"code": null,
"e": 4072,
"s": 3798,
"text": "Date Format:\nFormatted Date (1): 14:27:18\nFormatted Date (2): 23-Sep-2010\nFormatted Date (3): 23-Sep-2010 14:27:18\nFormatted Date (4): 23/09/10 14:27\nFormatted Date (5): 23-Sep-2010 14:27:18\nFormatted Date (6): 23 September 2010 14:27:18 GST\nFormatted Date (7): 2010-09-23\n"
},
{
"code": null,
"e": 4101,
"s": 4072,
"text": "Formatted Date (1): 14:27:18"
},
{
"code": null,
"e": 4133,
"s": 4101,
"text": "Formatted Date (2): 23-Sep-2010"
},
{
"code": null,
"e": 4174,
"s": 4133,
"text": "Formatted Date (3): 23-Sep-2010 14:27:18"
},
{
"code": null,
"e": 4209,
"s": 4174,
"text": "Formatted Date (4): 23/09/10 14:27"
},
{
"code": null,
"e": 4250,
"s": 4209,
"text": "Formatted Date (5): 23-Sep-2010 14:27:18"
},
{
"code": null,
"e": 4301,
"s": 4250,
"text": "Formatted Date (6): 23 September 2010 14:27:18 GST"
}
] |
UI Testing with Espresso in Android Studio
|
11 Jul, 2021
UI testing is the process of testing the visual elements of an application to ensure whether they appropriately meet the anticipated functionality. Verifying the application manually whether it works or not is a time taking and tiring process, but using espresso we can write automated tests that run fast and scale well. Espresso is an automated user interface testing framework for Android, developed by Google in 2013. In this article, we will be discussing
The basics of the Espresso framework, How to set up the Espresso framework in Android, and How to automate the testing environment with a simple android application.
The basics of the Espresso framework,
How to set up the Espresso framework in Android, and
How to automate the testing environment with a simple android application.
Anatomy of a UI Test
Find a View
Perform an action
Inspect the result
Espresso consists of mainly three components:
ViewMatchers – It is used for finding a view using different attributes like withId(), withText(), withTagKey(), etc.
ViewActions – It is used for performing the actions on the view defined in ViewMatchers like click(), longClick(), scrollTo(), etc.
ViewAssertions – It is used to assert that the view found using ViewMatchers and expected views are the same using match(), doesNotExist(), etc.
Since espresso takes care of synchronization with any UI events, we don’t have to worry about any view state transitions and implementation details. Now let’s have a look at the boilerplate code for running an automated test.
onView(ViewMatcher) // onView takes a viewMatcher like R.id.button
.perform(ViewAction) // perform takes a viewAction like pressing the button
.check(ViewAssertion); // check inspects if the output result is same as the expected result.
In this article, we will be using only certain types of ViewMatchers, ViewActions, and ViewAssertions, however, there are many more of them which can be found on the official website https://developer.android.com/training/testing/espresso/cheat-sheet
Step 1: Add the espresso library in dependencies
Navigate to app > Gradle Script > build.gradle (Module:app), add the following lines of code, and sync the project.
defaultConfig {
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
dependencies {
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
androidTestImplementation 'androidx.test:runner:1.3.0'
androidTestImplementation 'androidx.test:rules:1.3.0'
}
Step 2: Turn off animations from the Android device
Navigate to Settings > Developer options and turn off the following options:
Window animation scale
Transition animation scale
Animator duration scale
We will be building an application where a user can choose his preferred language, and the chosen language is displayed in the textView. Now, we will be implementing an automated test to validate if the chosen preferred language of the user is displayed in the TextView or not. A sample GIF is given below to get an idea about what we are going to do in this part.
Step 1: Create a New Project
To create a new project in Android Studio please refer to https://www.geeksforgeeks.org/android-how-to-create-start-a-new-project-in-android-studio/. Note that select Java as the programming language.
Step 2: Set up the espresso framework in Android as discussed in part 2 above.
Step 3: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/select_language" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="28dp" android:text="Select Your Preferred Language" android:textSize="19sp" android:textStyle="bold" /> <!-- LinearLayout contains all the languages button in a vertical order--> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/select_language" android:id="@+id/linear_layout" android:layout_centerHorizontal="true" android:layout_margin="22dp" android:orientation="vertical"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="16dp" android:id="@+id/english" android:text="English" android:onClick="onClick" android:textAllCaps="true" android:textColor="#0F9D58" android:textStyle="bold" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="16dp" android:id="@+id/german" android:onClick="onClick" android:text="German" android:textAllCaps="true" android:textColor="#0F9D58" android:textStyle="bold" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/french" android:padding="16dp" android:onClick="onClick" android:text="French" android:textAllCaps="true" android:textColor="#0F9D58" android:textStyle="bold" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#0F9D58" android:id="@+id/hindi" android:onClick="onClick" android:text="Hindi" android:padding="16dp" android:textAllCaps="true" android:textStyle="bold"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#0F9D58" android:id="@+id/urdu" android:onClick="onClick" android:text="Urdu" android:padding="16dp" android:textAllCaps="true" android:textStyle="bold"/> </LinearLayout> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/chosen" android:layout_centerHorizontal="true" android:layout_marginTop="28dp" android:text="Your Chosen Language is : " android:textSize="19sp" android:textStyle="bold" android:layout_below="@+id/linear_layout"/> <!-- The following textView shows the preferred language chosen by the user. --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/preferred_language" android:layout_centerHorizontal="true" android:layout_marginTop="28dp" android:hint="-------------" android:textSize="19sp" android:textStyle="bold" android:layout_below="@+id/chosen"/> </RelativeLayout>
Step 4: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file.
Java
import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;import android.view.View;import android.widget.TextView; public class MainActivity extends AppCompatActivity { // Textview to show the language // chosen by the user TextView preferred_language; // onClick is called whenever // a user clicks a button public void onClick(View view) { // whenever a user chooses a preferred language // by tapping button, it changes the chosen // language textView switch (view.getId()){ case R.id.english: preferred_language.setText("English"); break; case R.id.french: preferred_language.setText("French"); break; case R.id.german: preferred_language.setText("German"); break; case R.id.hindi: preferred_language.setText("Hindi"); break; case R.id.urdu: preferred_language.setText("Urdu"); break; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing the textview preferred_language = findViewById(R.id.preferred_language); }}
Step 5: Navigate to app > java > package-name(androidTest) > ExampleInstrumentedTest. Open the ExampleInstrumentedTest.java file and refer to the following code. Below is the code for the ExampleInstrumentedTest.java file. Comments are added to describe ViewMatchers, ViewActions, and ViewAssertions in the following code snippet.
Java
import androidx.test.ext.junit.rules.ActivityScenarioRule;import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Rule;import org.junit.Test;import org.junit.runner.RunWith; import static androidx.test.espresso.Espresso.onView;import static androidx.test.espresso.action.ViewActions.click;import static androidx.test.espresso.assertion.ViewAssertions.matches;import static androidx.test.espresso.matcher.ViewMatchers.withId;import static androidx.test.espresso.matcher.ViewMatchers.withText; @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest{ // rule specifies that we are // running test on MainActivity @Rule public ActivityScenarioRule<MainActivity> activityScenarioRule = new ActivityScenarioRule<>(MainActivity.class); // test to check if the preferred language // of user is displayed under the chosen language or not @Test public void selectLanguageAndCheck(){ onView(withId(R.id.german)) // ViewMatchers - withId(R.id.german) is to // specify that we are looking for Button // with id = R.id.german .perform(click()); // ViewActions - Performs click action on view. onView(withId(R.id.preferred_language)) // ViewMatchers - withId(R.id.preferred_language) // is to specify that we are looking for a TextView // with id = R.id.preferred_language .check(matches(withText("German"))); // ViewAssertions - validates if preferred_language // matches with the text "German" since we // pressed german language button. }}
Step 6 : Navigate to app > java > package-name(androidTest) > ExampleInstrumentedTest > Right Click and choose Run ExampleInstrumentedTest. This will run an automated test on an emulator/physical device and the result will be shown in the console once the test reaches completion.
Output: The test case is passed and it took only 666ms to run an automated test. This shows the espresso library can be quite handy when we need to test the UI elements in an application even on a very large scale. A slow-motion video of the test case is attached below since automated tests are quite fast.
GitHub Repository: https://github.com/garg-lucifer/GFGespresso
Android-Studio
Picked
Android
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android SDK and it's Components
Flutter - Custom Bottom Navigation Bar
How to Communicate Between Fragments in Android?
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Flutter - Stack Widget
Introduction to Android Development
Activity Lifecycle in Android with Demo App
Fragment Lifecycle in Android
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Jul, 2021"
},
{
"code": null,
"e": 490,
"s": 28,
"text": "UI testing is the process of testing the visual elements of an application to ensure whether they appropriately meet the anticipated functionality. Verifying the application manually whether it works or not is a time taking and tiring process, but using espresso we can write automated tests that run fast and scale well. Espresso is an automated user interface testing framework for Android, developed by Google in 2013. In this article, we will be discussing "
},
{
"code": null,
"e": 656,
"s": 490,
"text": "The basics of the Espresso framework, How to set up the Espresso framework in Android, and How to automate the testing environment with a simple android application."
},
{
"code": null,
"e": 695,
"s": 656,
"text": "The basics of the Espresso framework, "
},
{
"code": null,
"e": 749,
"s": 695,
"text": "How to set up the Espresso framework in Android, and "
},
{
"code": null,
"e": 824,
"s": 749,
"text": "How to automate the testing environment with a simple android application."
},
{
"code": null,
"e": 845,
"s": 824,
"text": "Anatomy of a UI Test"
},
{
"code": null,
"e": 857,
"s": 845,
"text": "Find a View"
},
{
"code": null,
"e": 875,
"s": 857,
"text": "Perform an action"
},
{
"code": null,
"e": 894,
"s": 875,
"text": "Inspect the result"
},
{
"code": null,
"e": 940,
"s": 894,
"text": "Espresso consists of mainly three components:"
},
{
"code": null,
"e": 1058,
"s": 940,
"text": "ViewMatchers – It is used for finding a view using different attributes like withId(), withText(), withTagKey(), etc."
},
{
"code": null,
"e": 1190,
"s": 1058,
"text": "ViewActions – It is used for performing the actions on the view defined in ViewMatchers like click(), longClick(), scrollTo(), etc."
},
{
"code": null,
"e": 1335,
"s": 1190,
"text": "ViewAssertions – It is used to assert that the view found using ViewMatchers and expected views are the same using match(), doesNotExist(), etc."
},
{
"code": null,
"e": 1562,
"s": 1335,
"text": "Since espresso takes care of synchronization with any UI events, we don’t have to worry about any view state transitions and implementation details. Now let’s have a look at the boilerplate code for running an automated test. "
},
{
"code": null,
"e": 1815,
"s": 1562,
"text": "onView(ViewMatcher) // onView takes a viewMatcher like R.id.button\n .perform(ViewAction) // perform takes a viewAction like pressing the button \n .check(ViewAssertion); // check inspects if the output result is same as the expected result. "
},
{
"code": null,
"e": 2066,
"s": 1815,
"text": "In this article, we will be using only certain types of ViewMatchers, ViewActions, and ViewAssertions, however, there are many more of them which can be found on the official website https://developer.android.com/training/testing/espresso/cheat-sheet"
},
{
"code": null,
"e": 2115,
"s": 2066,
"text": "Step 1: Add the espresso library in dependencies"
},
{
"code": null,
"e": 2232,
"s": 2115,
"text": "Navigate to app > Gradle Script > build.gradle (Module:app), add the following lines of code, and sync the project. "
},
{
"code": null,
"e": 2322,
"s": 2232,
"text": "defaultConfig {\n testInstrumentationRunner \"androidx.test.runner.AndroidJUnitRunner\"\n}"
},
{
"code": null,
"e": 2593,
"s": 2322,
"text": "dependencies {\n androidTestImplementation 'androidx.test.ext:junit:1.1.2'\n androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'\n androidTestImplementation 'androidx.test:runner:1.3.0'\n androidTestImplementation 'androidx.test:rules:1.3.0'\n}"
},
{
"code": null,
"e": 2645,
"s": 2593,
"text": "Step 2: Turn off animations from the Android device"
},
{
"code": null,
"e": 2723,
"s": 2645,
"text": "Navigate to Settings > Developer options and turn off the following options: "
},
{
"code": null,
"e": 2746,
"s": 2723,
"text": "Window animation scale"
},
{
"code": null,
"e": 2773,
"s": 2746,
"text": "Transition animation scale"
},
{
"code": null,
"e": 2797,
"s": 2773,
"text": "Animator duration scale"
},
{
"code": null,
"e": 3163,
"s": 2797,
"text": "We will be building an application where a user can choose his preferred language, and the chosen language is displayed in the textView. Now, we will be implementing an automated test to validate if the chosen preferred language of the user is displayed in the TextView or not. A sample GIF is given below to get an idea about what we are going to do in this part."
},
{
"code": null,
"e": 3192,
"s": 3163,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 3393,
"s": 3192,
"text": "To create a new project in Android Studio please refer to https://www.geeksforgeeks.org/android-how-to-create-start-a-new-project-in-android-studio/. Note that select Java as the programming language."
},
{
"code": null,
"e": 3472,
"s": 3393,
"text": "Step 2: Set up the espresso framework in Android as discussed in part 2 above."
},
{
"code": null,
"e": 3520,
"s": 3472,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 3663,
"s": 3520,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 3667,
"s": 3663,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout 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:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <TextView android:id=\"@+id/select_language\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"28dp\" android:text=\"Select Your Preferred Language\" android:textSize=\"19sp\" android:textStyle=\"bold\" /> <!-- LinearLayout contains all the languages button in a vertical order--> <LinearLayout android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/select_language\" android:id=\"@+id/linear_layout\" android:layout_centerHorizontal=\"true\" android:layout_margin=\"22dp\" android:orientation=\"vertical\"> <Button android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:padding=\"16dp\" android:id=\"@+id/english\" android:text=\"English\" android:onClick=\"onClick\" android:textAllCaps=\"true\" android:textColor=\"#0F9D58\" android:textStyle=\"bold\" /> <Button android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:padding=\"16dp\" android:id=\"@+id/german\" android:onClick=\"onClick\" android:text=\"German\" android:textAllCaps=\"true\" android:textColor=\"#0F9D58\" android:textStyle=\"bold\" /> <Button android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:id=\"@+id/french\" android:padding=\"16dp\" android:onClick=\"onClick\" android:text=\"French\" android:textAllCaps=\"true\" android:textColor=\"#0F9D58\" android:textStyle=\"bold\" /> <Button android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:textColor=\"#0F9D58\" android:id=\"@+id/hindi\" android:onClick=\"onClick\" android:text=\"Hindi\" android:padding=\"16dp\" android:textAllCaps=\"true\" android:textStyle=\"bold\"/> <Button android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:textColor=\"#0F9D58\" android:id=\"@+id/urdu\" android:onClick=\"onClick\" android:text=\"Urdu\" android:padding=\"16dp\" android:textAllCaps=\"true\" android:textStyle=\"bold\"/> </LinearLayout> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:id=\"@+id/chosen\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"28dp\" android:text=\"Your Chosen Language is : \" android:textSize=\"19sp\" android:textStyle=\"bold\" android:layout_below=\"@+id/linear_layout\"/> <!-- The following textView shows the preferred language chosen by the user. --> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:id=\"@+id/preferred_language\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"28dp\" android:hint=\"-------------\" android:textSize=\"19sp\" android:textStyle=\"bold\" android:layout_below=\"@+id/chosen\"/> </RelativeLayout>",
"e": 7474,
"s": 3667,
"text": null
},
{
"code": null,
"e": 7522,
"s": 7474,
"text": "Step 4: Working with the MainActivity.java file"
},
{
"code": null,
"e": 7639,
"s": 7522,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. "
},
{
"code": null,
"e": 7644,
"s": 7639,
"text": "Java"
},
{
"code": "import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;import android.view.View;import android.widget.TextView; public class MainActivity extends AppCompatActivity { // Textview to show the language // chosen by the user TextView preferred_language; // onClick is called whenever // a user clicks a button public void onClick(View view) { // whenever a user chooses a preferred language // by tapping button, it changes the chosen // language textView switch (view.getId()){ case R.id.english: preferred_language.setText(\"English\"); break; case R.id.french: preferred_language.setText(\"French\"); break; case R.id.german: preferred_language.setText(\"German\"); break; case R.id.hindi: preferred_language.setText(\"Hindi\"); break; case R.id.urdu: preferred_language.setText(\"Urdu\"); break; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing the textview preferred_language = findViewById(R.id.preferred_language); }}",
"e": 9022,
"s": 7644,
"text": null
},
{
"code": null,
"e": 9354,
"s": 9022,
"text": "Step 5: Navigate to app > java > package-name(androidTest) > ExampleInstrumentedTest. Open the ExampleInstrumentedTest.java file and refer to the following code. Below is the code for the ExampleInstrumentedTest.java file. Comments are added to describe ViewMatchers, ViewActions, and ViewAssertions in the following code snippet. "
},
{
"code": null,
"e": 9359,
"s": 9354,
"text": "Java"
},
{
"code": "import androidx.test.ext.junit.rules.ActivityScenarioRule;import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Rule;import org.junit.Test;import org.junit.runner.RunWith; import static androidx.test.espresso.Espresso.onView;import static androidx.test.espresso.action.ViewActions.click;import static androidx.test.espresso.assertion.ViewAssertions.matches;import static androidx.test.espresso.matcher.ViewMatchers.withId;import static androidx.test.espresso.matcher.ViewMatchers.withText; @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest{ // rule specifies that we are // running test on MainActivity @Rule public ActivityScenarioRule<MainActivity> activityScenarioRule = new ActivityScenarioRule<>(MainActivity.class); // test to check if the preferred language // of user is displayed under the chosen language or not @Test public void selectLanguageAndCheck(){ onView(withId(R.id.german)) // ViewMatchers - withId(R.id.german) is to // specify that we are looking for Button // with id = R.id.german .perform(click()); // ViewActions - Performs click action on view. onView(withId(R.id.preferred_language)) // ViewMatchers - withId(R.id.preferred_language) // is to specify that we are looking for a TextView // with id = R.id.preferred_language .check(matches(withText(\"German\"))); // ViewAssertions - validates if preferred_language // matches with the text \"German\" since we // pressed german language button. }}",
"e": 11185,
"s": 9359,
"text": null
},
{
"code": null,
"e": 11467,
"s": 11185,
"text": "Step 6 : Navigate to app > java > package-name(androidTest) > ExampleInstrumentedTest > Right Click and choose Run ExampleInstrumentedTest. This will run an automated test on an emulator/physical device and the result will be shown in the console once the test reaches completion. "
},
{
"code": null,
"e": 11775,
"s": 11467,
"text": "Output: The test case is passed and it took only 666ms to run an automated test. This shows the espresso library can be quite handy when we need to test the UI elements in an application even on a very large scale. A slow-motion video of the test case is attached below since automated tests are quite fast."
},
{
"code": null,
"e": 11838,
"s": 11775,
"text": "GitHub Repository: https://github.com/garg-lucifer/GFGespresso"
},
{
"code": null,
"e": 11853,
"s": 11838,
"text": "Android-Studio"
},
{
"code": null,
"e": 11860,
"s": 11853,
"text": "Picked"
},
{
"code": null,
"e": 11868,
"s": 11860,
"text": "Android"
},
{
"code": null,
"e": 11876,
"s": 11868,
"text": "Android"
},
{
"code": null,
"e": 11974,
"s": 11876,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12043,
"s": 11974,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 12075,
"s": 12043,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 12114,
"s": 12075,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 12163,
"s": 12114,
"text": "How to Communicate Between Fragments in Android?"
},
{
"code": null,
"e": 12205,
"s": 12163,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 12256,
"s": 12205,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 12279,
"s": 12256,
"text": "Flutter - Stack Widget"
},
{
"code": null,
"e": 12315,
"s": 12279,
"text": "Introduction to Android Development"
},
{
"code": null,
"e": 12359,
"s": 12315,
"text": "Activity Lifecycle in Android with Demo App"
}
] |
Remove rows with empty cells in R
|
23 May, 2021
A dataframe may contain elements belonging to different data types as cells. However, it may contain blank rows or rows containing missing values in all the columns. These rows are equivalent to dummy records and are termed empty rows. There are multiple ways to remove them.
A vector is declared to keep the indexes of all the rows containing all blank values. A for loop iteration is done over the rows of the dataframe. A counter is set to 0 to store all blank values in each row. Another iteration is done through columns. The cell value is compared to the blank value, and if it satisfies the condition the counter is incremented. After each inner loop iteration, the counter value is compared to the number of columns in the dataframe. If these values are equivalent, the row index is appended to the vector. After the end of the outer loop, the row indices stored in the vector are deleted using the ‘-‘ in front of the row index vector.
The time complexity of this approach is O(m *n ), where m is the number of rows and n is the number of columns.
Example:
R
# declaring a dataframedata_frame = data.frame(col1 = c("","b","","","e") , col2 = c("",2,"",4,5), col3= c("",FALSE,"","", TRUE)) print ("Original dataframe")print (data_frame) # declaring an empty vector to store # the rows with all the blank valuesvec <- c() # looping the rowsfor (i in 1:nrow(data_frame)){ # counter for blank values in # each row count = 0 # looping through columns for(j in 1:ncol(data_frame)){ # checking if the value is blank if(isTRUE(data_frame[i,j] == "")){ count = count + 1 } } # if count is equivalent to number # of columns if(count == ncol(data_frame)){ # append row number vec <- append(vec,i) }} # deleting rows using index in vectordata_frame_mod <- data_frame[-vec, ] print ("Modified dataframe")print (data_frame_mod)
Output
[1] "Original dataframe"
col1 col2 col3
1
2 b 2 FALSE
3
4 4
5 e 5 TRUE
[1] "Modified dataframe"
col1 col2 col3
2 b 2 FALSE
4 4
5 e 5 TRUE
apply() method in R is used to apply a specified function over the R object, vector, dataframe, or a matrix. This method returns a vector or array or list of values obtained by applying the function to the corresponding of an array or matrix.
Syntax: apply(df , axis, FUN, ...)
Parameter :
df – A dataframe or matrix
axis – The axis over which to apply the function. For a dataframe, 1 indicates rows, 2 indicates columns and c(1, 2) indicates rows and columns.
FUN – The function to be applied.
The constraint that the dataframe is subjected to is to check that the cell values are not “”, that is blank. In this approach, FUN is equivalent to ‘all’, since all the columns for any particular row should satisfy the condition, of not having a blank cell value.
Example:
R
# declaring an empty dataframedata_frame = data.frame(col1 = c("","b","","","e") , col2 = c("",2,"",4,5), col3= c("",FALSE,"","", TRUE)) print ("Original dataframe")print (data_frame) # checking where the cells are not all emptydata_frame_mod <- data_frame[!apply(data_frame == "", 1, all), ] print ("Modified dataframe")print (data_frame_mod )
Output
[1] "Original dataframe"
col1 col2 col3
1
2 b 2 FALSE
3
4 4
5 e 5 TRUE
[1] "Modified dataframe"
col1 col2 col3
2 b 2 FALSE
4 4
5 e 5 TRUE
A dataframe can consist of missing values or NA contained in replacement to the cell values. This approach uses many inbuilt R methods to remove all the rows with NA.
The number of columns of the dataframe can be checked using the ncol() method.
Syntax:
ncol( df)
Individual cell values are checked if the values are NA or not, by using the is.na() method. The dataframe is passed as an argument to this method. It returns a dataframe with dimensions equivalent to the original dataframe. It consists of logical values, TRUE if the value is NA, FALSE otherwise.
Syntax:
na_df <- is.na(df)
The rowSums() method is applied over the dataframe consisting of logical values obtained from the previous step. It returns the count of the total sum of NA values encountered in each row. The resultant vector contains the integer denoting a number of missing values of each row.
Syntax:
rowSums(na_df)
The rows where the row sum of na values of each row is not equivalent to the number of columns, those rows are stored in a separate variable as an output. If the two are equal, it implies that all columns contain NA in that specific row.
Example:
R
# declaring an empty dataframedata_frame = data.frame(col1 = c(NA,"b",NA,NA,"e") , col2 = c(NA,2,NA,4,5), col3= c(NA,FALSE,NA,NA, TRUE)) print ("Original dataframe")print (data_frame) # checking number of columnscols <- ncol(data_frame) # checking for which elements have # missing valuesis_na <- is.na(data_frame) # computes total number of nas # encountered in each rowrow_na <- rowSums(is_na) # checking where the cells are not # all NAdata_frame_mod <- data_frame[row_na != cols, ] print ("Modified dataframe")print (data_frame_mod )
Output
[1] "Original dataframe"
col1 col2 col3
1 <NA> NA NA
2 b 2 FALSE
3 <NA> NA NA
4 <NA> 4 NA
5 e 5 TRUE
[1] "Modified dataframe"
col1 col2 col3
2 b 2 FALSE
4 <NA> 4 NA
5 e 5 TRUE
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.
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to change Row Names of DataFrame in R ?
How to filter R DataFrame by values in a column?
Remove rows with NA in one column of R DataFrame
Replace Specific Characters in String in R
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 May, 2021"
},
{
"code": null,
"e": 305,
"s": 28,
"text": "A dataframe may contain elements belonging to different data types as cells. However, it may contain blank rows or rows containing missing values in all the columns. These rows are equivalent to dummy records and are termed empty rows. There are multiple ways to remove them. "
},
{
"code": null,
"e": 975,
"s": 305,
"text": "A vector is declared to keep the indexes of all the rows containing all blank values. A for loop iteration is done over the rows of the dataframe. A counter is set to 0 to store all blank values in each row. Another iteration is done through columns. The cell value is compared to the blank value, and if it satisfies the condition the counter is incremented. After each inner loop iteration, the counter value is compared to the number of columns in the dataframe. If these values are equivalent, the row index is appended to the vector. After the end of the outer loop, the row indices stored in the vector are deleted using the ‘-‘ in front of the row index vector. "
},
{
"code": null,
"e": 1087,
"s": 975,
"text": "The time complexity of this approach is O(m *n ), where m is the number of rows and n is the number of columns."
},
{
"code": null,
"e": 1096,
"s": 1087,
"text": "Example:"
},
{
"code": null,
"e": 1098,
"s": 1096,
"text": "R"
},
{
"code": "# declaring a dataframedata_frame = data.frame(col1 = c(\"\",\"b\",\"\",\"\",\"e\") , col2 = c(\"\",2,\"\",4,5), col3= c(\"\",FALSE,\"\",\"\", TRUE)) print (\"Original dataframe\")print (data_frame) # declaring an empty vector to store # the rows with all the blank valuesvec <- c() # looping the rowsfor (i in 1:nrow(data_frame)){ # counter for blank values in # each row count = 0 # looping through columns for(j in 1:ncol(data_frame)){ # checking if the value is blank if(isTRUE(data_frame[i,j] == \"\")){ count = count + 1 } } # if count is equivalent to number # of columns if(count == ncol(data_frame)){ # append row number vec <- append(vec,i) }} # deleting rows using index in vectordata_frame_mod <- data_frame[-vec, ] print (\"Modified dataframe\")print (data_frame_mod)",
"e": 2021,
"s": 1098,
"text": null
},
{
"code": null,
"e": 2028,
"s": 2021,
"text": "Output"
},
{
"code": null,
"e": 2256,
"s": 2028,
"text": "[1] \"Original dataframe\"\n col1 col2 col3\n1 \n2 b 2 FALSE\n3 \n4 4 \n5 e 5 TRUE\n[1] \"Modified dataframe\"\n col1 col2 col3\n2 b 2 FALSE\n4 4 \n5 e 5 TRUE"
},
{
"code": null,
"e": 2499,
"s": 2256,
"text": "apply() method in R is used to apply a specified function over the R object, vector, dataframe, or a matrix. This method returns a vector or array or list of values obtained by applying the function to the corresponding of an array or matrix."
},
{
"code": null,
"e": 2534,
"s": 2499,
"text": "Syntax: apply(df , axis, FUN, ...)"
},
{
"code": null,
"e": 2546,
"s": 2534,
"text": "Parameter :"
},
{
"code": null,
"e": 2573,
"s": 2546,
"text": "df – A dataframe or matrix"
},
{
"code": null,
"e": 2718,
"s": 2573,
"text": "axis – The axis over which to apply the function. For a dataframe, 1 indicates rows, 2 indicates columns and c(1, 2) indicates rows and columns."
},
{
"code": null,
"e": 2752,
"s": 2718,
"text": "FUN – The function to be applied."
},
{
"code": null,
"e": 3018,
"s": 2752,
"text": "The constraint that the dataframe is subjected to is to check that the cell values are not “”, that is blank. In this approach, FUN is equivalent to ‘all’, since all the columns for any particular row should satisfy the condition, of not having a blank cell value. "
},
{
"code": null,
"e": 3027,
"s": 3018,
"text": "Example:"
},
{
"code": null,
"e": 3029,
"s": 3027,
"text": "R"
},
{
"code": "# declaring an empty dataframedata_frame = data.frame(col1 = c(\"\",\"b\",\"\",\"\",\"e\") , col2 = c(\"\",2,\"\",4,5), col3= c(\"\",FALSE,\"\",\"\", TRUE)) print (\"Original dataframe\")print (data_frame) # checking where the cells are not all emptydata_frame_mod <- data_frame[!apply(data_frame == \"\", 1, all), ] print (\"Modified dataframe\")print (data_frame_mod )",
"e": 3425,
"s": 3029,
"text": null
},
{
"code": null,
"e": 3432,
"s": 3425,
"text": "Output"
},
{
"code": null,
"e": 3660,
"s": 3432,
"text": "[1] \"Original dataframe\"\n col1 col2 col3\n1 \n2 b 2 FALSE\n3 \n4 4 \n5 e 5 TRUE\n[1] \"Modified dataframe\"\n col1 col2 col3\n2 b 2 FALSE\n4 4 \n5 e 5 TRUE"
},
{
"code": null,
"e": 3828,
"s": 3660,
"text": "A dataframe can consist of missing values or NA contained in replacement to the cell values. This approach uses many inbuilt R methods to remove all the rows with NA. "
},
{
"code": null,
"e": 3907,
"s": 3828,
"text": "The number of columns of the dataframe can be checked using the ncol() method."
},
{
"code": null,
"e": 3915,
"s": 3907,
"text": "Syntax:"
},
{
"code": null,
"e": 3925,
"s": 3915,
"text": "ncol( df)"
},
{
"code": null,
"e": 4223,
"s": 3925,
"text": "Individual cell values are checked if the values are NA or not, by using the is.na() method. The dataframe is passed as an argument to this method. It returns a dataframe with dimensions equivalent to the original dataframe. It consists of logical values, TRUE if the value is NA, FALSE otherwise."
},
{
"code": null,
"e": 4231,
"s": 4223,
"text": "Syntax:"
},
{
"code": null,
"e": 4250,
"s": 4231,
"text": "na_df <- is.na(df)"
},
{
"code": null,
"e": 4530,
"s": 4250,
"text": "The rowSums() method is applied over the dataframe consisting of logical values obtained from the previous step. It returns the count of the total sum of NA values encountered in each row. The resultant vector contains the integer denoting a number of missing values of each row."
},
{
"code": null,
"e": 4538,
"s": 4530,
"text": "Syntax:"
},
{
"code": null,
"e": 4553,
"s": 4538,
"text": "rowSums(na_df)"
},
{
"code": null,
"e": 4791,
"s": 4553,
"text": "The rows where the row sum of na values of each row is not equivalent to the number of columns, those rows are stored in a separate variable as an output. If the two are equal, it implies that all columns contain NA in that specific row."
},
{
"code": null,
"e": 4800,
"s": 4791,
"text": "Example:"
},
{
"code": null,
"e": 4802,
"s": 4800,
"text": "R"
},
{
"code": "# declaring an empty dataframedata_frame = data.frame(col1 = c(NA,\"b\",NA,NA,\"e\") , col2 = c(NA,2,NA,4,5), col3= c(NA,FALSE,NA,NA, TRUE)) print (\"Original dataframe\")print (data_frame) # checking number of columnscols <- ncol(data_frame) # checking for which elements have # missing valuesis_na <- is.na(data_frame) # computes total number of nas # encountered in each rowrow_na <- rowSums(is_na) # checking where the cells are not # all NAdata_frame_mod <- data_frame[row_na != cols, ] print (\"Modified dataframe\")print (data_frame_mod )",
"e": 5394,
"s": 4802,
"text": null
},
{
"code": null,
"e": 5401,
"s": 5394,
"text": "Output"
},
{
"code": null,
"e": 5629,
"s": 5401,
"text": "[1] \"Original dataframe\"\n col1 col2 col3\n1 <NA> NA NA\n2 b 2 FALSE\n3 <NA> NA NA\n4 <NA> 4 NA\n5 e 5 TRUE\n[1] \"Modified dataframe\"\n col1 col2 col3\n2 b 2 FALSE\n4 <NA> 4 NA\n5 e 5 TRUE"
},
{
"code": null,
"e": 5636,
"s": 5629,
"text": "Picked"
},
{
"code": null,
"e": 5657,
"s": 5636,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 5669,
"s": 5657,
"text": "R-DataFrame"
},
{
"code": null,
"e": 5680,
"s": 5669,
"text": "R Language"
},
{
"code": null,
"e": 5691,
"s": 5680,
"text": "R Programs"
},
{
"code": null,
"e": 5789,
"s": 5691,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5841,
"s": 5789,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 5893,
"s": 5841,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 5951,
"s": 5893,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 5983,
"s": 5951,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 6018,
"s": 5983,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 6076,
"s": 6018,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 6120,
"s": 6076,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 6169,
"s": 6120,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 6218,
"s": 6169,
"text": "Remove rows with NA in one column of R DataFrame"
}
] |
Convert XML to CSV in Python
|
24 Jan, 2021
Prerequisites: Pandas
XML stands for Extensible Markup Language. This format is extremely useful for keeping track of small to medium amounts of data. As the data in XML format is not readable by general users, we need to convert it to some user-friendly format like CSV. CSV is easily readable and can be opened using any editor.
Now, let’s take an example to convert XML data to CSV data using python. We will import ElementTree for parsing data of XML format to CSV format. The xml.etree.ElementTree module implements a simple and efficient API for parsing and creating XML data.
Import module
Declare rows and columns for the data to arranged in csv file
Load xml file
Parse xml file
Write each row to csv file one by one
Save csv file
XML data used :
Link: sample.xml
Program:
Python3
# Importing the required librariesimport xml.etree.ElementTree as Xetimport pandas as pd cols = ["name", "phone", "email", "date", "country"]rows = [] # Parsing the XML filexmlparse = Xet.parse('sample.xml')root = xmlparse.getroot()for i in root: name = i.find("name").text phone = i.find("phone").text email = i.find("email").text date = i.find("date").text country = i.find("country").text rows.append({"name": name, "phone": phone, "email": email, "date": date, "country": country}) df = pd.DataFrame(rows, columns=cols) # Writing dataframe to csvdf.to_csv('output.csv')
Output:
Picked
python-csv
Python-XML
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Jan, 2021"
},
{
"code": null,
"e": 50,
"s": 28,
"text": "Prerequisites: Pandas"
},
{
"code": null,
"e": 359,
"s": 50,
"text": "XML stands for Extensible Markup Language. This format is extremely useful for keeping track of small to medium amounts of data. As the data in XML format is not readable by general users, we need to convert it to some user-friendly format like CSV. CSV is easily readable and can be opened using any editor."
},
{
"code": null,
"e": 611,
"s": 359,
"text": "Now, let’s take an example to convert XML data to CSV data using python. We will import ElementTree for parsing data of XML format to CSV format. The xml.etree.ElementTree module implements a simple and efficient API for parsing and creating XML data."
},
{
"code": null,
"e": 625,
"s": 611,
"text": "Import module"
},
{
"code": null,
"e": 687,
"s": 625,
"text": "Declare rows and columns for the data to arranged in csv file"
},
{
"code": null,
"e": 701,
"s": 687,
"text": "Load xml file"
},
{
"code": null,
"e": 716,
"s": 701,
"text": "Parse xml file"
},
{
"code": null,
"e": 754,
"s": 716,
"text": "Write each row to csv file one by one"
},
{
"code": null,
"e": 768,
"s": 754,
"text": "Save csv file"
},
{
"code": null,
"e": 785,
"s": 768,
"text": "XML data used : "
},
{
"code": null,
"e": 802,
"s": 785,
"text": "Link: sample.xml"
},
{
"code": null,
"e": 811,
"s": 802,
"text": "Program:"
},
{
"code": null,
"e": 819,
"s": 811,
"text": "Python3"
},
{
"code": "# Importing the required librariesimport xml.etree.ElementTree as Xetimport pandas as pd cols = [\"name\", \"phone\", \"email\", \"date\", \"country\"]rows = [] # Parsing the XML filexmlparse = Xet.parse('sample.xml')root = xmlparse.getroot()for i in root: name = i.find(\"name\").text phone = i.find(\"phone\").text email = i.find(\"email\").text date = i.find(\"date\").text country = i.find(\"country\").text rows.append({\"name\": name, \"phone\": phone, \"email\": email, \"date\": date, \"country\": country}) df = pd.DataFrame(rows, columns=cols) # Writing dataframe to csvdf.to_csv('output.csv')",
"e": 1481,
"s": 819,
"text": null
},
{
"code": null,
"e": 1489,
"s": 1481,
"text": "Output:"
},
{
"code": null,
"e": 1496,
"s": 1489,
"text": "Picked"
},
{
"code": null,
"e": 1507,
"s": 1496,
"text": "python-csv"
},
{
"code": null,
"e": 1518,
"s": 1507,
"text": "Python-XML"
},
{
"code": null,
"e": 1542,
"s": 1518,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 1549,
"s": 1542,
"text": "Python"
},
{
"code": null,
"e": 1568,
"s": 1549,
"text": "Technical Scripter"
}
] |
Aliquot sum - GeeksforGeeks
|
08 Apr, 2021
In number theory, the aliquot sum s(n) of a positive integer n is the sum of all proper divisors of n, that is, all divisors of n other than n itself.They are defined by the sums of their aliquot divisors. The aliquot divisors of a number are all of its divisors except the number itself. The aliquot sum is the sum of the aliquot divisors so, for example, the aliquot divisors of 12 are 1, 2, 3, 4, and 6 and it’s aliquot sum is 16.A number whose aliquot sum equals its value is a PERFECT number (6 for example).Examples :
Input : 12
Output : 16
Explanation :
Proper divisors of 12 is = 1, 2, 3, 4, 6
and sum 1 + 2 + 3 + 4 + 6 = 16
Input : 15
Output : 9
Explanation :
Proper divisors of 15 is 1, 3, 5
and sum 1 + 3 + 5 = 9
A simple solution is to traverse through all numbers smaller than n. For every number i, check if i divides n. If yes, we add it to result.
C++
Java
Python3
C#
PHP
Javascript
// CPP program for aliquot sum#include <iostream>using namespace std; // Function to calculate sum of// all proper divisorsint aliquotSum(int n){ int sum = 0; for (int i = 1; i < n; i++) if (n % i == 0) sum += i; return sum;} // Driver Codeint main(){ int n = 12; cout << aliquotSum(n); return 0;}
// Java program for aliquot sumimport java.io.*; class GFG { // Function to calculate sum of // all proper divisors static int aliquotSum(int n) { int sum = 0; for (int i = 1; i < n; i++) if (n % i == 0) sum += i; return sum; } // Driver Code public static void main(String args[]) throws IOException { int n = 12; System.out.println(aliquotSum(n)); }} /* This code is contributed by Nikita Tiwari.*/
# Python 3 program for aliquot sum # Function to calculate sum of# all proper divisorsdef aliquotSum(n) : sm = 0 for i in range(1,n) : if (n % i == 0) : sm = sm + i return sm # return sum # Driver Coden = 12print(aliquotSum(n)) # This code is contributed by Nikita Tiwari.
// C# program for aliquot sumusing System; class GFG { // Function to calculate sum of // all proper divisors static int aliquotSum(int n) { int sum = 0; for (int i = 1; i < n; i++) if (n % i == 0) sum += i; return sum; } // Driver Code public static void Main() { int n = 12; Console.WriteLine(aliquotSum(n)); }} /* This code is contributed by vt_m.*/
<?php// PHP program for aliquot sum // Function to calculate sum of// all proper divisorsfunction aliquotSum($n){ $sum = 0; for ($i = 1; $i < $n; $i++) if ($n % $i == 0) $sum += $i; return $sum;} // Driver Code$n = 12;echo(aliquotSum($n)); // This code is contributed by Ajit.?>
<script> // JavaScript program for aliquot sum // Function to calculate sum of// all proper divisors function aliquotSum(n) { let sum = 0; for (let i = 1; i < n; i++) if (n % i == 0) sum += i; return sum; } // Driver code let n = 12; document.write(aliquotSum(n)); </script>
Output :
16
Efficient Solutions : Sum of all proper divisors of a natural number Sum of all the factors of a number
jit_t
souravghosh0416
divisors
number-theory
Mathematical
number-theory
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Program to print prime numbers from 1 to N.
Fizz Buzz Implementation
Program to multiply two matrices
Modular multiplicative inverse
Check if a number is Palindrome
Find first and last digits of a number
Count ways to reach the n'th stair
Program to convert a given number to words
Find Union and Intersection of two unsorted arrays
|
[
{
"code": null,
"e": 24692,
"s": 24664,
"text": "\n08 Apr, 2021"
},
{
"code": null,
"e": 25218,
"s": 24692,
"text": "In number theory, the aliquot sum s(n) of a positive integer n is the sum of all proper divisors of n, that is, all divisors of n other than n itself.They are defined by the sums of their aliquot divisors. The aliquot divisors of a number are all of its divisors except the number itself. The aliquot sum is the sum of the aliquot divisors so, for example, the aliquot divisors of 12 are 1, 2, 3, 4, and 6 and it’s aliquot sum is 16.A number whose aliquot sum equals its value is a PERFECT number (6 for example).Examples : "
},
{
"code": null,
"e": 25420,
"s": 25218,
"text": "Input : 12\nOutput : 16\nExplanation :\nProper divisors of 12 is = 1, 2, 3, 4, 6 \nand sum 1 + 2 + 3 + 4 + 6 = 16\n\nInput : 15\nOutput : 9\nExplanation :\nProper divisors of 15 is 1, 3, 5\nand sum 1 + 3 + 5 = 9"
},
{
"code": null,
"e": 25564,
"s": 25422,
"text": "A simple solution is to traverse through all numbers smaller than n. For every number i, check if i divides n. If yes, we add it to result. "
},
{
"code": null,
"e": 25568,
"s": 25564,
"text": "C++"
},
{
"code": null,
"e": 25573,
"s": 25568,
"text": "Java"
},
{
"code": null,
"e": 25581,
"s": 25573,
"text": "Python3"
},
{
"code": null,
"e": 25584,
"s": 25581,
"text": "C#"
},
{
"code": null,
"e": 25588,
"s": 25584,
"text": "PHP"
},
{
"code": null,
"e": 25599,
"s": 25588,
"text": "Javascript"
},
{
"code": "// CPP program for aliquot sum#include <iostream>using namespace std; // Function to calculate sum of// all proper divisorsint aliquotSum(int n){ int sum = 0; for (int i = 1; i < n; i++) if (n % i == 0) sum += i; return sum;} // Driver Codeint main(){ int n = 12; cout << aliquotSum(n); return 0;}",
"e": 25945,
"s": 25599,
"text": null
},
{
"code": "// Java program for aliquot sumimport java.io.*; class GFG { // Function to calculate sum of // all proper divisors static int aliquotSum(int n) { int sum = 0; for (int i = 1; i < n; i++) if (n % i == 0) sum += i; return sum; } // Driver Code public static void main(String args[]) throws IOException { int n = 12; System.out.println(aliquotSum(n)); }} /* This code is contributed by Nikita Tiwari.*/",
"e": 26487,
"s": 25945,
"text": null
},
{
"code": "# Python 3 program for aliquot sum # Function to calculate sum of# all proper divisorsdef aliquotSum(n) : sm = 0 for i in range(1,n) : if (n % i == 0) : sm = sm + i return sm # return sum # Driver Coden = 12print(aliquotSum(n)) # This code is contributed by Nikita Tiwari.",
"e": 26797,
"s": 26487,
"text": null
},
{
"code": "// C# program for aliquot sumusing System; class GFG { // Function to calculate sum of // all proper divisors static int aliquotSum(int n) { int sum = 0; for (int i = 1; i < n; i++) if (n % i == 0) sum += i; return sum; } // Driver Code public static void Main() { int n = 12; Console.WriteLine(aliquotSum(n)); }} /* This code is contributed by vt_m.*/",
"e": 27290,
"s": 26797,
"text": null
},
{
"code": "<?php// PHP program for aliquot sum // Function to calculate sum of// all proper divisorsfunction aliquotSum($n){ $sum = 0; for ($i = 1; $i < $n; $i++) if ($n % $i == 0) $sum += $i; return $sum;} // Driver Code$n = 12;echo(aliquotSum($n)); // This code is contributed by Ajit.?>",
"e": 27605,
"s": 27290,
"text": null
},
{
"code": "<script> // JavaScript program for aliquot sum // Function to calculate sum of// all proper divisors function aliquotSum(n) { let sum = 0; for (let i = 1; i < n; i++) if (n % i == 0) sum += i; return sum; } // Driver code let n = 12; document.write(aliquotSum(n)); </script>",
"e": 27993,
"s": 27605,
"text": null
},
{
"code": null,
"e": 28003,
"s": 27993,
"text": "Output : "
},
{
"code": null,
"e": 28006,
"s": 28003,
"text": "16"
},
{
"code": null,
"e": 28111,
"s": 28006,
"text": "Efficient Solutions : Sum of all proper divisors of a natural number Sum of all the factors of a number "
},
{
"code": null,
"e": 28117,
"s": 28111,
"text": "jit_t"
},
{
"code": null,
"e": 28133,
"s": 28117,
"text": "souravghosh0416"
},
{
"code": null,
"e": 28142,
"s": 28133,
"text": "divisors"
},
{
"code": null,
"e": 28156,
"s": 28142,
"text": "number-theory"
},
{
"code": null,
"e": 28169,
"s": 28156,
"text": "Mathematical"
},
{
"code": null,
"e": 28183,
"s": 28169,
"text": "number-theory"
},
{
"code": null,
"e": 28196,
"s": 28183,
"text": "Mathematical"
},
{
"code": null,
"e": 28294,
"s": 28196,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28326,
"s": 28294,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 28370,
"s": 28326,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 28395,
"s": 28370,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 28428,
"s": 28395,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 28459,
"s": 28428,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 28491,
"s": 28459,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 28530,
"s": 28491,
"text": "Find first and last digits of a number"
},
{
"code": null,
"e": 28565,
"s": 28530,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 28608,
"s": 28565,
"text": "Program to convert a given number to words"
}
] |
How to align a logo image to center of navigation bar using HTML and CSS ? - GeeksforGeeks
|
23 Nov, 2020
Problem statement: You must have seen that while applying margin:auto property to the image tag in the navigation bar, the logo image in the navigation bar does not get centered.
Approach: As the image tag in CSS is an inline element, so the image tag will occupy only that much space which is required by it. So, in order to resolve this problem, we have assigned the display property of the image tag to “block” and then assign proper width and height to it. Assign the margin to “auto”. You will see that the logo image is now centered in the navigation bar.
HTML code: Following demonstrates the code for the above approach.
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <style> #navbar { width: 100vw; height: 40px; border: 3px solid white; border-radius: 15px; background-color: green; } #navbar img { display: block; width: 40px; height: 40px; margin: auto; } </style></head> <body> <nav id="navbar"> <img src="5.jpeg" alt="Logo image"> </nav></body> </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Misc
HTML-Misc
Technical Scripter 2020
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
|
[
{
"code": null,
"e": 25011,
"s": 24983,
"text": "\n23 Nov, 2020"
},
{
"code": null,
"e": 25190,
"s": 25011,
"text": "Problem statement: You must have seen that while applying margin:auto property to the image tag in the navigation bar, the logo image in the navigation bar does not get centered."
},
{
"code": null,
"e": 25573,
"s": 25190,
"text": "Approach: As the image tag in CSS is an inline element, so the image tag will occupy only that much space which is required by it. So, in order to resolve this problem, we have assigned the display property of the image tag to “block” and then assign proper width and height to it. Assign the margin to “auto”. You will see that the logo image is now centered in the navigation bar."
},
{
"code": null,
"e": 25640,
"s": 25573,
"text": "HTML code: Following demonstrates the code for the above approach."
},
{
"code": null,
"e": 25645,
"s": 25640,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <style> #navbar { width: 100vw; height: 40px; border: 3px solid white; border-radius: 15px; background-color: green; } #navbar img { display: block; width: 40px; height: 40px; margin: auto; } </style></head> <body> <nav id=\"navbar\"> <img src=\"5.jpeg\" alt=\"Logo image\"> </nav></body> </html>",
"e": 26246,
"s": 25645,
"text": null
},
{
"code": null,
"e": 26254,
"s": 26246,
"text": "Output:"
},
{
"code": null,
"e": 26391,
"s": 26254,
"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": 26400,
"s": 26391,
"text": "CSS-Misc"
},
{
"code": null,
"e": 26410,
"s": 26400,
"text": "HTML-Misc"
},
{
"code": null,
"e": 26434,
"s": 26410,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 26438,
"s": 26434,
"text": "CSS"
},
{
"code": null,
"e": 26443,
"s": 26438,
"text": "HTML"
},
{
"code": null,
"e": 26460,
"s": 26443,
"text": "Web Technologies"
},
{
"code": null,
"e": 26487,
"s": 26460,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 26492,
"s": 26487,
"text": "HTML"
},
{
"code": null,
"e": 26590,
"s": 26492,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26599,
"s": 26590,
"text": "Comments"
},
{
"code": null,
"e": 26612,
"s": 26599,
"text": "Old Comments"
},
{
"code": null,
"e": 26649,
"s": 26612,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 26678,
"s": 26649,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 26717,
"s": 26678,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 26759,
"s": 26717,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 26794,
"s": 26759,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 26854,
"s": 26794,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 26915,
"s": 26854,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 26968,
"s": 26915,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 27018,
"s": 26968,
"text": "How to Insert Form Data into Database using PHP ?"
}
] |
SAP ABAP - Variables
|
Variables are named data objects used to store values within the allotted memory area of a program. As the name suggests, users can change the content of variables with the help of ABAP statements. Each variable in ABAP has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.
You must declare all variables before they can be used. The basic form of a variable declaration is −
DATA <f> TYPE <type> VALUE <val>.
Here <f> specifies the name of a variable. The name of the variable can be up to 30 characters long. <type> specifies the type of variable. Any data type with fully specified technical attributes is known as <type>. The <val> specifies the initial value of the of <f> variable. In case you define an elementary fixed-length variable, the DATA statement automatically populates the value of the variable with the type-specific initial value. Other possible values for <val> can be a literal, constant, or an explicit clause, such as Is INITIAL.
Following are valid examples of variable declarations.
DATA d1(2) TYPE C.
DATA d2 LIKE d1.
DATA minimum_value TYPE I VALUE 10.
In the above code snippet, d1 is a variable of C type, d2 is a variable of d1 type, and minimum_value is a variable of ABAP integer type I.
This chapter will explain various variable types available in ABAP. There are three kinds of variables in ABAP −
Static Variables
Reference Variables
System Variables
Static variables are declared in subroutines, function modules, and static methods.
Static variables are declared in subroutines, function modules, and static methods.
The lifetime is linked to the context of the declaration.
The lifetime is linked to the context of the declaration.
With ‘CLASS-DATA’ statement, you can declare variables within the classes.
With ‘CLASS-DATA’ statement, you can declare variables within the classes.
The ‘PARAMETERS’ statement can be used to declare the elementary data objects that are linked to input fields on a selection screen.
The ‘PARAMETERS’ statement can be used to declare the elementary data objects that are linked to input fields on a selection screen.
You can also declare the internal tables that are linked to input fields on a selection screen by using ‘SELECT-OPTIONS’ statement.
You can also declare the internal tables that are linked to input fields on a selection screen by using ‘SELECT-OPTIONS’ statement.
Following are the conventions used while naming a variable −
You cannot use special characters such as "t" and "," to name variables.
You cannot use special characters such as "t" and "," to name variables.
The name of the predefined data objects can’t be changed.
The name of the predefined data objects can’t be changed.
The name of the variable can’t be the same as any ABAP keyword or clause.
The name of the variable can’t be the same as any ABAP keyword or clause.
The name of the variables must convey the meaning of the variable without the need for further comments.
The name of the variables must convey the meaning of the variable without the need for further comments.
Hyphens are reserved to represent the components of structures. Therefore, you are supposed to avoid hyphens in variable names.
Hyphens are reserved to represent the components of structures. Therefore, you are supposed to avoid hyphens in variable names.
The underscore character can be used to separate compound words.
The underscore character can be used to separate compound words.
This program shows how to declare a variable using the PARAMETERS statement −
REPORT ZTest123_01.
PARAMETERS: NAME(10) TYPE C,
CLASS TYPE I,
SCORE TYPE P DECIMALS 2,
CONNECT TYPE MARA-MATNR.
Here, NAME represents a parameter of 10 characters, CLASS specifies a parameter of integer type with the default size in bytes, SCORE represents a packed type parameter with values up to two decimal places, and CONNECT refers to the MARA-MATNF type of ABAP Dictionary.
The above code produces the following output −
The syntax for declaring reference variables is −
DATA <ref> TYPE REF TO <type> VALUE IS INITIAL.
REF TO addition declares a reference variable ref.
REF TO addition declares a reference variable ref.
The specification after REF TO specifies the static type of the reference variable.
The specification after REF TO specifies the static type of the reference variable.
The static type restricts the set of objects to which <ref> can refer.
The static type restricts the set of objects to which <ref> can refer.
The dynamic type of reference variable is the data type or class to which it currently refers.
The dynamic type of reference variable is the data type or class to which it currently refers.
The static type is always more general or the same as the dynamic type.
The static type is always more general or the same as the dynamic type.
The TYPE addition is used to create a bound reference type and as a start value, and only IS INITIAL can be specified after the VALUE addition.
The TYPE addition is used to create a bound reference type and as a start value, and only IS INITIAL can be specified after the VALUE addition.
CLASS C1 DEFINITION.
PUBLIC SECTION.
DATA Bl TYPE I VALUE 1.
ENDCLASS. DATA: Oref TYPE REF TO C1 ,
Dref1 LIKE REF TO Oref,
Dref2 TYPE REF TO I .
CREATE OBJECT Oref.
GET REFERENCE OF Oref INTO Dref1.
CREATE DATA Dref2.
Dref2→* = Dref1→*→Bl.
In the above code snippet, an object reference Oref and two data reference variables Dref1 and Dref2 are declared.
In the above code snippet, an object reference Oref and two data reference variables Dref1 and Dref2 are declared.
Both data reference variables are fully typed and can be dereferenced using the dereferencing operator →* at operand positions.
Both data reference variables are fully typed and can be dereferenced using the dereferencing operator →* at operand positions.
ABAP system variables are accessible from all ABAP programs.
ABAP system variables are accessible from all ABAP programs.
These fields are actually filled by the run-time environment.
These fields are actually filled by the run-time environment.
The values in these fields indicate the state of the system at any given point of time.
The values in these fields indicate the state of the system at any given point of time.
You can find the complete list of system variables in the SYST table in SAP.
You can find the complete list of system variables in the SYST table in SAP.
Individual fields of the SYST structure can be accessed by using either “SYST-” or “SY-”.
Individual fields of the SYST structure can be accessed by using either “SYST-” or “SY-”.
REPORT Z_Test123_01.
WRITE:/'SY-ABCDE', SY-ABCDE,
/'SY-DATUM', SY-DATUM,
/'SY-DBSYS', SY-DBSYS,
/'SY-HOST ', SY-HOST,
/'SY-LANGU', SY-LANGU,
/'SY-MANDT', SY-MANDT,
/'SY-OPSYS', SY-OPSYS,
/'SY-SAPRL', SY-SAPRL,
/'SY-SYSID', SY-SYSID,
/'SY-TCODE', SY-TCODE,
/'SY-UNAME', SY-UNAME,
/'SY-UZEIT', SY-UZEIT.
The above code produces the following output −
SY-ABCDE ABCDEFGHIJKLMNOPQRSTUVWXYZ
SY-DATUM 12.09.2015
SY-DBSYS ORACLE
SY-HOST sapserver
SY-LANGU EN
SY-MANDT 800
SY-OPSYS Windows NT
SY-SAPRL 700
SY-SYSID DMO
SY-TCODE SE38
SY-UNAME SAPUSER
SY-UZEIT 14:25:48
25 Lectures
6 hours
Sanjo Thomas
26 Lectures
2 hours
Neha Gupta
30 Lectures
2.5 hours
Sumit Agarwal
30 Lectures
4 hours
Sumit Agarwal
14 Lectures
1.5 hours
Neha Malik
13 Lectures
1.5 hours
Neha Malik
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3324,
"s": 2898,
"text": "Variables are named data objects used to store values within the allotted memory area of a program. As the name suggests, users can change the content of variables with the help of ABAP statements. Each variable in ABAP has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable."
},
{
"code": null,
"e": 3426,
"s": 3324,
"text": "You must declare all variables before they can be used. The basic form of a variable declaration is −"
},
{
"code": null,
"e": 3461,
"s": 3426,
"text": "DATA <f> TYPE <type> VALUE <val>. "
},
{
"code": null,
"e": 4005,
"s": 3461,
"text": "Here <f> specifies the name of a variable. The name of the variable can be up to 30 characters long. <type> specifies the type of variable. Any data type with fully specified technical attributes is known as <type>. The <val> specifies the initial value of the of <f> variable. In case you define an elementary fixed-length variable, the DATA statement automatically populates the value of the variable with the type-specific initial value. Other possible values for <val> can be a literal, constant, or an explicit clause, such as Is INITIAL."
},
{
"code": null,
"e": 4060,
"s": 4005,
"text": "Following are valid examples of variable declarations."
},
{
"code": null,
"e": 4137,
"s": 4060,
"text": "DATA d1(2) TYPE C. \nDATA d2 LIKE d1. \nDATA minimum_value TYPE I VALUE 10. "
},
{
"code": null,
"e": 4277,
"s": 4137,
"text": "In the above code snippet, d1 is a variable of C type, d2 is a variable of d1 type, and minimum_value is a variable of ABAP integer type I."
},
{
"code": null,
"e": 4390,
"s": 4277,
"text": "This chapter will explain various variable types available in ABAP. There are three kinds of variables in ABAP −"
},
{
"code": null,
"e": 4407,
"s": 4390,
"text": "Static Variables"
},
{
"code": null,
"e": 4427,
"s": 4407,
"text": "Reference Variables"
},
{
"code": null,
"e": 4444,
"s": 4427,
"text": "System Variables"
},
{
"code": null,
"e": 4528,
"s": 4444,
"text": "Static variables are declared in subroutines, function modules, and static methods."
},
{
"code": null,
"e": 4612,
"s": 4528,
"text": "Static variables are declared in subroutines, function modules, and static methods."
},
{
"code": null,
"e": 4670,
"s": 4612,
"text": "The lifetime is linked to the context of the declaration."
},
{
"code": null,
"e": 4728,
"s": 4670,
"text": "The lifetime is linked to the context of the declaration."
},
{
"code": null,
"e": 4803,
"s": 4728,
"text": "With ‘CLASS-DATA’ statement, you can declare variables within the classes."
},
{
"code": null,
"e": 4878,
"s": 4803,
"text": "With ‘CLASS-DATA’ statement, you can declare variables within the classes."
},
{
"code": null,
"e": 5011,
"s": 4878,
"text": "The ‘PARAMETERS’ statement can be used to declare the elementary data objects that are linked to input fields on a selection screen."
},
{
"code": null,
"e": 5144,
"s": 5011,
"text": "The ‘PARAMETERS’ statement can be used to declare the elementary data objects that are linked to input fields on a selection screen."
},
{
"code": null,
"e": 5276,
"s": 5144,
"text": "You can also declare the internal tables that are linked to input fields on a selection screen by using ‘SELECT-OPTIONS’ statement."
},
{
"code": null,
"e": 5408,
"s": 5276,
"text": "You can also declare the internal tables that are linked to input fields on a selection screen by using ‘SELECT-OPTIONS’ statement."
},
{
"code": null,
"e": 5469,
"s": 5408,
"text": "Following are the conventions used while naming a variable −"
},
{
"code": null,
"e": 5542,
"s": 5469,
"text": "You cannot use special characters such as \"t\" and \",\" to name variables."
},
{
"code": null,
"e": 5615,
"s": 5542,
"text": "You cannot use special characters such as \"t\" and \",\" to name variables."
},
{
"code": null,
"e": 5673,
"s": 5615,
"text": "The name of the predefined data objects can’t be changed."
},
{
"code": null,
"e": 5731,
"s": 5673,
"text": "The name of the predefined data objects can’t be changed."
},
{
"code": null,
"e": 5805,
"s": 5731,
"text": "The name of the variable can’t be the same as any ABAP keyword or clause."
},
{
"code": null,
"e": 5879,
"s": 5805,
"text": "The name of the variable can’t be the same as any ABAP keyword or clause."
},
{
"code": null,
"e": 5984,
"s": 5879,
"text": "The name of the variables must convey the meaning of the variable without the need for further comments."
},
{
"code": null,
"e": 6089,
"s": 5984,
"text": "The name of the variables must convey the meaning of the variable without the need for further comments."
},
{
"code": null,
"e": 6217,
"s": 6089,
"text": "Hyphens are reserved to represent the components of structures. Therefore, you are supposed to avoid hyphens in variable names."
},
{
"code": null,
"e": 6345,
"s": 6217,
"text": "Hyphens are reserved to represent the components of structures. Therefore, you are supposed to avoid hyphens in variable names."
},
{
"code": null,
"e": 6410,
"s": 6345,
"text": "The underscore character can be used to separate compound words."
},
{
"code": null,
"e": 6475,
"s": 6410,
"text": "The underscore character can be used to separate compound words."
},
{
"code": null,
"e": 6553,
"s": 6475,
"text": "This program shows how to declare a variable using the PARAMETERS statement −"
},
{
"code": null,
"e": 6671,
"s": 6553,
"text": "REPORT ZTest123_01. \nPARAMETERS: NAME(10) TYPE C, \nCLASS TYPE I, \nSCORE TYPE P DECIMALS 2, \nCONNECT TYPE MARA-MATNR. "
},
{
"code": null,
"e": 6940,
"s": 6671,
"text": "Here, NAME represents a parameter of 10 characters, CLASS specifies a parameter of integer type with the default size in bytes, SCORE represents a packed type parameter with values up to two decimal places, and CONNECT refers to the MARA-MATNF type of ABAP Dictionary."
},
{
"code": null,
"e": 6987,
"s": 6940,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 7037,
"s": 6987,
"text": "The syntax for declaring reference variables is −"
},
{
"code": null,
"e": 7087,
"s": 7037,
"text": "DATA <ref> TYPE REF TO <type> VALUE IS INITIAL. \n"
},
{
"code": null,
"e": 7138,
"s": 7087,
"text": "REF TO addition declares a reference variable ref."
},
{
"code": null,
"e": 7189,
"s": 7138,
"text": "REF TO addition declares a reference variable ref."
},
{
"code": null,
"e": 7273,
"s": 7189,
"text": "The specification after REF TO specifies the static type of the reference variable."
},
{
"code": null,
"e": 7357,
"s": 7273,
"text": "The specification after REF TO specifies the static type of the reference variable."
},
{
"code": null,
"e": 7428,
"s": 7357,
"text": "The static type restricts the set of objects to which <ref> can refer."
},
{
"code": null,
"e": 7499,
"s": 7428,
"text": "The static type restricts the set of objects to which <ref> can refer."
},
{
"code": null,
"e": 7594,
"s": 7499,
"text": "The dynamic type of reference variable is the data type or class to which it currently refers."
},
{
"code": null,
"e": 7689,
"s": 7594,
"text": "The dynamic type of reference variable is the data type or class to which it currently refers."
},
{
"code": null,
"e": 7761,
"s": 7689,
"text": "The static type is always more general or the same as the dynamic type."
},
{
"code": null,
"e": 7833,
"s": 7761,
"text": "The static type is always more general or the same as the dynamic type."
},
{
"code": null,
"e": 7977,
"s": 7833,
"text": "The TYPE addition is used to create a bound reference type and as a start value, and only IS INITIAL can be specified after the VALUE addition."
},
{
"code": null,
"e": 8121,
"s": 7977,
"text": "The TYPE addition is used to create a bound reference type and as a start value, and only IS INITIAL can be specified after the VALUE addition."
},
{
"code": null,
"e": 8370,
"s": 8121,
"text": "CLASS C1 DEFINITION. \nPUBLIC SECTION. \nDATA Bl TYPE I VALUE 1. \nENDCLASS. DATA: Oref TYPE REF TO C1 , \nDref1 LIKE REF TO Oref, \nDref2 TYPE REF TO I . \nCREATE OBJECT Oref. \nGET REFERENCE OF Oref INTO Dref1. \nCREATE DATA Dref2. \nDref2→* = Dref1→*→Bl."
},
{
"code": null,
"e": 8485,
"s": 8370,
"text": "In the above code snippet, an object reference Oref and two data reference variables Dref1 and Dref2 are declared."
},
{
"code": null,
"e": 8600,
"s": 8485,
"text": "In the above code snippet, an object reference Oref and two data reference variables Dref1 and Dref2 are declared."
},
{
"code": null,
"e": 8728,
"s": 8600,
"text": "Both data reference variables are fully typed and can be dereferenced using the dereferencing operator →* at operand positions."
},
{
"code": null,
"e": 8856,
"s": 8728,
"text": "Both data reference variables are fully typed and can be dereferenced using the dereferencing operator →* at operand positions."
},
{
"code": null,
"e": 8917,
"s": 8856,
"text": "ABAP system variables are accessible from all ABAP programs."
},
{
"code": null,
"e": 8978,
"s": 8917,
"text": "ABAP system variables are accessible from all ABAP programs."
},
{
"code": null,
"e": 9040,
"s": 8978,
"text": "These fields are actually filled by the run-time environment."
},
{
"code": null,
"e": 9102,
"s": 9040,
"text": "These fields are actually filled by the run-time environment."
},
{
"code": null,
"e": 9190,
"s": 9102,
"text": "The values in these fields indicate the state of the system at any given point of time."
},
{
"code": null,
"e": 9278,
"s": 9190,
"text": "The values in these fields indicate the state of the system at any given point of time."
},
{
"code": null,
"e": 9355,
"s": 9278,
"text": "You can find the complete list of system variables in the SYST table in SAP."
},
{
"code": null,
"e": 9432,
"s": 9355,
"text": "You can find the complete list of system variables in the SYST table in SAP."
},
{
"code": null,
"e": 9522,
"s": 9432,
"text": "Individual fields of the SYST structure can be accessed by using either “SYST-” or “SY-”."
},
{
"code": null,
"e": 9612,
"s": 9522,
"text": "Individual fields of the SYST structure can be accessed by using either “SYST-” or “SY-”."
},
{
"code": null,
"e": 9992,
"s": 9612,
"text": "REPORT Z_Test123_01. \n\nWRITE:/'SY-ABCDE', SY-ABCDE, \n /'SY-DATUM', SY-DATUM, \n /'SY-DBSYS', SY-DBSYS, \n /'SY-HOST ', SY-HOST, \n /'SY-LANGU', SY-LANGU,\n /'SY-MANDT', SY-MANDT,\n /'SY-OPSYS', SY-OPSYS,\n /'SY-SAPRL', SY-SAPRL,\n /'SY-SYSID', SY-SYSID,\n /'SY-TCODE', SY-TCODE,\n /'SY-UNAME', SY-UNAME,\n /'SY-UZEIT', SY-UZEIT."
},
{
"code": null,
"e": 10039,
"s": 9992,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 10280,
"s": 10039,
"text": "SY-ABCDE ABCDEFGHIJKLMNOPQRSTUVWXYZ \nSY-DATUM 12.09.2015 \nSY-DBSYS ORACLE \nSY-HOST sapserver \nSY-LANGU EN \nSY-MANDT 800 \nSY-OPSYS Windows NT \nSY-SAPRL 700 \nSY-SYSID DMO \nSY-TCODE SE38 \nSY-UNAME SAPUSER \nSY-UZEIT 14:25:48\n"
},
{
"code": null,
"e": 10313,
"s": 10280,
"text": "\n 25 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 10327,
"s": 10313,
"text": " Sanjo Thomas"
},
{
"code": null,
"e": 10360,
"s": 10327,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 10372,
"s": 10360,
"text": " Neha Gupta"
},
{
"code": null,
"e": 10407,
"s": 10372,
"text": "\n 30 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 10422,
"s": 10407,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 10455,
"s": 10422,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 10470,
"s": 10455,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 10505,
"s": 10470,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 10517,
"s": 10505,
"text": " Neha Malik"
},
{
"code": null,
"e": 10552,
"s": 10517,
"text": "\n 13 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 10564,
"s": 10552,
"text": " Neha Malik"
},
{
"code": null,
"e": 10571,
"s": 10564,
"text": " Print"
},
{
"code": null,
"e": 10582,
"s": 10571,
"text": " Add Notes"
}
] |
Spring - Bean Post Processors
|
The BeanPostProcessor interface defines callback methods that you can implement to provide your own instantiation logic, dependency-resolution logic, etc. You can also implement some custom logic after the Spring container finishes instantiating, configuring, and initializing a bean by plugging in one or more BeanPostProcessor implementations.
You can configure multiple BeanPostProcessor interfaces and you can control the order in which these BeanPostProcessor interfaces execute by setting the order property provided the BeanPostProcessor implements the Ordered interface.
The BeanPostProcessors operate on bean (or object) instances, which means that the Spring IoC container instantiates a bean instance and then BeanPostProcessor interfaces do their work.
An ApplicationContext automatically detects any beans that are defined with the implementation of the BeanPostProcessor interface and registers these beans as postprocessors, to be then called appropriately by the container upon bean creation.
The following examples show how to write, register, and use BeanPostProcessors in the context of an ApplicationContext.
Let us have a working Eclipse IDE in place and take the following steps to create a Spring application −
Here is the content of HelloWorld.java file −
package com.tutorialspoint;
public class HelloWorld {
private String message;
public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
public void init(){
System.out.println("Bean is going through init.");
}
public void destroy(){
System.out.println("Bean will destroy now.");
}
}
This is a very basic example of implementing BeanPostProcessor, which prints a bean name before and after initialization of any bean. You can implement more complex logic before and after intializing a bean because you have access on bean object inside both the post processor methods.
Here is the content of InitHelloWorld.java file −
package com.tutorialspoint;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.BeansException;
public class InitHelloWorld implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("BeforeInitialization : " + beanName);
return bean; // you can return any other object as well
}
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("AfterInitialization : " + beanName);
return bean; // you can return any other object as well
}
}
Following is the content of the MainApp.java file. Here you need to register a shutdown hook registerShutdownHook() method that is declared on the AbstractApplicationContext class. This will ensures a graceful shutdown and calls the relevant destroy methods.
package com.tutorialspoint;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
obj.getMessage();
context.registerShutdownHook();
}
}
Following is the configuration file Beans.xml required for init and destroy methods −
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld"
init-method = "init" destroy-method = "destroy">
<property name = "message" value = "Hello World!"/>
</bean>
<bean class = "com.tutorialspoint.InitHelloWorld" />
</beans>
Once you are done with creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −
BeforeInitialization : helloWorld
Bean is going through init.
AfterInitialization : helloWorld
Your Message : Hello World!
Bean will destroy now.
102 Lectures
8 hours
Karthikeya T
39 Lectures
5 hours
Chaand Sheikh
73 Lectures
5.5 hours
Senol Atac
62 Lectures
4.5 hours
Senol Atac
67 Lectures
4.5 hours
Senol Atac
69 Lectures
5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2638,
"s": 2292,
"text": "The BeanPostProcessor interface defines callback methods that you can implement to provide your own instantiation logic, dependency-resolution logic, etc. You can also implement some custom logic after the Spring container finishes instantiating, configuring, and initializing a bean by plugging in one or more BeanPostProcessor implementations."
},
{
"code": null,
"e": 2871,
"s": 2638,
"text": "You can configure multiple BeanPostProcessor interfaces and you can control the order in which these BeanPostProcessor interfaces execute by setting the order property provided the BeanPostProcessor implements the Ordered interface."
},
{
"code": null,
"e": 3057,
"s": 2871,
"text": "The BeanPostProcessors operate on bean (or object) instances, which means that the Spring IoC container instantiates a bean instance and then BeanPostProcessor interfaces do their work."
},
{
"code": null,
"e": 3301,
"s": 3057,
"text": "An ApplicationContext automatically detects any beans that are defined with the implementation of the BeanPostProcessor interface and registers these beans as postprocessors, to be then called appropriately by the container upon bean creation."
},
{
"code": null,
"e": 3421,
"s": 3301,
"text": "The following examples show how to write, register, and use BeanPostProcessors in the context of an ApplicationContext."
},
{
"code": null,
"e": 3526,
"s": 3421,
"text": "Let us have a working Eclipse IDE in place and take the following steps to create a Spring application −"
},
{
"code": null,
"e": 3572,
"s": 3526,
"text": "Here is the content of HelloWorld.java file −"
},
{
"code": null,
"e": 3993,
"s": 3572,
"text": "package com.tutorialspoint;\n\npublic class HelloWorld {\n private String message;\n\n public void setMessage(String message){\n this.message = message;\n }\n public void getMessage(){\n System.out.println(\"Your Message : \" + message);\n }\n public void init(){\n System.out.println(\"Bean is going through init.\");\n }\n public void destroy(){\n System.out.println(\"Bean will destroy now.\");\n }\n}"
},
{
"code": null,
"e": 4279,
"s": 3993,
"text": "This is a very basic example of implementing BeanPostProcessor, which prints a bean name before and after initialization of any bean. You can implement more complex logic before and after intializing a bean because you have access on bean object inside both the post processor methods."
},
{
"code": null,
"e": 4329,
"s": 4279,
"text": "Here is the content of InitHelloWorld.java file −"
},
{
"code": null,
"e": 5032,
"s": 4329,
"text": "package com.tutorialspoint;\n\nimport org.springframework.beans.factory.config.BeanPostProcessor;\nimport org.springframework.beans.BeansException;\n\npublic class InitHelloWorld implements BeanPostProcessor {\n public Object postProcessBeforeInitialization(Object bean, String beanName) \n throws BeansException {\n \n System.out.println(\"BeforeInitialization : \" + beanName);\n return bean; // you can return any other object as well\n }\n public Object postProcessAfterInitialization(Object bean, String beanName) \n throws BeansException {\n \n System.out.println(\"AfterInitialization : \" + beanName);\n return bean; // you can return any other object as well\n }\n}"
},
{
"code": null,
"e": 5291,
"s": 5032,
"text": "Following is the content of the MainApp.java file. Here you need to register a shutdown hook registerShutdownHook() method that is declared on the AbstractApplicationContext class. This will ensures a graceful shutdown and calls the relevant destroy methods."
},
{
"code": null,
"e": 5763,
"s": 5291,
"text": "package com.tutorialspoint;\n\nimport org.springframework.context.support.AbstractApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\n\npublic class MainApp {\n public static void main(String[] args) {\n AbstractApplicationContext context = new ClassPathXmlApplicationContext(\"Beans.xml\");\n\n HelloWorld obj = (HelloWorld) context.getBean(\"helloWorld\");\n obj.getMessage();\n context.registerShutdownHook();\n }\n}"
},
{
"code": null,
"e": 5849,
"s": 5763,
"text": "Following is the configuration file Beans.xml required for init and destroy methods −"
},
{
"code": null,
"e": 6411,
"s": 5849,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\">\n\n <bean id = \"helloWorld\" class = \"com.tutorialspoint.HelloWorld\"\n init-method = \"init\" destroy-method = \"destroy\">\n <property name = \"message\" value = \"Hello World!\"/>\n </bean>\n\n <bean class = \"com.tutorialspoint.InitHelloWorld\" />\n\n</beans>"
},
{
"code": null,
"e": 6595,
"s": 6411,
"text": "Once you are done with creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −"
},
{
"code": null,
"e": 6742,
"s": 6595,
"text": "BeforeInitialization : helloWorld\nBean is going through init.\nAfterInitialization : helloWorld\nYour Message : Hello World!\nBean will destroy now.\n"
},
{
"code": null,
"e": 6776,
"s": 6742,
"text": "\n 102 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 6790,
"s": 6776,
"text": " Karthikeya T"
},
{
"code": null,
"e": 6823,
"s": 6790,
"text": "\n 39 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6838,
"s": 6823,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 6873,
"s": 6838,
"text": "\n 73 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6885,
"s": 6873,
"text": " Senol Atac"
},
{
"code": null,
"e": 6920,
"s": 6885,
"text": "\n 62 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6932,
"s": 6920,
"text": " Senol Atac"
},
{
"code": null,
"e": 6967,
"s": 6932,
"text": "\n 67 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6979,
"s": 6967,
"text": " Senol Atac"
},
{
"code": null,
"e": 7012,
"s": 6979,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 7024,
"s": 7012,
"text": " Senol Atac"
},
{
"code": null,
"e": 7031,
"s": 7024,
"text": " Print"
},
{
"code": null,
"e": 7042,
"s": 7031,
"text": " Add Notes"
}
] |
Performance metrics for binary classifier (in simple words) | by Irene P | Towards Data Science
|
Say we have a simple binary classifier which accepts boxes with Schrodinger’s cats 😺 as the input and we expect the classifier to return label 1 (positive) if the cat is alive and 0 (negative) if not, but errors occur from time to time.
The reasons may be different, for example — poor quality of input data, or wrong features selected. E.g. if it’s a deep sleeping cat so it looks quite dead, the classifier can easily return 0 for it.
The figure below shows 4 possible cases, in two of them the classifier gives correct predictions, in the other two — it’s wrong:
Thus, if our null hypothesis is that ALL cats are alive (belongs to class 1), then the possible errors are:
null hypothesis was wrongly rejected
dead cat was classified as alive
null hypothesis was wrongly accepted
alive cat was classified as dead
Let’s complete the pic above with numbers: how many samples were labeled correctly, and how many times the classifier was wrong. That’s how we get the confusion matrix for binary classification.
Here is an example of a matrix constructed using the Python scikit-learn:
from sklearn.metrics import confusion_matriximport pandas as pdn = confusion_matrix(test_labels, predictions)plot_confusion_matrix(n, classes = ['Dead cat', 'Alive cat'], title = 'Confusion Matrix');
In this case we have:
true negatives = 616 (dead cats labeled as dead)
false negatives = 59 (alive cats labeled as dead)
true positives = 71 (alive cats labeled as alive)
false positives = 89 (dead cats labeled as alive)
All that values we can get using ravel() from numpy:
tn, fp, fn, tp = confusion_matrix(test_labels, predictions).ravel()
So, now we know how many times the model did right and wrong predictions, and the next step is to evaluate the classifier — to check if the predictions made by it were good enough. Let’s see what metrics do we have for that.
First we’ll try to use Accuracy Score for evaluation: to divide number of correct predictions by total number of predictions and get the percentage of samples were predicted correctly:
When the data is imbalanced and there are significantly more alive cats than dead (or vice versa). Let’s figure out why.
We want to find all the alive cats asap before they join the other 95, but our classifier had lost all hope and became pessimistic: now it always says the cat in the box is dead (even if it’s not).
Then it will be right 95 times (TN = 95), and wrong 5 times (FN = 5). The other values are: TP = FP = 0. Let’s calculate the classifier’s accuracy:
Looks like the classifier has great accuracy — 95%, but it do absolutely nothing.
The reason is the large number of “guessed” dead cats makes a big contribution to the accuracy score and suppress errors.
So it turns out that in order to get a high accuracy, classifier can always give a label of the predominant class. But it doesn’t fit with the problem’s solution logic: high accuracy didn’t help us to find a single box with alive cat.
Looks like we need to move from calculating the common metric for all classes to separate performance metrics for each class.
To calculate True Positive Rate (aka Recall, Sensitivity, and Hit Rate) we compare the number of correct predictions that the cat is alive with the total number of boxes with alive cats:
True Negative Rate (aka Specificity or Selectivity): here we compare the number of boxes with dead cats and the number of correct predictions that the cat is dead:
Let’s calculate both measures for our pessimistic classifier and imbalanced data (95 alive and 5 dead cats):
Well, this time the model failed to trick us: although TNR is perfect (1), but TPR is 0.
This clearly illustrates the essence of this model: it’s pretty good at finding dead cats, but terrible at finding alive ones.
All this is taken into account in balanced accuracy metric, which is an analog of accuracy, but can be used for imbalanced classes.
It is calculated as the average of sensitivity and specificity, i.e. the average of the proportion corrects of each class individually:
When all classes are balanced, so there are the same number of samples in each class, TP + FN ≈ TN + FP and binary classifier’s “regular” Accuracy is approximately equal to Balanced Accuracy.
In our case with imbalanced cats (95 dead and 5 alive):
Here we got 50% in contrast to the Accuracy score which was 95%. And, until our model guesses at least one alive cat, it won’t get a BA score higher than 50% — that’s life (and the balanced accuracy formula).
Looks like that’s all done — we can just always use balanced accuracy as it’s immune to class imbalance. But here’s another example.
Let’s say now our classifier said that there are 10 alive cats among the boxes, but... none of them were actually alive.
That is what we have then:
none of 5 alive cats were found (TP = 0), all of them were labeled as dead (FN = 5)
of the 95 dead cats, 85 were correctly classified (TN = 85) and 10 were mistaken for alive (FP = 10)
And balanced accuracy decreased from 0.5 to 0.45:
On the one hand, this makes sense, since now there are more errors (the model identified dead cats unmistakably before). On the other hand, as we’re trying to find alive cats, both models are equally useless: neither of them found a single alive cat, but metrics says that the first one is better. So what should we trust?
The point is, balanced accuracy metric gives only half its weight to how many alive cats we classified correctly. The other half is given to how many dead cats we labeled correctly, while for our task this information is useless.
An important role here is played by the task we use the classifier for. In example described above, it’s in our best interest to detect a greatest number of cats alive, but whether the model can identify dead cats doesn’t matter much (anyway, it’s too late to try to rescue them). But if one day it becomes as important to find dead cats as alive ones, we can safely use the Balanced Accuracy.
But for now, we are still focused on detecting alive cats and continue to look for a metric that can help us evaluate our model.
Let’s assume that we retrained our model and it finally predicted 5 alive cats out of 5! But we still have a few mistakes — 5 dead cats were labeled as alive too.
In other words: FP = 5, TP = 5, TN = 90, FN = 0.
Then what is model’s Recall (True Positive Rate)?
1 or 100% — awesome!
But what about those cats called alive but were dead? We all know that the classifier was wrong as many times as it was right. And, obviously, there should be a metric that reflects it.
There is such a metric — Precision:
It shows the ability of our model to differ the “alive cat” class from all the others, but, unfortunately, it does not give an idea of whether we have found all the alive cats or not.
In contrast, Recall metric shows whether we found all the alive cats, but it can’t say anything about how many times we had to open boxes with dead cats throughout these searches.
Well, let’s calculate Precision for our last experiment and then interpret the results:
So:
Recall = 1 means that no matter how many alive cats are there in total, we’ll find them all.
Precision = 0.5 means that opening a box with label “alive”, in half of the cases we’ll find a dead cat there.
(I’ll remind we still have 95 dead ☠️ and 5 alive 😸 cats)
Separately, Precision and Recall make little sense:
a model that always classifies all cats as alive (optimistic) has a perfect Recall (100%), but very low Precision (5%).
a model that deems alive only those cats about which it’s absolutely sure (pessimistic), has 100% Precision. But if there are a lot of cats sleeping like a dog, Recall will be very low.
We need to balance both metrics to get a full picture and answers to both questions:1. how many “alive” predictions were correct (Precision)2. what part of alive cats was classified correctly (Recall)
And that’s where F1 metric comes in handy.
F1 is the harmonic mean of Precision and Recall, so you can’t get a high F1 if either one is very low.
Let’s recall how our model was training and calculate F1 score for all of 3 cases:
At first, the model labeled all cats as dead:TP = FP = 0, TN = 95, FN = 5Then it labeled 10 cats as alive, but there was not a single alive cat among them:TP = 0, FP = 10, FN = 5, TN = 85Finally, the classifier predicted correctly 5 out of 5 alive cats, but also mistakenly labeled 5 dead cats as alive:TP = 5, FP = 5, FN = 0, TN = 90
At first, the model labeled all cats as dead:TP = FP = 0, TN = 95, FN = 5
Then it labeled 10 cats as alive, but there was not a single alive cat among them:TP = 0, FP = 10, FN = 5, TN = 85
Finally, the classifier predicted correctly 5 out of 5 alive cats, but also mistakenly labeled 5 dead cats as alive:TP = 5, FP = 5, FN = 0, TN = 90
You can see that with each retraining the “quality” of negative predictions decreases and positive — rises, so we expect F1 to reflect this changes:
Well, that makes sense. Cases 1 and 2 are essentially the same for us — despite the different behaviour of the model, we didn’t find any alive cats. But the third time the classifier labeled all the alive cats correctly — and F1 increased, along with our hope of saving the cats found 😸.
The thing is, unlike Balanced Accuracy, the F1 doesn’t take into account True Negatives — it’s easy to see if we expand the formula:
This means it doesn’t matter how many dead cats there were in dataset in total nor how many of them we successfully found. We focus on detecting the alive ones only as they are more important.
Let’s compare that with the Balanced Accuracy behaviour:
So if we care more about saving alive cats (detecting positives), metric F1 fits better.
F1 only cares about the samples the model said are positive, and about the samples that actually are positive and doesn’t care at all about how many negative samples we have in dataset or how many were classified correctly.
That’s why this metric is quite popular when evaluating models aimed at finding anomalies.
And on the contrary, we should prefer Balanced Accuracy more if negative samples are almost as important as positives.
For multiclass classification, if one class contains much more samples than the others, its metrics will suppress all the others. Then you can form its own contingency matrix and calculate its own F1 value for each class, and the resulting F1 shall be simple (i.e. not weighted) arithmetic mean for all classes.
the fraction of correct predictions
depends on the balance between classes, is not applicable to imbalanced datasets
for balanced datasets, is equal to Balanced Accuracy
the average of Sensitivity and Specificity
immune to class imbalance, can be applied to imbalanced datasets
for balanced datasets, is equal to Accuracy
the fraction of true positive predictions from all positive predictions
shows if the classifier is able to differ one class from all others
immune to class imbalance, can be applied to imbalanced datasets
should be balanced with Recall
the fraction of true positive predictions from all positive samples in dataset
shows if the classifier is able to detect a giving class at all
immune to class imbalance, can be applied to imbalanced datasets
should be balanced with Precision
harmonic mean of Precision and Recall
doesn’t take into account True Negatives
immune to class imbalance, can be applied to imbalanced datasets
All the metrics mentioned above can be found in scikit-learn library:
from sklearn.metrics import accuracy_scorefrom sklearn.metrics import balanced_accuracy_scorefrom sklearn.metrics import recall_scorefrom sklearn.metrics import precision_scorefrom sklearn.metrics import f1_score
I skipped a number of metrics here, which are also ok to be used if you have imbalanced dataset, like Precision–Recall curve, or Kappa score, or AUC ROС, which is immune to class imbalance too... Or it is not?
Let’s figure it out in the next part :)
* All images by Author
|
[
{
"code": null,
"e": 284,
"s": 47,
"text": "Say we have a simple binary classifier which accepts boxes with Schrodinger’s cats 😺 as the input and we expect the classifier to return label 1 (positive) if the cat is alive and 0 (negative) if not, but errors occur from time to time."
},
{
"code": null,
"e": 484,
"s": 284,
"text": "The reasons may be different, for example — poor quality of input data, or wrong features selected. E.g. if it’s a deep sleeping cat so it looks quite dead, the classifier can easily return 0 for it."
},
{
"code": null,
"e": 613,
"s": 484,
"text": "The figure below shows 4 possible cases, in two of them the classifier gives correct predictions, in the other two — it’s wrong:"
},
{
"code": null,
"e": 721,
"s": 613,
"text": "Thus, if our null hypothesis is that ALL cats are alive (belongs to class 1), then the possible errors are:"
},
{
"code": null,
"e": 758,
"s": 721,
"text": "null hypothesis was wrongly rejected"
},
{
"code": null,
"e": 791,
"s": 758,
"text": "dead cat was classified as alive"
},
{
"code": null,
"e": 828,
"s": 791,
"text": "null hypothesis was wrongly accepted"
},
{
"code": null,
"e": 861,
"s": 828,
"text": "alive cat was classified as dead"
},
{
"code": null,
"e": 1056,
"s": 861,
"text": "Let’s complete the pic above with numbers: how many samples were labeled correctly, and how many times the classifier was wrong. That’s how we get the confusion matrix for binary classification."
},
{
"code": null,
"e": 1130,
"s": 1056,
"text": "Here is an example of a matrix constructed using the Python scikit-learn:"
},
{
"code": null,
"e": 1341,
"s": 1130,
"text": "from sklearn.metrics import confusion_matriximport pandas as pdn = confusion_matrix(test_labels, predictions)plot_confusion_matrix(n, classes = ['Dead cat', 'Alive cat'], \t\t\t\t\t\t\t\t\t\t\ttitle = 'Confusion Matrix');"
},
{
"code": null,
"e": 1363,
"s": 1341,
"text": "In this case we have:"
},
{
"code": null,
"e": 1412,
"s": 1363,
"text": "true negatives = 616 (dead cats labeled as dead)"
},
{
"code": null,
"e": 1462,
"s": 1412,
"text": "false negatives = 59 (alive cats labeled as dead)"
},
{
"code": null,
"e": 1512,
"s": 1462,
"text": "true positives = 71 (alive cats labeled as alive)"
},
{
"code": null,
"e": 1562,
"s": 1512,
"text": "false positives = 89 (dead cats labeled as alive)"
},
{
"code": null,
"e": 1615,
"s": 1562,
"text": "All that values we can get using ravel() from numpy:"
},
{
"code": null,
"e": 1683,
"s": 1615,
"text": "tn, fp, fn, tp = confusion_matrix(test_labels, predictions).ravel()"
},
{
"code": null,
"e": 1908,
"s": 1683,
"text": "So, now we know how many times the model did right and wrong predictions, and the next step is to evaluate the classifier — to check if the predictions made by it were good enough. Let’s see what metrics do we have for that."
},
{
"code": null,
"e": 2093,
"s": 1908,
"text": "First we’ll try to use Accuracy Score for evaluation: to divide number of correct predictions by total number of predictions and get the percentage of samples were predicted correctly:"
},
{
"code": null,
"e": 2214,
"s": 2093,
"text": "When the data is imbalanced and there are significantly more alive cats than dead (or vice versa). Let’s figure out why."
},
{
"code": null,
"e": 2412,
"s": 2214,
"text": "We want to find all the alive cats asap before they join the other 95, but our classifier had lost all hope and became pessimistic: now it always says the cat in the box is dead (even if it’s not)."
},
{
"code": null,
"e": 2560,
"s": 2412,
"text": "Then it will be right 95 times (TN = 95), and wrong 5 times (FN = 5). The other values are: TP = FP = 0. Let’s calculate the classifier’s accuracy:"
},
{
"code": null,
"e": 2642,
"s": 2560,
"text": "Looks like the classifier has great accuracy — 95%, but it do absolutely nothing."
},
{
"code": null,
"e": 2764,
"s": 2642,
"text": "The reason is the large number of “guessed” dead cats makes a big contribution to the accuracy score and suppress errors."
},
{
"code": null,
"e": 2999,
"s": 2764,
"text": "So it turns out that in order to get a high accuracy, classifier can always give a label of the predominant class. But it doesn’t fit with the problem’s solution logic: high accuracy didn’t help us to find a single box with alive cat."
},
{
"code": null,
"e": 3125,
"s": 2999,
"text": "Looks like we need to move from calculating the common metric for all classes to separate performance metrics for each class."
},
{
"code": null,
"e": 3312,
"s": 3125,
"text": "To calculate True Positive Rate (aka Recall, Sensitivity, and Hit Rate) we compare the number of correct predictions that the cat is alive with the total number of boxes with alive cats:"
},
{
"code": null,
"e": 3476,
"s": 3312,
"text": "True Negative Rate (aka Specificity or Selectivity): here we compare the number of boxes with dead cats and the number of correct predictions that the cat is dead:"
},
{
"code": null,
"e": 3585,
"s": 3476,
"text": "Let’s calculate both measures for our pessimistic classifier and imbalanced data (95 alive and 5 dead cats):"
},
{
"code": null,
"e": 3674,
"s": 3585,
"text": "Well, this time the model failed to trick us: although TNR is perfect (1), but TPR is 0."
},
{
"code": null,
"e": 3801,
"s": 3674,
"text": "This clearly illustrates the essence of this model: it’s pretty good at finding dead cats, but terrible at finding alive ones."
},
{
"code": null,
"e": 3933,
"s": 3801,
"text": "All this is taken into account in balanced accuracy metric, which is an analog of accuracy, but can be used for imbalanced classes."
},
{
"code": null,
"e": 4069,
"s": 3933,
"text": "It is calculated as the average of sensitivity and specificity, i.e. the average of the proportion corrects of each class individually:"
},
{
"code": null,
"e": 4261,
"s": 4069,
"text": "When all classes are balanced, so there are the same number of samples in each class, TP + FN ≈ TN + FP and binary classifier’s “regular” Accuracy is approximately equal to Balanced Accuracy."
},
{
"code": null,
"e": 4317,
"s": 4261,
"text": "In our case with imbalanced cats (95 dead and 5 alive):"
},
{
"code": null,
"e": 4526,
"s": 4317,
"text": "Here we got 50% in contrast to the Accuracy score which was 95%. And, until our model guesses at least one alive cat, it won’t get a BA score higher than 50% — that’s life (and the balanced accuracy formula)."
},
{
"code": null,
"e": 4659,
"s": 4526,
"text": "Looks like that’s all done — we can just always use balanced accuracy as it’s immune to class imbalance. But here’s another example."
},
{
"code": null,
"e": 4780,
"s": 4659,
"text": "Let’s say now our classifier said that there are 10 alive cats among the boxes, but... none of them were actually alive."
},
{
"code": null,
"e": 4807,
"s": 4780,
"text": "That is what we have then:"
},
{
"code": null,
"e": 4891,
"s": 4807,
"text": "none of 5 alive cats were found (TP = 0), all of them were labeled as dead (FN = 5)"
},
{
"code": null,
"e": 4992,
"s": 4891,
"text": "of the 95 dead cats, 85 were correctly classified (TN = 85) and 10 were mistaken for alive (FP = 10)"
},
{
"code": null,
"e": 5042,
"s": 4992,
"text": "And balanced accuracy decreased from 0.5 to 0.45:"
},
{
"code": null,
"e": 5365,
"s": 5042,
"text": "On the one hand, this makes sense, since now there are more errors (the model identified dead cats unmistakably before). On the other hand, as we’re trying to find alive cats, both models are equally useless: neither of them found a single alive cat, but metrics says that the first one is better. So what should we trust?"
},
{
"code": null,
"e": 5595,
"s": 5365,
"text": "The point is, balanced accuracy metric gives only half its weight to how many alive cats we classified correctly. The other half is given to how many dead cats we labeled correctly, while for our task this information is useless."
},
{
"code": null,
"e": 5989,
"s": 5595,
"text": "An important role here is played by the task we use the classifier for. In example described above, it’s in our best interest to detect a greatest number of cats alive, but whether the model can identify dead cats doesn’t matter much (anyway, it’s too late to try to rescue them). But if one day it becomes as important to find dead cats as alive ones, we can safely use the Balanced Accuracy."
},
{
"code": null,
"e": 6118,
"s": 5989,
"text": "But for now, we are still focused on detecting alive cats and continue to look for a metric that can help us evaluate our model."
},
{
"code": null,
"e": 6281,
"s": 6118,
"text": "Let’s assume that we retrained our model and it finally predicted 5 alive cats out of 5! But we still have a few mistakes — 5 dead cats were labeled as alive too."
},
{
"code": null,
"e": 6330,
"s": 6281,
"text": "In other words: FP = 5, TP = 5, TN = 90, FN = 0."
},
{
"code": null,
"e": 6380,
"s": 6330,
"text": "Then what is model’s Recall (True Positive Rate)?"
},
{
"code": null,
"e": 6401,
"s": 6380,
"text": "1 or 100% — awesome!"
},
{
"code": null,
"e": 6587,
"s": 6401,
"text": "But what about those cats called alive but were dead? We all know that the classifier was wrong as many times as it was right. And, obviously, there should be a metric that reflects it."
},
{
"code": null,
"e": 6623,
"s": 6587,
"text": "There is such a metric — Precision:"
},
{
"code": null,
"e": 6807,
"s": 6623,
"text": "It shows the ability of our model to differ the “alive cat” class from all the others, but, unfortunately, it does not give an idea of whether we have found all the alive cats or not."
},
{
"code": null,
"e": 6987,
"s": 6807,
"text": "In contrast, Recall metric shows whether we found all the alive cats, but it can’t say anything about how many times we had to open boxes with dead cats throughout these searches."
},
{
"code": null,
"e": 7075,
"s": 6987,
"text": "Well, let’s calculate Precision for our last experiment and then interpret the results:"
},
{
"code": null,
"e": 7079,
"s": 7075,
"text": "So:"
},
{
"code": null,
"e": 7172,
"s": 7079,
"text": "Recall = 1 means that no matter how many alive cats are there in total, we’ll find them all."
},
{
"code": null,
"e": 7283,
"s": 7172,
"text": "Precision = 0.5 means that opening a box with label “alive”, in half of the cases we’ll find a dead cat there."
},
{
"code": null,
"e": 7341,
"s": 7283,
"text": "(I’ll remind we still have 95 dead ☠️ and 5 alive 😸 cats)"
},
{
"code": null,
"e": 7393,
"s": 7341,
"text": "Separately, Precision and Recall make little sense:"
},
{
"code": null,
"e": 7513,
"s": 7393,
"text": "a model that always classifies all cats as alive (optimistic) has a perfect Recall (100%), but very low Precision (5%)."
},
{
"code": null,
"e": 7699,
"s": 7513,
"text": "a model that deems alive only those cats about which it’s absolutely sure (pessimistic), has 100% Precision. But if there are a lot of cats sleeping like a dog, Recall will be very low."
},
{
"code": null,
"e": 7900,
"s": 7699,
"text": "We need to balance both metrics to get a full picture and answers to both questions:1. how many “alive” predictions were correct (Precision)2. what part of alive cats was classified correctly (Recall)"
},
{
"code": null,
"e": 7943,
"s": 7900,
"text": "And that’s where F1 metric comes in handy."
},
{
"code": null,
"e": 8046,
"s": 7943,
"text": "F1 is the harmonic mean of Precision and Recall, so you can’t get a high F1 if either one is very low."
},
{
"code": null,
"e": 8129,
"s": 8046,
"text": "Let’s recall how our model was training and calculate F1 score for all of 3 cases:"
},
{
"code": null,
"e": 8464,
"s": 8129,
"text": "At first, the model labeled all cats as dead:TP = FP = 0, TN = 95, FN = 5Then it labeled 10 cats as alive, but there was not a single alive cat among them:TP = 0, FP = 10, FN = 5, TN = 85Finally, the classifier predicted correctly 5 out of 5 alive cats, but also mistakenly labeled 5 dead cats as alive:TP = 5, FP = 5, FN = 0, TN = 90"
},
{
"code": null,
"e": 8538,
"s": 8464,
"text": "At first, the model labeled all cats as dead:TP = FP = 0, TN = 95, FN = 5"
},
{
"code": null,
"e": 8653,
"s": 8538,
"text": "Then it labeled 10 cats as alive, but there was not a single alive cat among them:TP = 0, FP = 10, FN = 5, TN = 85"
},
{
"code": null,
"e": 8801,
"s": 8653,
"text": "Finally, the classifier predicted correctly 5 out of 5 alive cats, but also mistakenly labeled 5 dead cats as alive:TP = 5, FP = 5, FN = 0, TN = 90"
},
{
"code": null,
"e": 8950,
"s": 8801,
"text": "You can see that with each retraining the “quality” of negative predictions decreases and positive — rises, so we expect F1 to reflect this changes:"
},
{
"code": null,
"e": 9238,
"s": 8950,
"text": "Well, that makes sense. Cases 1 and 2 are essentially the same for us — despite the different behaviour of the model, we didn’t find any alive cats. But the third time the classifier labeled all the alive cats correctly — and F1 increased, along with our hope of saving the cats found 😸."
},
{
"code": null,
"e": 9371,
"s": 9238,
"text": "The thing is, unlike Balanced Accuracy, the F1 doesn’t take into account True Negatives — it’s easy to see if we expand the formula:"
},
{
"code": null,
"e": 9564,
"s": 9371,
"text": "This means it doesn’t matter how many dead cats there were in dataset in total nor how many of them we successfully found. We focus on detecting the alive ones only as they are more important."
},
{
"code": null,
"e": 9621,
"s": 9564,
"text": "Let’s compare that with the Balanced Accuracy behaviour:"
},
{
"code": null,
"e": 9710,
"s": 9621,
"text": "So if we care more about saving alive cats (detecting positives), metric F1 fits better."
},
{
"code": null,
"e": 9934,
"s": 9710,
"text": "F1 only cares about the samples the model said are positive, and about the samples that actually are positive and doesn’t care at all about how many negative samples we have in dataset or how many were classified correctly."
},
{
"code": null,
"e": 10025,
"s": 9934,
"text": "That’s why this metric is quite popular when evaluating models aimed at finding anomalies."
},
{
"code": null,
"e": 10144,
"s": 10025,
"text": "And on the contrary, we should prefer Balanced Accuracy more if negative samples are almost as important as positives."
},
{
"code": null,
"e": 10456,
"s": 10144,
"text": "For multiclass classification, if one class contains much more samples than the others, its metrics will suppress all the others. Then you can form its own contingency matrix and calculate its own F1 value for each class, and the resulting F1 shall be simple (i.e. not weighted) arithmetic mean for all classes."
},
{
"code": null,
"e": 10492,
"s": 10456,
"text": "the fraction of correct predictions"
},
{
"code": null,
"e": 10573,
"s": 10492,
"text": "depends on the balance between classes, is not applicable to imbalanced datasets"
},
{
"code": null,
"e": 10626,
"s": 10573,
"text": "for balanced datasets, is equal to Balanced Accuracy"
},
{
"code": null,
"e": 10669,
"s": 10626,
"text": "the average of Sensitivity and Specificity"
},
{
"code": null,
"e": 10734,
"s": 10669,
"text": "immune to class imbalance, can be applied to imbalanced datasets"
},
{
"code": null,
"e": 10778,
"s": 10734,
"text": "for balanced datasets, is equal to Accuracy"
},
{
"code": null,
"e": 10850,
"s": 10778,
"text": "the fraction of true positive predictions from all positive predictions"
},
{
"code": null,
"e": 10918,
"s": 10850,
"text": "shows if the classifier is able to differ one class from all others"
},
{
"code": null,
"e": 10983,
"s": 10918,
"text": "immune to class imbalance, can be applied to imbalanced datasets"
},
{
"code": null,
"e": 11014,
"s": 10983,
"text": "should be balanced with Recall"
},
{
"code": null,
"e": 11093,
"s": 11014,
"text": "the fraction of true positive predictions from all positive samples in dataset"
},
{
"code": null,
"e": 11157,
"s": 11093,
"text": "shows if the classifier is able to detect a giving class at all"
},
{
"code": null,
"e": 11222,
"s": 11157,
"text": "immune to class imbalance, can be applied to imbalanced datasets"
},
{
"code": null,
"e": 11256,
"s": 11222,
"text": "should be balanced with Precision"
},
{
"code": null,
"e": 11294,
"s": 11256,
"text": "harmonic mean of Precision and Recall"
},
{
"code": null,
"e": 11335,
"s": 11294,
"text": "doesn’t take into account True Negatives"
},
{
"code": null,
"e": 11400,
"s": 11335,
"text": "immune to class imbalance, can be applied to imbalanced datasets"
},
{
"code": null,
"e": 11470,
"s": 11400,
"text": "All the metrics mentioned above can be found in scikit-learn library:"
},
{
"code": null,
"e": 11683,
"s": 11470,
"text": "from sklearn.metrics import accuracy_scorefrom sklearn.metrics import balanced_accuracy_scorefrom sklearn.metrics import recall_scorefrom sklearn.metrics import precision_scorefrom sklearn.metrics import f1_score"
},
{
"code": null,
"e": 11893,
"s": 11683,
"text": "I skipped a number of metrics here, which are also ok to be used if you have imbalanced dataset, like Precision–Recall curve, or Kappa score, or AUC ROС, which is immune to class imbalance too... Or it is not?"
},
{
"code": null,
"e": 11933,
"s": 11893,
"text": "Let’s figure it out in the next part :)"
}
] |
The Nice Way To Deploy An ML Model Using Docker | by Yash Prakash | Towards Data Science
|
There are challenges associated with ML projects when built and run by different developers in a team or otherwise. Sometime, the dependencies may end up mismatching, causing troubles for other dependent libraries in the same project. Besides, you also need to have a clear documentation of every step to take in case you’re providing a project that has to be executed in a specific way.
All of this can be made easier and quicker by using Docker. With containerization, you can save you a lot of time, and help smooth out the process of deployment of your app in the long run.
If you’re looking for a guide with a complete set of steps to manually build and run a docker image for your project, you can find it right here, in this article:
pub.towardsai.net
However, in this tutorial, I will going over a simpler process to ease out the Docker development, one that can be done entirely with the help of VSCode itself.
Let’s go over each step in building a model, then an API and finally, dockerizing it.👇
We will be using Spacy for building a simple sentiment classifier which outputs two results for any piece of text passed through to it:
Polarity — it is a float which lies in the range of [-1,1] where 1 means a wholly positive statement and -1 means a wholly negative statement.
Subjectivity — ‘subjective’ sentences generally refer to personal opinion, emotion or judgment whereas ‘objective’ refers to factual information. It is a float which lies in the range of [0,1].
Now, let’s install some packages to start with our development:
pipenv shell # make a new virtual environmentpipenv install pydantic fastapi uvicorn spacy spacytextblob # the packages to install
Now, cd into the project and make a new file called “model.py”.
Let’s fill in the code for this file:
import spacyfrom spacytextblob.spacytextblob import SpacyTextBlobfrom pydantic import BaseModelclass SentimentQueryModel(BaseModel): text : strclass SentimentModel: def get_sentiment(self, text): nlp = spacy.load('en_core_web_sm') nlp.add_pipe("spacytextblob") doc = nlp(text) polarity = doc._.polarity subjectivity = doc._.subjectivity return polarity, subjectivity
We are using SentimentQueryModel to contain our only query for this model — the text that we will be predicting the sentiment for, and SentimentModel as the class that loads the spacy tokeniser and the spacytextblob library and performs the sentiment prediction for our given text.
We will now move on to the next step in which build our API.
FastAPI is a newer, better way to deploy your machine learning model as a REST API for use in your web apps.
Let’s use our “model.py” in a new file called “main.py” and build a REST API with it:
import uvicornfrom fastapi import FastAPIfrom model import SentimentModel, SentimentQueryModelapp = FastAPI()model = SentimentModel()@app.post('/predict') def predict(data: SentimentQueryModel): data = data.dict() polarity, subjectivity = model.get_sentiment(data['text']) return { 'polarity': polarity, 'subjectivity': subjectivity }if __name__ == '__main__': uvicorn.run(app, host='0.0.0.0', port=8000)
This API will now run on localhost port 8000, which we will verify by running in the terminal:
python main.py
and you’ll see the output:
If you navigate to localhost:8000/docs, you’ll be able to view and test the API in the browser itself! Isn’t that neat?
But now that we have our model and our API, we can finally move on to making a Docker container out of it!
Make sure you have the Docker by Microsoft extension installed in your VSCode. Next, go ahead and start up Docker Desktop on your machine.
Now, go into VSCode and type: Command + Shift + P to bring up the command palette. Type “Add Docker files” and you’ll get the option to add a Dockerfile to your project. This process significantly simplifies our entire workflow.
Follow through the instructions and keep the port number as 8080. Don’t forget that port 8000 is used for our API itself so we need a different one for Docker to run on!
Now, simply right click the Dockerfile in the sidebar and select “Build Image”.
You will begin to see the output in the terminal as the image is being built.
Next, you can go ahead and switch to the Docker tab on your VSCode sidebar.
Here, you’ll see a list of images you already have in your system. The new image we built just now will also show up here like this:
Now you only need to right click the ‘latest’ under the image name and select the Run option.
You can view the startup logs by right clicking the built container and clicking on ‘View logs’ option.
Now, when you navigate to localhost:8000/docs, you’ll see the following screen:
You can simply click on “Execute” which will then produce an output such as:
So, there you have it — a full pipeline of making an API out of an ML model and containerizing it with Docker!
As you can probably grasp by now, VSCode makes it extremely easy for anyone with minimal knowledge of Docker to quickly spin up their project within a container. I hope this beginner tutorial was helpful in getting you familiar with deploying ML model with Docker.
In the future, I’ll be coming back and doing some more complicated models and containerizing them with Docker. So follow me and stay in the loop!
ipom.medium.com
Follow me on Twitter.Subscribe to my Data Science publication. Check out the full code repository of all of my Data Science articles!
A couple other articles of mine you might be interested in:
|
[
{
"code": null,
"e": 560,
"s": 172,
"text": "There are challenges associated with ML projects when built and run by different developers in a team or otherwise. Sometime, the dependencies may end up mismatching, causing troubles for other dependent libraries in the same project. Besides, you also need to have a clear documentation of every step to take in case you’re providing a project that has to be executed in a specific way."
},
{
"code": null,
"e": 750,
"s": 560,
"text": "All of this can be made easier and quicker by using Docker. With containerization, you can save you a lot of time, and help smooth out the process of deployment of your app in the long run."
},
{
"code": null,
"e": 913,
"s": 750,
"text": "If you’re looking for a guide with a complete set of steps to manually build and run a docker image for your project, you can find it right here, in this article:"
},
{
"code": null,
"e": 931,
"s": 913,
"text": "pub.towardsai.net"
},
{
"code": null,
"e": 1092,
"s": 931,
"text": "However, in this tutorial, I will going over a simpler process to ease out the Docker development, one that can be done entirely with the help of VSCode itself."
},
{
"code": null,
"e": 1179,
"s": 1092,
"text": "Let’s go over each step in building a model, then an API and finally, dockerizing it.👇"
},
{
"code": null,
"e": 1315,
"s": 1179,
"text": "We will be using Spacy for building a simple sentiment classifier which outputs two results for any piece of text passed through to it:"
},
{
"code": null,
"e": 1458,
"s": 1315,
"text": "Polarity — it is a float which lies in the range of [-1,1] where 1 means a wholly positive statement and -1 means a wholly negative statement."
},
{
"code": null,
"e": 1652,
"s": 1458,
"text": "Subjectivity — ‘subjective’ sentences generally refer to personal opinion, emotion or judgment whereas ‘objective’ refers to factual information. It is a float which lies in the range of [0,1]."
},
{
"code": null,
"e": 1716,
"s": 1652,
"text": "Now, let’s install some packages to start with our development:"
},
{
"code": null,
"e": 1847,
"s": 1716,
"text": "pipenv shell # make a new virtual environmentpipenv install pydantic fastapi uvicorn spacy spacytextblob # the packages to install"
},
{
"code": null,
"e": 1911,
"s": 1847,
"text": "Now, cd into the project and make a new file called “model.py”."
},
{
"code": null,
"e": 1949,
"s": 1911,
"text": "Let’s fill in the code for this file:"
},
{
"code": null,
"e": 2365,
"s": 1949,
"text": "import spacyfrom spacytextblob.spacytextblob import SpacyTextBlobfrom pydantic import BaseModelclass SentimentQueryModel(BaseModel): text : strclass SentimentModel: def get_sentiment(self, text): nlp = spacy.load('en_core_web_sm') nlp.add_pipe(\"spacytextblob\") doc = nlp(text) polarity = doc._.polarity subjectivity = doc._.subjectivity return polarity, subjectivity"
},
{
"code": null,
"e": 2647,
"s": 2365,
"text": "We are using SentimentQueryModel to contain our only query for this model — the text that we will be predicting the sentiment for, and SentimentModel as the class that loads the spacy tokeniser and the spacytextblob library and performs the sentiment prediction for our given text."
},
{
"code": null,
"e": 2708,
"s": 2647,
"text": "We will now move on to the next step in which build our API."
},
{
"code": null,
"e": 2817,
"s": 2708,
"text": "FastAPI is a newer, better way to deploy your machine learning model as a REST API for use in your web apps."
},
{
"code": null,
"e": 2903,
"s": 2817,
"text": "Let’s use our “model.py” in a new file called “main.py” and build a REST API with it:"
},
{
"code": null,
"e": 3359,
"s": 2903,
"text": "import uvicornfrom fastapi import FastAPIfrom model import SentimentModel, SentimentQueryModelapp = FastAPI()model = SentimentModel()@app.post('/predict') def predict(data: SentimentQueryModel): data = data.dict() polarity, subjectivity = model.get_sentiment(data['text']) return { 'polarity': polarity, 'subjectivity': subjectivity }if __name__ == '__main__': uvicorn.run(app, host='0.0.0.0', port=8000)"
},
{
"code": null,
"e": 3454,
"s": 3359,
"text": "This API will now run on localhost port 8000, which we will verify by running in the terminal:"
},
{
"code": null,
"e": 3469,
"s": 3454,
"text": "python main.py"
},
{
"code": null,
"e": 3496,
"s": 3469,
"text": "and you’ll see the output:"
},
{
"code": null,
"e": 3616,
"s": 3496,
"text": "If you navigate to localhost:8000/docs, you’ll be able to view and test the API in the browser itself! Isn’t that neat?"
},
{
"code": null,
"e": 3723,
"s": 3616,
"text": "But now that we have our model and our API, we can finally move on to making a Docker container out of it!"
},
{
"code": null,
"e": 3862,
"s": 3723,
"text": "Make sure you have the Docker by Microsoft extension installed in your VSCode. Next, go ahead and start up Docker Desktop on your machine."
},
{
"code": null,
"e": 4091,
"s": 3862,
"text": "Now, go into VSCode and type: Command + Shift + P to bring up the command palette. Type “Add Docker files” and you’ll get the option to add a Dockerfile to your project. This process significantly simplifies our entire workflow."
},
{
"code": null,
"e": 4261,
"s": 4091,
"text": "Follow through the instructions and keep the port number as 8080. Don’t forget that port 8000 is used for our API itself so we need a different one for Docker to run on!"
},
{
"code": null,
"e": 4341,
"s": 4261,
"text": "Now, simply right click the Dockerfile in the sidebar and select “Build Image”."
},
{
"code": null,
"e": 4419,
"s": 4341,
"text": "You will begin to see the output in the terminal as the image is being built."
},
{
"code": null,
"e": 4495,
"s": 4419,
"text": "Next, you can go ahead and switch to the Docker tab on your VSCode sidebar."
},
{
"code": null,
"e": 4628,
"s": 4495,
"text": "Here, you’ll see a list of images you already have in your system. The new image we built just now will also show up here like this:"
},
{
"code": null,
"e": 4722,
"s": 4628,
"text": "Now you only need to right click the ‘latest’ under the image name and select the Run option."
},
{
"code": null,
"e": 4826,
"s": 4722,
"text": "You can view the startup logs by right clicking the built container and clicking on ‘View logs’ option."
},
{
"code": null,
"e": 4906,
"s": 4826,
"text": "Now, when you navigate to localhost:8000/docs, you’ll see the following screen:"
},
{
"code": null,
"e": 4983,
"s": 4906,
"text": "You can simply click on “Execute” which will then produce an output such as:"
},
{
"code": null,
"e": 5094,
"s": 4983,
"text": "So, there you have it — a full pipeline of making an API out of an ML model and containerizing it with Docker!"
},
{
"code": null,
"e": 5359,
"s": 5094,
"text": "As you can probably grasp by now, VSCode makes it extremely easy for anyone with minimal knowledge of Docker to quickly spin up their project within a container. I hope this beginner tutorial was helpful in getting you familiar with deploying ML model with Docker."
},
{
"code": null,
"e": 5505,
"s": 5359,
"text": "In the future, I’ll be coming back and doing some more complicated models and containerizing them with Docker. So follow me and stay in the loop!"
},
{
"code": null,
"e": 5521,
"s": 5505,
"text": "ipom.medium.com"
},
{
"code": null,
"e": 5655,
"s": 5521,
"text": "Follow me on Twitter.Subscribe to my Data Science publication. Check out the full code repository of all of my Data Science articles!"
}
] |
How to create a label using JavaFX?
|
You can display a text element/image on the User Interface using the Label
component. It is a not editable text control, mostly used to specify the purpose of
other nodes in the application.
In JavaFX, you can create a label by instantiating the javafx.scene.control.Label class.
Just like a text node you can set the desired font to the text node in JavaFX using the setFont() method and, you can add color to it using the setFill() method.
To create a label −
Instantiate the Label class.
Instantiate the Label class.
Set the required properties to it.
Set the required properties to it.
Add the label to the scene.
Add the label to the scene.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
public class LabelExample extends Application {
public void start(Stage stage) {
//Creating a Label
Label label = new Label("Sample label");
//Setting font to the label
Font font = Font.font("Brush Script MT", FontWeight.BOLD, FontPosture.REGULAR, 25);
label.setFont(font);
//Filling color to the label
label.setTextFill(Color.BROWN);
//Setting the position
label.setTranslateX(150);
label.setTranslateY(25);
Group root = new Group();
root.getChildren().add(label);
//Setting the stage
Scene scene = new Scene(root, 595, 150, Color.BEIGE);
stage.setTitle("Label Example");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
|
[
{
"code": null,
"e": 1253,
"s": 1062,
"text": "You can display a text element/image on the User Interface using the Label\ncomponent. It is a not editable text control, mostly used to specify the purpose of\nother nodes in the application."
},
{
"code": null,
"e": 1342,
"s": 1253,
"text": "In JavaFX, you can create a label by instantiating the javafx.scene.control.Label class."
},
{
"code": null,
"e": 1504,
"s": 1342,
"text": "Just like a text node you can set the desired font to the text node in JavaFX using the setFont() method and, you can add color to it using the setFill() method."
},
{
"code": null,
"e": 1524,
"s": 1504,
"text": "To create a label −"
},
{
"code": null,
"e": 1553,
"s": 1524,
"text": "Instantiate the Label class."
},
{
"code": null,
"e": 1582,
"s": 1553,
"text": "Instantiate the Label class."
},
{
"code": null,
"e": 1617,
"s": 1582,
"text": "Set the required properties to it."
},
{
"code": null,
"e": 1652,
"s": 1617,
"text": "Set the required properties to it."
},
{
"code": null,
"e": 1680,
"s": 1652,
"text": "Add the label to the scene."
},
{
"code": null,
"e": 1708,
"s": 1680,
"text": "Add the label to the scene."
},
{
"code": null,
"e": 2792,
"s": 1708,
"text": "import javafx.application.Application;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.control.Label;\nimport javafx.scene.paint.Color;\nimport javafx.scene.text.Font;\nimport javafx.scene.text.FontPosture;\nimport javafx.scene.text.FontWeight;\nimport javafx.stage.Stage;\npublic class LabelExample extends Application {\n public void start(Stage stage) {\n //Creating a Label\n Label label = new Label(\"Sample label\");\n //Setting font to the label\n Font font = Font.font(\"Brush Script MT\", FontWeight.BOLD, FontPosture.REGULAR, 25);\n label.setFont(font);\n //Filling color to the label\n label.setTextFill(Color.BROWN);\n //Setting the position\n label.setTranslateX(150);\n label.setTranslateY(25);\n Group root = new Group();\n root.getChildren().add(label);\n //Setting the stage\n Scene scene = new Scene(root, 595, 150, Color.BEIGE);\n stage.setTitle(\"Label Example\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}"
}
] |
Find modular node in a linked list - GeeksforGeeks
|
18 Aug, 2021
Given a singly linked list and a number k, find the last node whose n%k == 0, where n is the number of nodes in the list.Examples:
Input : list = 1->2->3->4->5->6->7
k = 3
Output : 6
Input : list = 3->7->1->9->8
k = 2
Output : 9
1. Take a pointer modularNode and initialize it with NULL. Traverse the linked list. 2. For every i%k=0, update modularNode.
C++
Java
Python3
C#
Javascript
// C++ program to find modular node in a linked list#include <bits/stdc++.h> /* Linked list node */struct Node { int data; Node* next;}; /* Function to create a new node with given data */Node* newNode(int data){ Node* new_node = new Node; new_node->data = data; new_node->next = NULL; return new_node;} /* Function to find modular node in the linked list */Node* modularNode(Node* head, int k){ // Corner cases if (k <= 0 || head == NULL) return NULL; // Traverse the given list int i = 1; Node* modularNode = NULL; for (Node* temp = head; temp != NULL; temp = temp->next) { if (i % k == 0) modularNode = temp; i++; } return modularNode;} /* Driver program to test above function */int main(void){ Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); int k = 2; Node* answer = modularNode(head, k); printf("\nModular node is "); if (answer != NULL) printf("%d\n", answer->data); else printf("null\n"); return 0;}
// A Java program to find modular node in a linked listpublic class GFG{ // A Linkedlist node static class Node{ int data; Node next; Node(int data){ this.data = data; } } // Function to find modular node in the linked list static Node modularNode(Node head, int k) { // Corner cases if (k <= 0 || head == null) return null; // Traverse the given list int i = 1; Node modularNode = null; for (Node temp = head; temp != null; temp = temp.next) { if (i % k == 0) modularNode = temp; i++; } return modularNode; } // Driver code to test above function public static void main(String[] args) { Node head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = new Node(5); int k = 2; Node answer = modularNode(head, k); System.out.print("Modular node is "); if (answer != null) System.out.println(answer.data); else System.out.println("null"); }}// This code is contributed by Sumit Ghosh
# Python3 program to find modular node# in a linked listimport math # Linked list nodeclass Node: def __init__(self, data): self.data = data self.next = None # Function to create a new node# with given datadef newNode(data): new_node = Node(data) new_node.data = data new_node.next = None return new_node # Function to find modular node# in the linked listdef modularNode(head, k): # Corner cases if (k <= 0 or head == None): return None # Traverse the given list i = 1 modularNode = None temp = head while (temp != None): if (i % k == 0): modularNode = temp i = i + 1 temp = temp.next return modularNode # Driver Codeif __name__ == '__main__': head = newNode(1) head.next = newNode(2) head.next.next = newNode(3) head.next.next.next = newNode(4) head.next.next.next.next = newNode(5) k = 2 answer = modularNode(head, k) print("Modular node is", end = ' ') if (answer != None): print(answer.data, end = ' ') else: print("None") # This code is contributed by Srathore
// C# program to find modular node in a linked listusing System; class GFG{ // A Linkedlist node public class Node { public int data; public Node next; public Node(int data) { this.data = data; } } // Function to find modular node in the linked list static Node modularNode(Node head, int k) { // Corner cases if (k <= 0 || head == null) return null; // Traverse the given list int i = 1; Node modularNode = null; for (Node temp = head; temp != null; temp = temp.next) { if (i % k == 0) modularNode = temp; i++; } return modularNode; } // Driver code public static void Main(String[] args) { Node head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = new Node(5); int k = 2; Node answer = modularNode(head, k); Console.Write("Modular node is "); if (answer != null) Console.WriteLine(answer.data); else Console.WriteLine("null"); }} // This code is contributed by Rajput-JI
<script> // A JavaScript program to find// modular node in a linked list // A Linkedlist node class Node { constructor(val) { this.data = val; this.next = null; } } // Function to find modular node in the linked list function modularNode(head , k) { // Corner cases if (k <= 0 || head == null) return null; // Traverse the given list var i = 1; var modularNode = null; for (temp = head; temp != null; temp = temp.next) { if (i % k == 0) modularNode = temp; i++; } return modularNode; } // Driver code to test above function var head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = new Node(5); var k = 2; var answer = modularNode(head, k); document.write("Modular node is "); if (answer != null) document.write(answer.data); else document.write("null"); // This code contributed by Rajput-Ji </script>
Output:
Modular node is 4
YouTubeGeeksforGeeks501K subscribersFind modular node in a linked list | 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 / 5:30•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=LNryat2UNXo" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
?list=PLqM7alHXFySH41ZxzrPNj2pAYPOI8ITe7
This article is contributed by Prakriti Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Rajput-Ji
sapnasingh4991
surinderdawra388
Modular Arithmetic
Linked List
Linked List
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Linked List | Set 1 (Introduction)
Linked List | Set 2 (Inserting a node)
Stack Data Structure (Introduction and Program)
Linked List | Set 3 (Deleting a node)
LinkedList in Java
Linked List vs Array
Delete a Linked List node at a given position
Implementing a Linked List in Java using Class
Detect loop in a linked list
Find the middle of a given linked list
|
[
{
"code": null,
"e": 31010,
"s": 30982,
"text": "\n18 Aug, 2021"
},
{
"code": null,
"e": 31143,
"s": 31010,
"text": "Given a singly linked list and a number k, find the last node whose n%k == 0, where n is the number of nodes in the list.Examples: "
},
{
"code": null,
"e": 31258,
"s": 31143,
"text": "Input : list = 1->2->3->4->5->6->7\n k = 3\nOutput : 6\n\nInput : list = 3->7->1->9->8\n k = 2\nOutput : 9"
},
{
"code": null,
"e": 31386,
"s": 31260,
"text": "1. Take a pointer modularNode and initialize it with NULL. Traverse the linked list. 2. For every i%k=0, update modularNode. "
},
{
"code": null,
"e": 31390,
"s": 31386,
"text": "C++"
},
{
"code": null,
"e": 31395,
"s": 31390,
"text": "Java"
},
{
"code": null,
"e": 31403,
"s": 31395,
"text": "Python3"
},
{
"code": null,
"e": 31406,
"s": 31403,
"text": "C#"
},
{
"code": null,
"e": 31417,
"s": 31406,
"text": "Javascript"
},
{
"code": "// C++ program to find modular node in a linked list#include <bits/stdc++.h> /* Linked list node */struct Node { int data; Node* next;}; /* Function to create a new node with given data */Node* newNode(int data){ Node* new_node = new Node; new_node->data = data; new_node->next = NULL; return new_node;} /* Function to find modular node in the linked list */Node* modularNode(Node* head, int k){ // Corner cases if (k <= 0 || head == NULL) return NULL; // Traverse the given list int i = 1; Node* modularNode = NULL; for (Node* temp = head; temp != NULL; temp = temp->next) { if (i % k == 0) modularNode = temp; i++; } return modularNode;} /* Driver program to test above function */int main(void){ Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); int k = 2; Node* answer = modularNode(head, k); printf(\"\\nModular node is \"); if (answer != NULL) printf(\"%d\\n\", answer->data); else printf(\"null\\n\"); return 0;}",
"e": 32572,
"s": 31417,
"text": null
},
{
"code": "// A Java program to find modular node in a linked listpublic class GFG{ // A Linkedlist node static class Node{ int data; Node next; Node(int data){ this.data = data; } } // Function to find modular node in the linked list static Node modularNode(Node head, int k) { // Corner cases if (k <= 0 || head == null) return null; // Traverse the given list int i = 1; Node modularNode = null; for (Node temp = head; temp != null; temp = temp.next) { if (i % k == 0) modularNode = temp; i++; } return modularNode; } // Driver code to test above function public static void main(String[] args) { Node head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = new Node(5); int k = 2; Node answer = modularNode(head, k); System.out.print(\"Modular node is \"); if (answer != null) System.out.println(answer.data); else System.out.println(\"null\"); }}// This code is contributed by Sumit Ghosh",
"e": 33832,
"s": 32572,
"text": null
},
{
"code": "# Python3 program to find modular node# in a linked listimport math # Linked list nodeclass Node: def __init__(self, data): self.data = data self.next = None # Function to create a new node# with given datadef newNode(data): new_node = Node(data) new_node.data = data new_node.next = None return new_node # Function to find modular node# in the linked listdef modularNode(head, k): # Corner cases if (k <= 0 or head == None): return None # Traverse the given list i = 1 modularNode = None temp = head while (temp != None): if (i % k == 0): modularNode = temp i = i + 1 temp = temp.next return modularNode # Driver Codeif __name__ == '__main__': head = newNode(1) head.next = newNode(2) head.next.next = newNode(3) head.next.next.next = newNode(4) head.next.next.next.next = newNode(5) k = 2 answer = modularNode(head, k) print(\"Modular node is\", end = ' ') if (answer != None): print(answer.data, end = ' ') else: print(\"None\") # This code is contributed by Srathore",
"e": 34942,
"s": 33832,
"text": null
},
{
"code": "// C# program to find modular node in a linked listusing System; class GFG{ // A Linkedlist node public class Node { public int data; public Node next; public Node(int data) { this.data = data; } } // Function to find modular node in the linked list static Node modularNode(Node head, int k) { // Corner cases if (k <= 0 || head == null) return null; // Traverse the given list int i = 1; Node modularNode = null; for (Node temp = head; temp != null; temp = temp.next) { if (i % k == 0) modularNode = temp; i++; } return modularNode; } // Driver code public static void Main(String[] args) { Node head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = new Node(5); int k = 2; Node answer = modularNode(head, k); Console.Write(\"Modular node is \"); if (answer != null) Console.WriteLine(answer.data); else Console.WriteLine(\"null\"); }} // This code is contributed by Rajput-JI",
"e": 36215,
"s": 34942,
"text": null
},
{
"code": "<script> // A JavaScript program to find// modular node in a linked list // A Linkedlist node class Node { constructor(val) { this.data = val; this.next = null; } } // Function to find modular node in the linked list function modularNode(head , k) { // Corner cases if (k <= 0 || head == null) return null; // Traverse the given list var i = 1; var modularNode = null; for (temp = head; temp != null; temp = temp.next) { if (i % k == 0) modularNode = temp; i++; } return modularNode; } // Driver code to test above function var head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = new Node(5); var k = 2; var answer = modularNode(head, k); document.write(\"Modular node is \"); if (answer != null) document.write(answer.data); else document.write(\"null\"); // This code contributed by Rajput-Ji </script>",
"e": 37365,
"s": 36215,
"text": null
},
{
"code": null,
"e": 37375,
"s": 37365,
"text": "Output: "
},
{
"code": null,
"e": 37393,
"s": 37375,
"text": "Modular node is 4"
},
{
"code": null,
"e": 38226,
"s": 37393,
"text": "YouTubeGeeksforGeeks501K subscribersFind modular node in a linked list | 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 / 5:30•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=LNryat2UNXo\" 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": 38268,
"s": 38226,
"text": "?list=PLqM7alHXFySH41ZxzrPNj2pAYPOI8ITe7 "
},
{
"code": null,
"e": 38689,
"s": 38268,
"text": "This article is contributed by Prakriti Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 38699,
"s": 38689,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 38714,
"s": 38699,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 38731,
"s": 38714,
"text": "surinderdawra388"
},
{
"code": null,
"e": 38750,
"s": 38731,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 38762,
"s": 38750,
"text": "Linked List"
},
{
"code": null,
"e": 38774,
"s": 38762,
"text": "Linked List"
},
{
"code": null,
"e": 38793,
"s": 38774,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 38891,
"s": 38793,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38900,
"s": 38891,
"text": "Comments"
},
{
"code": null,
"e": 38913,
"s": 38900,
"text": "Old Comments"
},
{
"code": null,
"e": 38948,
"s": 38913,
"text": "Linked List | Set 1 (Introduction)"
},
{
"code": null,
"e": 38987,
"s": 38948,
"text": "Linked List | Set 2 (Inserting a node)"
},
{
"code": null,
"e": 39035,
"s": 38987,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 39073,
"s": 39035,
"text": "Linked List | Set 3 (Deleting a node)"
},
{
"code": null,
"e": 39092,
"s": 39073,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 39113,
"s": 39092,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 39159,
"s": 39113,
"text": "Delete a Linked List node at a given position"
},
{
"code": null,
"e": 39206,
"s": 39159,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 39235,
"s": 39206,
"text": "Detect loop in a linked list"
}
] |
Set the base time zone offset to GMT in Java
|
In order to set the base time zone to GMT in Java, we use the setRawOffset(int offsetMillis) method. The java.util.TimeZone.setRawOffset(int offsetMillis) method set the base timezone offset to GMT.
Declaration − The java.util.TimeZone.setRawOffset(int offsetMillis) method is declared as follows −
public abstract void setRawOffset(int offsetMillis)
where offsetMillis is the given base time zone offset to GMT.
Let us set the base timezone offset to GMT in Java −
Live Demo
import java.util.*;
public class Example {
public static void main( String args[] ) {
// creating default object of TimeZone
TimeZone obj = TimeZone.getDefault();
System.out.println("Default timezone object: \n" + obj);
// setting the raw offset
obj.setRawOffset(25000);
System.out.println("The value of the offset is :" + obj.getRawOffset());
}
}
Default timezone object: sun.util.calendar.ZoneInfo[id="Etc/UTC",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]
The value of the offset is :25000
|
[
{
"code": null,
"e": 1261,
"s": 1062,
"text": "In order to set the base time zone to GMT in Java, we use the setRawOffset(int offsetMillis) method. The java.util.TimeZone.setRawOffset(int offsetMillis) method set the base timezone offset to GMT."
},
{
"code": null,
"e": 1361,
"s": 1261,
"text": "Declaration − The java.util.TimeZone.setRawOffset(int offsetMillis) method is declared as follows −"
},
{
"code": null,
"e": 1413,
"s": 1361,
"text": "public abstract void setRawOffset(int offsetMillis)"
},
{
"code": null,
"e": 1475,
"s": 1413,
"text": "where offsetMillis is the given base time zone offset to GMT."
},
{
"code": null,
"e": 1528,
"s": 1475,
"text": "Let us set the base timezone offset to GMT in Java −"
},
{
"code": null,
"e": 1539,
"s": 1528,
"text": " Live Demo"
},
{
"code": null,
"e": 1929,
"s": 1539,
"text": "import java.util.*;\npublic class Example {\n public static void main( String args[] ) {\n // creating default object of TimeZone\n TimeZone obj = TimeZone.getDefault();\n System.out.println(\"Default timezone object: \\n\" + obj);\n // setting the raw offset\n obj.setRawOffset(25000);\n System.out.println(\"The value of the offset is :\" + obj.getRawOffset());\n }\n}"
},
{
"code": null,
"e": 2097,
"s": 1929,
"text": "Default timezone object: sun.util.calendar.ZoneInfo[id=\"Etc/UTC\",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]\nThe value of the offset is :25000"
}
] |
Unit Testing in Python using Unittest
|
In this article, we will learn about the fundamentals of software testing with the help of the unit test module available in Python 3.x. Or earlier. It allows automation, sharing of the setup and exit code for tests, and independent tests for every framework.
In the unit tests, we use a wide variety of object-oriented concepts. We will be discussing some majorly used concepts here.
Testcase − It is response specific base class in accordance with a given set of inputs. We use base class of unit test i.e. “TestCase” to implement this operation.
Testcase − It is response specific base class in accordance with a given set of inputs. We use base class of unit test i.e. “TestCase” to implement this operation.
Testsuite − It is used to club test cases together and execute them simultaneously.
Testsuite − It is used to club test cases together and execute them simultaneously.
Testrunner − It follows an outcome-based execution of tasks. It is involved in displaying the results after executing the tasks.
Testrunner − It follows an outcome-based execution of tasks. It is involved in displaying the results after executing the tasks.
Test fixture − It serves as a baseline for the test cases in the associated environment.
Test fixture − It serves as a baseline for the test cases in the associated environment.
Now lets a basic example to see how unit testing works.
Live Demo
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('TUTOR'.lower(), 'tutor')
def test_islower(self):
self.assertTrue('tutor'.islower())
self.assertFalse('Tutor'.islower())
if __name__ == '__main__':
unittest.main()
...
---------------------------------------------------------------
Ran 2 tests in 0.000s
OK
Here we extend the unit test class in the form of single inheritance. Here we used to built-in methods like assertEqual() , assertTrue() & assertFalse()
assertEqual() is used to validate/compare the output with the result
assertTrue() is used to verify that the given condition is True or not.
assertFalse() is used to verify that the given condition is False or not.
The output of the above code can be in three forms −
OK – This indicates that all tests generated have executed successfully
FAIL – This indicates either test case has failed and an AssertionError exception is raised.
ERROR – This indicates that the test raises an exception/error.
We can use the decorator @unittest.skip(<reason>)
Live Demo
import unittest
class TestString(unittest.TestCase):
@unittest.skip("check skipped tests")
def test_upper(self):
self.assertEqual('TUTOR'.lower(), 'tutor')
def test_islower(self):
self.assertTrue('tutor'.islower())
self.assertFalse('Tutor'.islower())
if __name__ == '__main__':
unittest.main()
...
---------------------------------------------------------------
-
Ran 2 tests in 0.000s
OK (skipped=2)
In this article, we learned about Unit Testing in Python using the unittest module in Python 3.x. Or earlier.
|
[
{
"code": null,
"e": 1322,
"s": 1062,
"text": "In this article, we will learn about the fundamentals of software testing with the help of the unit test module available in Python 3.x. Or earlier. It allows automation, sharing of the setup and exit code for tests, and independent tests for every framework."
},
{
"code": null,
"e": 1447,
"s": 1322,
"text": "In the unit tests, we use a wide variety of object-oriented concepts. We will be discussing some majorly used concepts here."
},
{
"code": null,
"e": 1611,
"s": 1447,
"text": "Testcase − It is response specific base class in accordance with a given set of inputs. We use base class of unit test i.e. “TestCase” to implement this operation."
},
{
"code": null,
"e": 1775,
"s": 1611,
"text": "Testcase − It is response specific base class in accordance with a given set of inputs. We use base class of unit test i.e. “TestCase” to implement this operation."
},
{
"code": null,
"e": 1859,
"s": 1775,
"text": "Testsuite − It is used to club test cases together and execute them simultaneously."
},
{
"code": null,
"e": 1943,
"s": 1859,
"text": "Testsuite − It is used to club test cases together and execute them simultaneously."
},
{
"code": null,
"e": 2072,
"s": 1943,
"text": "Testrunner − It follows an outcome-based execution of tasks. It is involved in displaying the results after executing the tasks."
},
{
"code": null,
"e": 2201,
"s": 2072,
"text": "Testrunner − It follows an outcome-based execution of tasks. It is involved in displaying the results after executing the tasks."
},
{
"code": null,
"e": 2290,
"s": 2201,
"text": "Test fixture − It serves as a baseline for the test cases in the associated environment."
},
{
"code": null,
"e": 2379,
"s": 2290,
"text": "Test fixture − It serves as a baseline for the test cases in the associated environment."
},
{
"code": null,
"e": 2435,
"s": 2379,
"text": "Now lets a basic example to see how unit testing works."
},
{
"code": null,
"e": 2446,
"s": 2435,
"text": " Live Demo"
},
{
"code": null,
"e": 2736,
"s": 2446,
"text": "import unittest\nclass TestStringMethods(unittest.TestCase):\n def test_upper(self):\n self.assertEqual('TUTOR'.lower(), 'tutor')\n def test_islower(self):\n self.assertTrue('tutor'.islower())\n self.assertFalse('Tutor'.islower())\nif __name__ == '__main__':\n unittest.main()"
},
{
"code": null,
"e": 2830,
"s": 2736,
"text": "...\n---------------------------------------------------------------\n\nRan 2 tests in 0.000s\nOK"
},
{
"code": null,
"e": 2983,
"s": 2830,
"text": "Here we extend the unit test class in the form of single inheritance. Here we used to built-in methods like assertEqual() , assertTrue() & assertFalse()"
},
{
"code": null,
"e": 3052,
"s": 2983,
"text": "assertEqual() is used to validate/compare the output with the result"
},
{
"code": null,
"e": 3124,
"s": 3052,
"text": "assertTrue() is used to verify that the given condition is True or not."
},
{
"code": null,
"e": 3198,
"s": 3124,
"text": "assertFalse() is used to verify that the given condition is False or not."
},
{
"code": null,
"e": 3251,
"s": 3198,
"text": "The output of the above code can be in three forms −"
},
{
"code": null,
"e": 3323,
"s": 3251,
"text": "OK – This indicates that all tests generated have executed successfully"
},
{
"code": null,
"e": 3416,
"s": 3323,
"text": "FAIL – This indicates either test case has failed and an AssertionError exception is raised."
},
{
"code": null,
"e": 3480,
"s": 3416,
"text": "ERROR – This indicates that the test raises an exception/error."
},
{
"code": null,
"e": 3530,
"s": 3480,
"text": "We can use the decorator @unittest.skip(<reason>)"
},
{
"code": null,
"e": 3541,
"s": 3530,
"text": " Live Demo"
},
{
"code": null,
"e": 3865,
"s": 3541,
"text": "import unittest\nclass TestString(unittest.TestCase):\n @unittest.skip(\"check skipped tests\")\n def test_upper(self):\n self.assertEqual('TUTOR'.lower(), 'tutor')\n def test_islower(self):\n self.assertTrue('tutor'.islower())\n self.assertFalse('Tutor'.islower())\nif __name__ == '__main__':\n unittest.main()"
},
{
"code": null,
"e": 3972,
"s": 3865,
"text": "...\n---------------------------------------------------------------\n-\nRan 2 tests in 0.000s\nOK (skipped=2)"
},
{
"code": null,
"e": 4082,
"s": 3972,
"text": "In this article, we learned about Unit Testing in Python using the unittest module in Python 3.x. Or earlier."
}
] |
Easy Fine-Tuning of Transformers for Named-Entity Recognition | by Lars Kjeldgaard | Towards Data Science
|
In this article, we will go through how to easily fine-tune any pretrained Natural Language Processing (=NLP) transformer for Named-Entity Recognition (=NER) in any language.
Why should you care? Well, NER is a powerful NLP task with many applications, as has been thoroughly described on Towards Data Science. However, effectively using NER often requires language or domain specific fine-tuning of your NER model based on the pretrained transformers that are available and realistic to use given your compute budget.
To show you how to do just that, we use the python package NERDA to fine-tune a BERT transformer for NER.
NERDA is a general purpose NER-system that can be used for fine-tuning any transformer for NER in any language with a minimum of code.
If you are not familiar with NER, look to the Wikipedia definition:
Named-entity recognition (also known as (named) entity identification, entity chunking, and entity extraction) is a Natural Language Processing subtask of information extraction that seeks to locate and classify named entities mentioned in unstructured text into pre-defined categories such as person names, organizations, locations, medical codes, time expressions, quantities, monetary values, percentages, etc.
We can illustrate this further with an example of a NER task.
TASK: Identify person names and organizations in text:
Jim bought 300 shares of Acme Corp.
SOLUTION: Persons: ‘Jim’, Organizations: ‘Acme Corp.’
To get an introduction to the other concepts and technologies mentioned in this article we have listed a number of previous Towards Data Science stories in the Resources section.
Now, let us turn to actually fine-tuning a transformer for NER.
The steps we show you are the same regardless of your choice of transformer and target language.
We will utilize the new python package NERDA for the job.
NERDA has an easy-to-use interface for fine-tuning NLP transformers for Named-Entity Recognition tasks. It builds on the popular machine learning framework PyTorch and Hugging Face transformers.
NERDA is open-sourced and available on the Python Package Index (PyPI). It can be installed with:
pip install NERDA
We will use the English CoNLL-2003 data set with NER annotations for training and validation of our model.First we download the data set and load the predefined training and validation data splits.
from NERDA.datasets import get_conll_data, download_conll_data download_conll_data()training = get_conll_data('train')validation = get_conll_data('valid')
CoNLL-2003 operates with the following types of named entities (fairly standard categories):
PERsonsORGanizationsLOCationsMISCellaneousOutside (not a named entity)
PERsons
ORGanizations
LOCations
MISCellaneous
Outside (not a named entity)
An observation from the CoNLL-2003 data set consists of a word-tokenized sentence with a named-entity tag for each of the word tokens.
Below you see an example of a random sentence from the CoNLL data set with its word-tokens coupled with their respective named-entity tags ([tag]).
Germany [B-LOC]'s [O]representative [O]to [O] the [O]European [B-ORG] Union [I-ORG] 's [O]veterinary [O] committee [O]Werner [B-PER] Zwingmann [I-PER]said [O]on [O] Wednesday [O]...
The data set implements the Inside-Outside-Beginning (IOB) tagging scheme.
The IOB tagging scheme implies, that words that are beginning of named entities are tagged with ‘B-’ and words ‘inside’ (=continuations of) named entities are tagged with ‘I-’.
In the example above, ‘Germany’ is identified as a LOCation, ‘European Union’ as an ORGanization and ‘Werner Zwingmann’ as a PERson.
As a first step, we specify the available NER tags for the task (excluding the special ‘outside’ tag).
tag_scheme = ['B-PER','I-PER','B-ORG','I-ORG','B-LOC','I-LOC','B-MISC','I-MISC']
Next, we must decide, which transformer from Hugging Face transformers, we want to fine-tune. We will stick with an uncased multilingual BERT transformer (a popular choice).
transformer = 'bert-base-multilingual-uncased'
Also, we have the option to provide a selection of basic hyperparameters for the network as well as for the model training itself.
# hyperparameters for networkdropout = 0.1# hyperparameters for trainingtraining_hyperparameters = {'epochs' : 4,'warmup_steps' : 500, 'train_batch_size': 13, 'learning_rate': 0.0001}
Now, put the pieces together into a complete model configuration using the NERDA model interface.
from NERDA.models import NERDAmodel = NERDA(dataset_training = training,dataset_validation = validation,tag_scheme = tag_scheme, tag_outside = 'O',transformer = transformer,dropout = dropout,hyperparameters = training_hyperparameters)
Under the hood NERDA implements a torch neural network, that builds on the chosen transformer (in this case BERT). By default, the architecture of the network will be analogous to the one of the models in Hvingelby et al. 2020 (you can also provide your own network architecture, if you want).
In order to train the model and thereby fine-tune the BERT transformer, all there is left to do is to invoke the train method.
model.train()
Note: this will take some time depending on the dimensions of your machine (if you want to skip training, you can go ahead and use one of the precooked models, that NERDA ships with).
And that is all there is to it. We have now fine-tuned our very own state-of-the-art BERT-based model for NER.
Let us see how the model performs (by means of F1-scores) on an independent test set.
>>> test = get_conll_data('test')>>> model.evaluate_performance(test)Level F1-Score B-PER 0.963I-PER 0.987B-ORG 0.887I-ORG 0.866B-LOC 0.922I-LOC 0.817B-MISC 0.823I-MISC 0.680AVG_MICRO 0.907
‘AVG_MICRO’: the micro-averaged F1-score across entity tags.
As you see, performance looks great.
We can now use the model for identifying named-entities in new texts, i.e.
>>> model.predict_text('Cristiano Ronaldo plays for Juventus FC')([['Cristian', 'Ronaldo', 'plays', 'for', 'Juventus', 'FC']], [['B-PER', 'I-PER', 'O', 'O', 'B-ORG', 'I-ORG']])
The model (correctly) identifies ‘Cristiano Ronaldo’ (football player) as a person and ‘Juventus FC’ (football club) as an organization.
For the time being more than 5000 transformer models are available on Hugging Face. So which one should you fine-tune? We hate to disappoint you, but the answer is: it depends. There is no free lunch. The transformer models all have their different strengths and weaknesses. In addition, you need to choose a transformer that aligns with your compute budget and level of respect for climate change.
As mentioned earlier, BERT is usually a good pick. The new kid on the block, ELECTRA, is however much more lightweight and computationally efficient compared to BERT and still performs very well on NER tasks.
Whatever transformer you pick, chances are that NERDA will support it. In the code example above all you would have to change in order to fine-tune an ELECTRA transformer in stead of BERT would be to change the transformer parameter, i.e.:
model = NERDA(...,transformer = 'google/electra-small-discriminator',...)
With NERDAyou can also fine-tune a transformer for any language e.g. using your own data set with ease. To fine-tune a transformer for NER in Danish, we can utilize the DaNE data set consisting of Danish sentences with NER annotations.
All you would have to change in the former code example to achieve this is simply:
from NERDA.datasets import get_dane_datamodel = NERDA(...,dataset_training = get_dane_data('train'),dataset_validation = get_dane_data('dev'),...)
If you do not have any (or just not enough) training data with NER annotations for the desired language, you can use tools like doccano for annotating new texts.
Surprisingly, fine-tuning NERDA for a specific language does not require as much annotated data as you might think, as NERDA leverages the knowledge that is already existing in the transformer. The Danish NER dataset DaNE, for example, includes not more than 5500 sentences, which is enough for training NERDA models with reasonable performance.
NERDA is developed as a part of Ekstra Bladet’s activities on Platform Intelligence in News (PIN). PIN is an industrial research project that is carried out in collaboration between the Technical University of Denmark, University of Copenhagen and Copenhagen Business School with funding from Innovation Fund Denmark. The project runs from 2020-2023 and develops recommender systems and natural language processing systems geared for news publishing, some of which are open sourced like NERDA.
Resources
github.com
huggingface.co
pytorch.org
github.com
“DaNE: A Named Entity Ressource for Danish”, Hvingelby et. al (2020)
|
[
{
"code": null,
"e": 347,
"s": 172,
"text": "In this article, we will go through how to easily fine-tune any pretrained Natural Language Processing (=NLP) transformer for Named-Entity Recognition (=NER) in any language."
},
{
"code": null,
"e": 691,
"s": 347,
"text": "Why should you care? Well, NER is a powerful NLP task with many applications, as has been thoroughly described on Towards Data Science. However, effectively using NER often requires language or domain specific fine-tuning of your NER model based on the pretrained transformers that are available and realistic to use given your compute budget."
},
{
"code": null,
"e": 797,
"s": 691,
"text": "To show you how to do just that, we use the python package NERDA to fine-tune a BERT transformer for NER."
},
{
"code": null,
"e": 932,
"s": 797,
"text": "NERDA is a general purpose NER-system that can be used for fine-tuning any transformer for NER in any language with a minimum of code."
},
{
"code": null,
"e": 1000,
"s": 932,
"text": "If you are not familiar with NER, look to the Wikipedia definition:"
},
{
"code": null,
"e": 1414,
"s": 1000,
"text": "Named-entity recognition (also known as (named) entity identification, entity chunking, and entity extraction) is a Natural Language Processing subtask of information extraction that seeks to locate and classify named entities mentioned in unstructured text into pre-defined categories such as person names, organizations, locations, medical codes, time expressions, quantities, monetary values, percentages, etc."
},
{
"code": null,
"e": 1476,
"s": 1414,
"text": "We can illustrate this further with an example of a NER task."
},
{
"code": null,
"e": 1531,
"s": 1476,
"text": "TASK: Identify person names and organizations in text:"
},
{
"code": null,
"e": 1567,
"s": 1531,
"text": "Jim bought 300 shares of Acme Corp."
},
{
"code": null,
"e": 1621,
"s": 1567,
"text": "SOLUTION: Persons: ‘Jim’, Organizations: ‘Acme Corp.’"
},
{
"code": null,
"e": 1800,
"s": 1621,
"text": "To get an introduction to the other concepts and technologies mentioned in this article we have listed a number of previous Towards Data Science stories in the Resources section."
},
{
"code": null,
"e": 1864,
"s": 1800,
"text": "Now, let us turn to actually fine-tuning a transformer for NER."
},
{
"code": null,
"e": 1961,
"s": 1864,
"text": "The steps we show you are the same regardless of your choice of transformer and target language."
},
{
"code": null,
"e": 2019,
"s": 1961,
"text": "We will utilize the new python package NERDA for the job."
},
{
"code": null,
"e": 2214,
"s": 2019,
"text": "NERDA has an easy-to-use interface for fine-tuning NLP transformers for Named-Entity Recognition tasks. It builds on the popular machine learning framework PyTorch and Hugging Face transformers."
},
{
"code": null,
"e": 2312,
"s": 2214,
"text": "NERDA is open-sourced and available on the Python Package Index (PyPI). It can be installed with:"
},
{
"code": null,
"e": 2330,
"s": 2312,
"text": "pip install NERDA"
},
{
"code": null,
"e": 2528,
"s": 2330,
"text": "We will use the English CoNLL-2003 data set with NER annotations for training and validation of our model.First we download the data set and load the predefined training and validation data splits."
},
{
"code": null,
"e": 2683,
"s": 2528,
"text": "from NERDA.datasets import get_conll_data, download_conll_data download_conll_data()training = get_conll_data('train')validation = get_conll_data('valid')"
},
{
"code": null,
"e": 2776,
"s": 2683,
"text": "CoNLL-2003 operates with the following types of named entities (fairly standard categories):"
},
{
"code": null,
"e": 2847,
"s": 2776,
"text": "PERsonsORGanizationsLOCationsMISCellaneousOutside (not a named entity)"
},
{
"code": null,
"e": 2855,
"s": 2847,
"text": "PERsons"
},
{
"code": null,
"e": 2869,
"s": 2855,
"text": "ORGanizations"
},
{
"code": null,
"e": 2879,
"s": 2869,
"text": "LOCations"
},
{
"code": null,
"e": 2893,
"s": 2879,
"text": "MISCellaneous"
},
{
"code": null,
"e": 2922,
"s": 2893,
"text": "Outside (not a named entity)"
},
{
"code": null,
"e": 3057,
"s": 2922,
"text": "An observation from the CoNLL-2003 data set consists of a word-tokenized sentence with a named-entity tag for each of the word tokens."
},
{
"code": null,
"e": 3205,
"s": 3057,
"text": "Below you see an example of a random sentence from the CoNLL data set with its word-tokens coupled with their respective named-entity tags ([tag])."
},
{
"code": null,
"e": 3387,
"s": 3205,
"text": "Germany [B-LOC]'s [O]representative [O]to [O] the [O]European [B-ORG] Union [I-ORG] 's [O]veterinary [O] committee [O]Werner [B-PER] Zwingmann [I-PER]said [O]on [O] Wednesday [O]..."
},
{
"code": null,
"e": 3462,
"s": 3387,
"text": "The data set implements the Inside-Outside-Beginning (IOB) tagging scheme."
},
{
"code": null,
"e": 3639,
"s": 3462,
"text": "The IOB tagging scheme implies, that words that are beginning of named entities are tagged with ‘B-’ and words ‘inside’ (=continuations of) named entities are tagged with ‘I-’."
},
{
"code": null,
"e": 3772,
"s": 3639,
"text": "In the example above, ‘Germany’ is identified as a LOCation, ‘European Union’ as an ORGanization and ‘Werner Zwingmann’ as a PERson."
},
{
"code": null,
"e": 3875,
"s": 3772,
"text": "As a first step, we specify the available NER tags for the task (excluding the special ‘outside’ tag)."
},
{
"code": null,
"e": 3956,
"s": 3875,
"text": "tag_scheme = ['B-PER','I-PER','B-ORG','I-ORG','B-LOC','I-LOC','B-MISC','I-MISC']"
},
{
"code": null,
"e": 4130,
"s": 3956,
"text": "Next, we must decide, which transformer from Hugging Face transformers, we want to fine-tune. We will stick with an uncased multilingual BERT transformer (a popular choice)."
},
{
"code": null,
"e": 4177,
"s": 4130,
"text": "transformer = 'bert-base-multilingual-uncased'"
},
{
"code": null,
"e": 4308,
"s": 4177,
"text": "Also, we have the option to provide a selection of basic hyperparameters for the network as well as for the model training itself."
},
{
"code": null,
"e": 4582,
"s": 4308,
"text": "# hyperparameters for networkdropout = 0.1# hyperparameters for trainingtraining_hyperparameters = {'epochs' : 4,'warmup_steps' : 500, 'train_batch_size': 13, 'learning_rate': 0.0001}"
},
{
"code": null,
"e": 4680,
"s": 4582,
"text": "Now, put the pieces together into a complete model configuration using the NERDA model interface."
},
{
"code": null,
"e": 4915,
"s": 4680,
"text": "from NERDA.models import NERDAmodel = NERDA(dataset_training = training,dataset_validation = validation,tag_scheme = tag_scheme, tag_outside = 'O',transformer = transformer,dropout = dropout,hyperparameters = training_hyperparameters)"
},
{
"code": null,
"e": 5209,
"s": 4915,
"text": "Under the hood NERDA implements a torch neural network, that builds on the chosen transformer (in this case BERT). By default, the architecture of the network will be analogous to the one of the models in Hvingelby et al. 2020 (you can also provide your own network architecture, if you want)."
},
{
"code": null,
"e": 5336,
"s": 5209,
"text": "In order to train the model and thereby fine-tune the BERT transformer, all there is left to do is to invoke the train method."
},
{
"code": null,
"e": 5350,
"s": 5336,
"text": "model.train()"
},
{
"code": null,
"e": 5534,
"s": 5350,
"text": "Note: this will take some time depending on the dimensions of your machine (if you want to skip training, you can go ahead and use one of the precooked models, that NERDA ships with)."
},
{
"code": null,
"e": 5645,
"s": 5534,
"text": "And that is all there is to it. We have now fine-tuned our very own state-of-the-art BERT-based model for NER."
},
{
"code": null,
"e": 5731,
"s": 5645,
"text": "Let us see how the model performs (by means of F1-scores) on an independent test set."
},
{
"code": null,
"e": 5930,
"s": 5731,
"text": ">>> test = get_conll_data('test')>>> model.evaluate_performance(test)Level F1-Score B-PER 0.963I-PER 0.987B-ORG 0.887I-ORG 0.866B-LOC 0.922I-LOC 0.817B-MISC 0.823I-MISC 0.680AVG_MICRO 0.907"
},
{
"code": null,
"e": 5991,
"s": 5930,
"text": "‘AVG_MICRO’: the micro-averaged F1-score across entity tags."
},
{
"code": null,
"e": 6028,
"s": 5991,
"text": "As you see, performance looks great."
},
{
"code": null,
"e": 6103,
"s": 6028,
"text": "We can now use the model for identifying named-entities in new texts, i.e."
},
{
"code": null,
"e": 6280,
"s": 6103,
"text": ">>> model.predict_text('Cristiano Ronaldo plays for Juventus FC')([['Cristian', 'Ronaldo', 'plays', 'for', 'Juventus', 'FC']], [['B-PER', 'I-PER', 'O', 'O', 'B-ORG', 'I-ORG']])"
},
{
"code": null,
"e": 6417,
"s": 6280,
"text": "The model (correctly) identifies ‘Cristiano Ronaldo’ (football player) as a person and ‘Juventus FC’ (football club) as an organization."
},
{
"code": null,
"e": 6816,
"s": 6417,
"text": "For the time being more than 5000 transformer models are available on Hugging Face. So which one should you fine-tune? We hate to disappoint you, but the answer is: it depends. There is no free lunch. The transformer models all have their different strengths and weaknesses. In addition, you need to choose a transformer that aligns with your compute budget and level of respect for climate change."
},
{
"code": null,
"e": 7025,
"s": 6816,
"text": "As mentioned earlier, BERT is usually a good pick. The new kid on the block, ELECTRA, is however much more lightweight and computationally efficient compared to BERT and still performs very well on NER tasks."
},
{
"code": null,
"e": 7265,
"s": 7025,
"text": "Whatever transformer you pick, chances are that NERDA will support it. In the code example above all you would have to change in order to fine-tune an ELECTRA transformer in stead of BERT would be to change the transformer parameter, i.e.:"
},
{
"code": null,
"e": 7339,
"s": 7265,
"text": "model = NERDA(...,transformer = 'google/electra-small-discriminator',...)"
},
{
"code": null,
"e": 7575,
"s": 7339,
"text": "With NERDAyou can also fine-tune a transformer for any language e.g. using your own data set with ease. To fine-tune a transformer for NER in Danish, we can utilize the DaNE data set consisting of Danish sentences with NER annotations."
},
{
"code": null,
"e": 7658,
"s": 7575,
"text": "All you would have to change in the former code example to achieve this is simply:"
},
{
"code": null,
"e": 7805,
"s": 7658,
"text": "from NERDA.datasets import get_dane_datamodel = NERDA(...,dataset_training = get_dane_data('train'),dataset_validation = get_dane_data('dev'),...)"
},
{
"code": null,
"e": 7967,
"s": 7805,
"text": "If you do not have any (or just not enough) training data with NER annotations for the desired language, you can use tools like doccano for annotating new texts."
},
{
"code": null,
"e": 8313,
"s": 7967,
"text": "Surprisingly, fine-tuning NERDA for a specific language does not require as much annotated data as you might think, as NERDA leverages the knowledge that is already existing in the transformer. The Danish NER dataset DaNE, for example, includes not more than 5500 sentences, which is enough for training NERDA models with reasonable performance."
},
{
"code": null,
"e": 8807,
"s": 8313,
"text": "NERDA is developed as a part of Ekstra Bladet’s activities on Platform Intelligence in News (PIN). PIN is an industrial research project that is carried out in collaboration between the Technical University of Denmark, University of Copenhagen and Copenhagen Business School with funding from Innovation Fund Denmark. The project runs from 2020-2023 and develops recommender systems and natural language processing systems geared for news publishing, some of which are open sourced like NERDA."
},
{
"code": null,
"e": 8817,
"s": 8807,
"text": "Resources"
},
{
"code": null,
"e": 8828,
"s": 8817,
"text": "github.com"
},
{
"code": null,
"e": 8843,
"s": 8828,
"text": "huggingface.co"
},
{
"code": null,
"e": 8855,
"s": 8843,
"text": "pytorch.org"
},
{
"code": null,
"e": 8866,
"s": 8855,
"text": "github.com"
}
] |
How To Host Your Own Python Models | by Emmett Boudreau | Towards Data Science
|
Under the topic of deployment with machine-learning, there are a lot of things to consider and a lot of different options that will provide you with a different result. Firstly, there are a lot of standard VPS and semi-shared hosts that you could go with for deploying your models. These are usually not great options for a beginner but allow for more freedom in what applications are used and how the file-system is arranged. Another option is, of course, a deployment solution like AWS or Google Cloud. While these are both great options, neither of them will give you the price-to-performance ratio and convenience of hosting a server yourself. Although there are of course drawbacks to hosting a server yourself, it is certainly a great option if you happen to have good and reliable internet and an extra computer lying around.
When you’re running your own server, something very important to consider is what it is actually going to run on. You might not have a full-blown server sitting in your closet like many computing maniacs, but that is fine. For most applications, it’s unlikely that you’re going to have a need for 128GB of memory and a ridiculously high core count processor. For example, if you wish to only deploy a few endpoints, maybe serve some static files, you could go with essentially any computer with more than 1GB of memory.
That being said, another thing you’ll want to consider is heat. How hot does it get where you live, and do you have centralized air-conditioning? It’s important to keep your server components cool, and server processors generate a lot of heat and will require a lot more environmental cooling than your average computer. As a result, you could even have a server but not want to use it because of the heat in your environment.
Another thing that you might want to consider is power consumption. After all, if you’re not using all of your server’s power, but running a high TDP processor, it might not even be cost-effective to host it yourself — you might end up paying more for electricity than you bargained for.
A great suggestion that I have when you don’t need all that much power is to use a laptop. Many people have an old I-7 or I-5 laptop with about 4GB of memory sitting around somewhere, and these are a great option for a simple server that can perform a lot of operations for incredibly cheap. Laptop processors have dramatically lower TDP compared to desktop processors, and as a result, they don’t generate nearly as much heat or use very much power.
The first thing you’re going to need to do in order to serve any sort of files to the world wide web is set up port forwarding. Port forwarding allows your local connection to your internet service provider and network to be not only incoming from networks, but also outgoing into networks. Web-pages and websites are always configured to run on port 80. Sometimes port 80 acts as a socket port for a port like 8000, for example, and this is precisely how your model is likely going to use your ports.
A default gateway is the default device IP that all of the other devices are going to use in order to pass through to your ISP. In other words, the default gateway of your network is your router’s local IP address. On Linux, you can obtain this information using
route -n
On Windows, you’re going to first need to run command prompt as administrator. Next, you’ll simply type
ipconfig
into the command prompt, return, and then search for default gateway in the list of values provided. Grab the default gateway for your network and paste it into your web-browser. This should bring you to the login page for your router, which you will of course now need to login to.
After logging in, your router’s setup will almost certainly vary, so it will be difficult to explain where port forwarding is going to be on every single router. Usually, it is either in its own tab or under the “ advanced” tab.
I’m not really sure why, but for some reason, it is likely your network is going to request an application name for forwarding your ports. This can be anything, it doesn’t really matter at all what the application is called. The only purpose this serves is for organization is my guess. You will want to forward ports 60–82 and ports 8000–8030. As to the question of TCP versus UDP, TCP is slower but will eat a lot less bandwidth, whereas UDP is fast but can cause unstable connections when used sparingly. To be clear, UDP is usually used for things that need a high-pinging connection like video-games and things of that nature. So for hosting a website, it’s probably a good idea to just use TCP. I usually just forward for both TCP and UDP, though, because the protocol doesn’t really take effect anywhere in this regard. The protocol is determined by the application, not the router, so all you would be doing by selecting TCP or UDP here is limiting your ability to use one or the other.
Next, you will, of course, need a domain. This is a self-explanatory process —
buy a domain.
Alternatively, you could always just use your server’s public IP address as your domain, as well. The next thing you will need to do is get your domain name server off of your router. This will let the domain registry know where to send incoming connections. You will need to then put this into the name-server on your chosen domain registration site.
Before getting into actually creating and deploying an endpoint, it’s important to test your server to see if it actually works. For this article, I’m going to be using Ubuntu as it is absolutely dominating the server market and beginner-friendly compared to RHEL or Arch servers. After connecting our new server to wifi, we’re going to want to either use dig or curl to get our public address. The problem with dig is that it often relies on name-servers that might identify you by your hardware address, not your IP address, so I usually do:
curl ifconfig.co
Now that we have the IP of our server, copy it into another computer. This is a public IP address, so it won’t work through a local area connection. In other words, we are not making a request to a local server, so we wouldn’t get a local server — so it doesn’t matter if the computer is on the same network or not, this will not work if the ports are not forwarded properly. Now back on the server run
python -im http.server
This will start up a development server that will serve the files stored on your machine statically. Now go ahead and navigate to that public IP address on your other computer, and if you end up in ~/ on your server, congratulations!
In order to set up the virtual part of your server, your first going to need to have an idea of what options you have to do so. The two biggest and most used options are NGINX and Apache. I published an article a while ago which compared the two if you’d like to learn more about them individually to make your decision:
medium.com
You’re also going to need to use Supervisor and set one up to run your server. I’m not going to be including configurations here, as this article is more networking-based, but here are articles that will walk you through how to deploy both Gunicorn3 (Python production servers) and Genie (Julia production servers) with NGINX and Supervisor:
towardsdatascience.com
towardsdatascience.com
And if you wanted to serve static files, I have got you covered for that, as well:
medium.com
The last step I would take in this project is installing Openssh on both machines with
(my daily machine runs Fedora)sudo dnf install openssh-client(The server runs Ubuntu)sudo apt-get install openssh-server
This will allow you to connect to the server while it is headless and not connected to any peripherals. This means that you will be able to log into it without ever needing to actually use the computer itself, which is pretty handy! Another cool thing is that you can also login to your public IPV4 address from anywhere in the world using SSH, as well, as long as the SSH port, port 22, is forwarded as well.
I’d say that depending on your situation, and what exactly it is that you want to do with your server, running your own server off your router can be a fantastic and incredibly cost-effective approach. Running your own server allows you to manage your own hardware, rather than rent it. Using a low TDP processor can really save you a few bucks as well, as you could end up spending pennies in power each month to keep your websites and endpoints up. Need more storage? Buy a bigger hard-drive. Need more memory? Buy more memory. It is simple and cuts out an often unwanted middleman who is running your website from behind the curtain, giving you the freedom and the flexibility to take your website anywhere!
|
[
{
"code": null,
"e": 1005,
"s": 172,
"text": "Under the topic of deployment with machine-learning, there are a lot of things to consider and a lot of different options that will provide you with a different result. Firstly, there are a lot of standard VPS and semi-shared hosts that you could go with for deploying your models. These are usually not great options for a beginner but allow for more freedom in what applications are used and how the file-system is arranged. Another option is, of course, a deployment solution like AWS or Google Cloud. While these are both great options, neither of them will give you the price-to-performance ratio and convenience of hosting a server yourself. Although there are of course drawbacks to hosting a server yourself, it is certainly a great option if you happen to have good and reliable internet and an extra computer lying around."
},
{
"code": null,
"e": 1525,
"s": 1005,
"text": "When you’re running your own server, something very important to consider is what it is actually going to run on. You might not have a full-blown server sitting in your closet like many computing maniacs, but that is fine. For most applications, it’s unlikely that you’re going to have a need for 128GB of memory and a ridiculously high core count processor. For example, if you wish to only deploy a few endpoints, maybe serve some static files, you could go with essentially any computer with more than 1GB of memory."
},
{
"code": null,
"e": 1952,
"s": 1525,
"text": "That being said, another thing you’ll want to consider is heat. How hot does it get where you live, and do you have centralized air-conditioning? It’s important to keep your server components cool, and server processors generate a lot of heat and will require a lot more environmental cooling than your average computer. As a result, you could even have a server but not want to use it because of the heat in your environment."
},
{
"code": null,
"e": 2240,
"s": 1952,
"text": "Another thing that you might want to consider is power consumption. After all, if you’re not using all of your server’s power, but running a high TDP processor, it might not even be cost-effective to host it yourself — you might end up paying more for electricity than you bargained for."
},
{
"code": null,
"e": 2691,
"s": 2240,
"text": "A great suggestion that I have when you don’t need all that much power is to use a laptop. Many people have an old I-7 or I-5 laptop with about 4GB of memory sitting around somewhere, and these are a great option for a simple server that can perform a lot of operations for incredibly cheap. Laptop processors have dramatically lower TDP compared to desktop processors, and as a result, they don’t generate nearly as much heat or use very much power."
},
{
"code": null,
"e": 3193,
"s": 2691,
"text": "The first thing you’re going to need to do in order to serve any sort of files to the world wide web is set up port forwarding. Port forwarding allows your local connection to your internet service provider and network to be not only incoming from networks, but also outgoing into networks. Web-pages and websites are always configured to run on port 80. Sometimes port 80 acts as a socket port for a port like 8000, for example, and this is precisely how your model is likely going to use your ports."
},
{
"code": null,
"e": 3456,
"s": 3193,
"text": "A default gateway is the default device IP that all of the other devices are going to use in order to pass through to your ISP. In other words, the default gateway of your network is your router’s local IP address. On Linux, you can obtain this information using"
},
{
"code": null,
"e": 3465,
"s": 3456,
"text": "route -n"
},
{
"code": null,
"e": 3569,
"s": 3465,
"text": "On Windows, you’re going to first need to run command prompt as administrator. Next, you’ll simply type"
},
{
"code": null,
"e": 3578,
"s": 3569,
"text": "ipconfig"
},
{
"code": null,
"e": 3861,
"s": 3578,
"text": "into the command prompt, return, and then search for default gateway in the list of values provided. Grab the default gateway for your network and paste it into your web-browser. This should bring you to the login page for your router, which you will of course now need to login to."
},
{
"code": null,
"e": 4090,
"s": 3861,
"text": "After logging in, your router’s setup will almost certainly vary, so it will be difficult to explain where port forwarding is going to be on every single router. Usually, it is either in its own tab or under the “ advanced” tab."
},
{
"code": null,
"e": 5085,
"s": 4090,
"text": "I’m not really sure why, but for some reason, it is likely your network is going to request an application name for forwarding your ports. This can be anything, it doesn’t really matter at all what the application is called. The only purpose this serves is for organization is my guess. You will want to forward ports 60–82 and ports 8000–8030. As to the question of TCP versus UDP, TCP is slower but will eat a lot less bandwidth, whereas UDP is fast but can cause unstable connections when used sparingly. To be clear, UDP is usually used for things that need a high-pinging connection like video-games and things of that nature. So for hosting a website, it’s probably a good idea to just use TCP. I usually just forward for both TCP and UDP, though, because the protocol doesn’t really take effect anywhere in this regard. The protocol is determined by the application, not the router, so all you would be doing by selecting TCP or UDP here is limiting your ability to use one or the other."
},
{
"code": null,
"e": 5164,
"s": 5085,
"text": "Next, you will, of course, need a domain. This is a self-explanatory process —"
},
{
"code": null,
"e": 5178,
"s": 5164,
"text": "buy a domain."
},
{
"code": null,
"e": 5530,
"s": 5178,
"text": "Alternatively, you could always just use your server’s public IP address as your domain, as well. The next thing you will need to do is get your domain name server off of your router. This will let the domain registry know where to send incoming connections. You will need to then put this into the name-server on your chosen domain registration site."
},
{
"code": null,
"e": 6074,
"s": 5530,
"text": "Before getting into actually creating and deploying an endpoint, it’s important to test your server to see if it actually works. For this article, I’m going to be using Ubuntu as it is absolutely dominating the server market and beginner-friendly compared to RHEL or Arch servers. After connecting our new server to wifi, we’re going to want to either use dig or curl to get our public address. The problem with dig is that it often relies on name-servers that might identify you by your hardware address, not your IP address, so I usually do:"
},
{
"code": null,
"e": 6091,
"s": 6074,
"text": "curl ifconfig.co"
},
{
"code": null,
"e": 6494,
"s": 6091,
"text": "Now that we have the IP of our server, copy it into another computer. This is a public IP address, so it won’t work through a local area connection. In other words, we are not making a request to a local server, so we wouldn’t get a local server — so it doesn’t matter if the computer is on the same network or not, this will not work if the ports are not forwarded properly. Now back on the server run"
},
{
"code": null,
"e": 6517,
"s": 6494,
"text": "python -im http.server"
},
{
"code": null,
"e": 6751,
"s": 6517,
"text": "This will start up a development server that will serve the files stored on your machine statically. Now go ahead and navigate to that public IP address on your other computer, and if you end up in ~/ on your server, congratulations!"
},
{
"code": null,
"e": 7072,
"s": 6751,
"text": "In order to set up the virtual part of your server, your first going to need to have an idea of what options you have to do so. The two biggest and most used options are NGINX and Apache. I published an article a while ago which compared the two if you’d like to learn more about them individually to make your decision:"
},
{
"code": null,
"e": 7083,
"s": 7072,
"text": "medium.com"
},
{
"code": null,
"e": 7425,
"s": 7083,
"text": "You’re also going to need to use Supervisor and set one up to run your server. I’m not going to be including configurations here, as this article is more networking-based, but here are articles that will walk you through how to deploy both Gunicorn3 (Python production servers) and Genie (Julia production servers) with NGINX and Supervisor:"
},
{
"code": null,
"e": 7448,
"s": 7425,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 7471,
"s": 7448,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 7554,
"s": 7471,
"text": "And if you wanted to serve static files, I have got you covered for that, as well:"
},
{
"code": null,
"e": 7565,
"s": 7554,
"text": "medium.com"
},
{
"code": null,
"e": 7652,
"s": 7565,
"text": "The last step I would take in this project is installing Openssh on both machines with"
},
{
"code": null,
"e": 7773,
"s": 7652,
"text": "(my daily machine runs Fedora)sudo dnf install openssh-client(The server runs Ubuntu)sudo apt-get install openssh-server"
},
{
"code": null,
"e": 8183,
"s": 7773,
"text": "This will allow you to connect to the server while it is headless and not connected to any peripherals. This means that you will be able to log into it without ever needing to actually use the computer itself, which is pretty handy! Another cool thing is that you can also login to your public IPV4 address from anywhere in the world using SSH, as well, as long as the SSH port, port 22, is forwarded as well."
}
] |
How can I make a time delay in Python?
|
In order to introduce delay of definite interval, we can use sleep() function that is available in time module of Standard Python library. The sleep() function takes an integer number corresponding to seconds as an argument.
time.sleep(sec)
In following example, current time is first displayed and then the execution is paused for 10 seconds using sleep() function.
import time
print ("current time : ",time.ctime())
time.sleep(10)
print ("after 10 sec : ",time.ctime())
|
[
{
"code": null,
"e": 1287,
"s": 1062,
"text": "In order to introduce delay of definite interval, we can use sleep() function that is available in time module of Standard Python library. The sleep() function takes an integer number corresponding to seconds as an argument."
},
{
"code": null,
"e": 1303,
"s": 1287,
"text": "time.sleep(sec)"
},
{
"code": null,
"e": 1429,
"s": 1303,
"text": "In following example, current time is first displayed and then the execution is paused for 10 seconds using sleep() function."
},
{
"code": null,
"e": 1535,
"s": 1429,
"text": "import time\nprint (\"current time : \",time.ctime())\ntime.sleep(10)\n print (\"after 10 sec : \",time.ctime())"
}
] |
Python 3 - String isspace() Method
|
The isspace() method checks whether the string consists of whitespace.
Following is the syntax for isspace() method −
str.isspace()
NA
This method returns true if there are only whitespace characters in the string and there is at least one character, false otherwise.
The following example shows the usage of isspace() method.
#!/usr/bin/python3
str = " "
print (str.isspace())
str = "This is string example....wow!!!"
print (str.isspace())
When we run above program, it produces the following result −
True
False
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": 2411,
"s": 2340,
"text": "The isspace() method checks whether the string consists of whitespace."
},
{
"code": null,
"e": 2458,
"s": 2411,
"text": "Following is the syntax for isspace() method −"
},
{
"code": null,
"e": 2473,
"s": 2458,
"text": "str.isspace()\n"
},
{
"code": null,
"e": 2476,
"s": 2473,
"text": "NA"
},
{
"code": null,
"e": 2609,
"s": 2476,
"text": "This method returns true if there are only whitespace characters in the string and there is at least one character, false otherwise."
},
{
"code": null,
"e": 2668,
"s": 2609,
"text": "The following example shows the usage of isspace() method."
},
{
"code": null,
"e": 2791,
"s": 2668,
"text": "#!/usr/bin/python3\n\nstr = \" \" \nprint (str.isspace())\n\nstr = \"This is string example....wow!!!\"\nprint (str.isspace())"
},
{
"code": null,
"e": 2853,
"s": 2791,
"text": "When we run above program, it produces the following result −"
},
{
"code": null,
"e": 2865,
"s": 2853,
"text": "True\nFalse\n"
},
{
"code": null,
"e": 2902,
"s": 2865,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 2918,
"s": 2902,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 2951,
"s": 2918,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 2970,
"s": 2951,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3005,
"s": 2970,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3027,
"s": 3005,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3061,
"s": 3027,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3089,
"s": 3061,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3124,
"s": 3089,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3138,
"s": 3124,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3171,
"s": 3138,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3188,
"s": 3171,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3195,
"s": 3188,
"text": " Print"
},
{
"code": null,
"e": 3206,
"s": 3195,
"text": " Add Notes"
}
] |
DateTime.SpecifyKind() Method in C# - GeeksforGeeks
|
06 Feb, 2019
This method is used to create a new DateTime object which has the same number of ticks as the specified DateTime but is designated as either local time, Coordinated Universal Time (UTC), or neither, as indicated by the specified DateTimeKind value.
Syntax: public static DateTime SpecifyKind (DateTime value, DateTimeKind kind);
Parameters:value: It is the date and time.kind: It is one of the enumeration values which indicates whether the new object represents local time, UTC, or neither.
Return Value: This method returns a new object that has the same number of ticks as the object represented by the value parameter and the DateTimeKind value specified by the kind parameter.
Below programs illustrate the use of DateTime.SpecifyKind(DateTime, DateTimeKind) Method:
Example 1:
// C# program to demonstrate the// DateTime.SpecifyKind(DateTime,// DateTimeKind) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // creating object of DateTime DateTime date = new DateTime(2005, 5, 6, 14, 34, 42); Console.WriteLine("Kind Before Using Method: " +date.Kind); // getting DateTime of same DateTime // instance using SpecifyKind() method DateTime value = DateTime.SpecifyKind(date, DateTimeKind.Local); Console.WriteLine("Kind After Using Method: " + value.Kind); Console.WriteLine("DateTime is {0}", value); }}
Kind Before Using Method: Unspecified
Kind After Using Method: Local
DateTime is 05/06/2005 14:34:42
Example 2:
// C# program to demonstrate the// DateTime.SpecifyKind(DateTime,// DateTimeKind) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // creating object of DateTime DateTime date = new DateTime(1970, 1, 1, 4, 0, 15); // getting DateTime of same DateTime // instance using SpecifyKind() method DateTime value = DateTime.SpecifyKind(date, DateTimeKind.Local); Console.WriteLine("DateTime is {0}", value); }}
DateTime is 01/01/1970 04:00:15
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.datetime.specifykind?view=netframework-4.7.2
CSharp DateTime Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
C# | Inheritance
Partial Classes in C#
C# | List Class
Lambda Expressions in C#
Difference between Hashtable and Dictionary in C#
Convert String to Character Array in C#
|
[
{
"code": null,
"e": 24302,
"s": 24274,
"text": "\n06 Feb, 2019"
},
{
"code": null,
"e": 24551,
"s": 24302,
"text": "This method is used to create a new DateTime object which has the same number of ticks as the specified DateTime but is designated as either local time, Coordinated Universal Time (UTC), or neither, as indicated by the specified DateTimeKind value."
},
{
"code": null,
"e": 24631,
"s": 24551,
"text": "Syntax: public static DateTime SpecifyKind (DateTime value, DateTimeKind kind);"
},
{
"code": null,
"e": 24794,
"s": 24631,
"text": "Parameters:value: It is the date and time.kind: It is one of the enumeration values which indicates whether the new object represents local time, UTC, or neither."
},
{
"code": null,
"e": 24984,
"s": 24794,
"text": "Return Value: This method returns a new object that has the same number of ticks as the object represented by the value parameter and the DateTimeKind value specified by the kind parameter."
},
{
"code": null,
"e": 25074,
"s": 24984,
"text": "Below programs illustrate the use of DateTime.SpecifyKind(DateTime, DateTimeKind) Method:"
},
{
"code": null,
"e": 25085,
"s": 25074,
"text": "Example 1:"
},
{
"code": "// C# program to demonstrate the// DateTime.SpecifyKind(DateTime,// DateTimeKind) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // creating object of DateTime DateTime date = new DateTime(2005, 5, 6, 14, 34, 42); Console.WriteLine(\"Kind Before Using Method: \" +date.Kind); // getting DateTime of same DateTime // instance using SpecifyKind() method DateTime value = DateTime.SpecifyKind(date, DateTimeKind.Local); Console.WriteLine(\"Kind After Using Method: \" + value.Kind); Console.WriteLine(\"DateTime is {0}\", value); }}",
"e": 25983,
"s": 25085,
"text": null
},
{
"code": null,
"e": 26085,
"s": 25983,
"text": "Kind Before Using Method: Unspecified\nKind After Using Method: Local\nDateTime is 05/06/2005 14:34:42\n"
},
{
"code": null,
"e": 26096,
"s": 26085,
"text": "Example 2:"
},
{
"code": "// C# program to demonstrate the// DateTime.SpecifyKind(DateTime,// DateTimeKind) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // creating object of DateTime DateTime date = new DateTime(1970, 1, 1, 4, 0, 15); // getting DateTime of same DateTime // instance using SpecifyKind() method DateTime value = DateTime.SpecifyKind(date, DateTimeKind.Local); Console.WriteLine(\"DateTime is {0}\", value); }}",
"e": 26677,
"s": 26096,
"text": null
},
{
"code": null,
"e": 26710,
"s": 26677,
"text": "DateTime is 01/01/1970 04:00:15\n"
},
{
"code": null,
"e": 26721,
"s": 26710,
"text": "Reference:"
},
{
"code": null,
"e": 26817,
"s": 26721,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.datetime.specifykind?view=netframework-4.7.2"
},
{
"code": null,
"e": 26840,
"s": 26817,
"text": "CSharp DateTime Struct"
},
{
"code": null,
"e": 26854,
"s": 26840,
"text": "CSharp-method"
},
{
"code": null,
"e": 26857,
"s": 26854,
"text": "C#"
},
{
"code": null,
"e": 26955,
"s": 26857,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26964,
"s": 26955,
"text": "Comments"
},
{
"code": null,
"e": 26977,
"s": 26964,
"text": "Old Comments"
},
{
"code": null,
"e": 27000,
"s": 26977,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27028,
"s": 27000,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 27068,
"s": 27028,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 27111,
"s": 27068,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 27128,
"s": 27111,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 27150,
"s": 27128,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 27166,
"s": 27150,
"text": "C# | List Class"
},
{
"code": null,
"e": 27191,
"s": 27166,
"text": "Lambda Expressions in C#"
},
{
"code": null,
"e": 27241,
"s": 27191,
"text": "Difference between Hashtable and Dictionary in C#"
}
] |
Machine Learning Basics: Polynomial Regression | by Gurucharan M K | Towards Data Science
|
In previous stories, I have given a brief of Linear Regression and showed how to perform Simple and Multiple Linear Regression. In this article, we will go through the program for building a Polynomial Regression model based on the non-linear data.
In the previous examples of Linear Regression, when the data is plotted on the graph, there was a linear relationship between both the dependent and independent variables. Thus, it was more suitable to build a linear model to get accurate predictions. What if the data points had the following non-linearity making the linear model giving an error in predictions due to non-linearity?
In this case, we have to build a polynomial relationship which will accurately fit the data points in the given plot. This is called Polynomial Regression. The formula for a Polynomial Regression curve is given as y=w1x+w2x2+..+b
Below are the GIFs of fitting both a Linear Regression model and a Polynomial Regression model on a non-linear data.
As we can see, the Linear regression always tends to make an error however hard it tries to fit in the data. On the other hand, the Polynomial Regression graph manages to fit the data points onto the line more accurately.
In this example, we will go through the implementation of Polynomial Regression, in which we will predict the Salary of a new employee based on his position level in his previous company from the salary data for the same position levels in the new company.
In this data, we have the two independent variables namely, Position and Level. There is one independent variable i.e., Salary. So, in this problem we have to train a Polynomial Regression model with this data to understand the correlation between the Level and Salary of the employee data in the company and be able to predict the salary for the new employee based on this data.
In this first step, we will be importing the libraries required to build the ML model. The NumPy library and the matplotlib are imported. Additionally, we have imported the Pandas library for data analysis.
import numpy as npimport matplotlib.pyplot as pltimport pandas as pd
In this step, we shall use pandas to store the data obtained from my github repository and store it as a Pandas DataFrame using the function “pd.read_csv”.
We go through our dataset and assign the independent variable (x) to the second column with the column name “Level” and the dependent variable (y) to the last column, which is the “Salary” to be predicted.
dataset = pd.read_csv('https://raw.githubusercontent.com/mk-gurucharan/Regression/master/PositionSalaries_Data.csv')X = dataset.iloc[:, 1:-1].valuesy = dataset.iloc[:, -1].valuesdataset.head(5)>>Position Level SalaryBusiness Analyst 1 45000Junior Consultant 2 50000Senior Consultant 3 60000Manager 4 80000Country Manager 5 110000
We use the corresponding .iloc function to slice the DataFrame to assign these indexes to X and Y. In this, the Level is taken as the independent variable and is assigned to X. The dependent variable that is to be predicted is the last column (-1) which is Salary and it is assigned to y. We print the DataFrame “dataset” to see if we have got the correct columns for our training data.
The dataset on which we are using has very few number of rows and hence we train the entire dataset for building the Polynomial Regression model. In this the “PolynomialFeatures” function is used to assign the degree of the polynomial line that we are going to plot. In this, the degree is set as 4.
The independent variable X is then fitted with the PolynomialFeatures class and is converted to a new variable X_poly. In this, the variable X is converted to a new matrix X_Poly which consists of all the polynomial combinations of features with degree=4.
from sklearn.preprocessing import PolynomialFeaturesfrom sklearn.linear_model import LinearRegressionpoly_reg = PolynomialFeatures(degree = 4)X_poly = poly_reg.fit_transform(X)lin_reg = LinearRegression()lin_reg.fit(X_poly, y)
The class “LinearRegression” is also imported and is assigned to the variable “lin_reg” which is fitted with the X_poly and y for building the model.
In this step, we are going to predict the values Salary based on the Polynomial Regression model built. The “regressor.predict” function is used to predict the values for our independent variable, X_poly. We assign the predicted values as y_pred. We now have two data, y(real values) and y_pred (predicted values).
y_pred = lin_reg.predict(X_poly)
In this step , we shall print both the values of y as Real Values and y_pred values as Predicted Values of each X_test in a Pandas DataFrame.
df = pd.DataFrame({'Real Values':y, 'Predicted Values':y_pred})df>>Real Values Predicted Values45000 53356.64335750000 31759.90676060000 58642.19114280000 94632.867133110000 121724.941725150000 143275.058275200000 184003.496504300000 289994.172494500000 528694.6386951000000 988916.083916
We can see that the model has done a great job in fitting the data and predicting the salary of the employee based on the position level.
In this last step, we shall visualize the polynomial model that was built using the given data and plot the values of “y” and “y_pred” on the graph and analyze the results
X_grid = np.arange(min(X), max(X), 0.1)X_grid = X_grid.reshape((len(X_grid), 1))plt.scatter(X, y, color = 'red')plt.scatter(X, y_pred, color = 'green')plt.plot(X_grid, lin_reg.predict(poly_reg.fit_transform(X_grid)), color = 'black')plt.title('Polynomial Regression')plt.xlabel('Position level')plt.ylabel('Salary')plt.show()
In this graph, the Real values are plotted in “Red” color and the Predicted values are plotted in “Green” color. The Polynomial Regression line that is generated is drawn in “Black” color.
I am attaching a link of my github repository where you can find the Google Colab notebook and the data files for your reference.
github.com
Hope I have been able to clearly explain the program for building a Polynomial Regression model.
You can also find the explanation of the program for other Regression models below:
Simple Linear Regression
Multiple Linear Regression
Polynomial Regression
Support Vector Regression
Decision Tree Regression
Random Forest Regression
We will come across the more complex models of Regression, Classification and Clustering in the upcoming articles. Till then, Happy Machine Learning!
|
[
{
"code": null,
"e": 420,
"s": 171,
"text": "In previous stories, I have given a brief of Linear Regression and showed how to perform Simple and Multiple Linear Regression. In this article, we will go through the program for building a Polynomial Regression model based on the non-linear data."
},
{
"code": null,
"e": 805,
"s": 420,
"text": "In the previous examples of Linear Regression, when the data is plotted on the graph, there was a linear relationship between both the dependent and independent variables. Thus, it was more suitable to build a linear model to get accurate predictions. What if the data points had the following non-linearity making the linear model giving an error in predictions due to non-linearity?"
},
{
"code": null,
"e": 1035,
"s": 805,
"text": "In this case, we have to build a polynomial relationship which will accurately fit the data points in the given plot. This is called Polynomial Regression. The formula for a Polynomial Regression curve is given as y=w1x+w2x2+..+b"
},
{
"code": null,
"e": 1152,
"s": 1035,
"text": "Below are the GIFs of fitting both a Linear Regression model and a Polynomial Regression model on a non-linear data."
},
{
"code": null,
"e": 1374,
"s": 1152,
"text": "As we can see, the Linear regression always tends to make an error however hard it tries to fit in the data. On the other hand, the Polynomial Regression graph manages to fit the data points onto the line more accurately."
},
{
"code": null,
"e": 1631,
"s": 1374,
"text": "In this example, we will go through the implementation of Polynomial Regression, in which we will predict the Salary of a new employee based on his position level in his previous company from the salary data for the same position levels in the new company."
},
{
"code": null,
"e": 2011,
"s": 1631,
"text": "In this data, we have the two independent variables namely, Position and Level. There is one independent variable i.e., Salary. So, in this problem we have to train a Polynomial Regression model with this data to understand the correlation between the Level and Salary of the employee data in the company and be able to predict the salary for the new employee based on this data."
},
{
"code": null,
"e": 2218,
"s": 2011,
"text": "In this first step, we will be importing the libraries required to build the ML model. The NumPy library and the matplotlib are imported. Additionally, we have imported the Pandas library for data analysis."
},
{
"code": null,
"e": 2287,
"s": 2218,
"text": "import numpy as npimport matplotlib.pyplot as pltimport pandas as pd"
},
{
"code": null,
"e": 2443,
"s": 2287,
"text": "In this step, we shall use pandas to store the data obtained from my github repository and store it as a Pandas DataFrame using the function “pd.read_csv”."
},
{
"code": null,
"e": 2649,
"s": 2443,
"text": "We go through our dataset and assign the independent variable (x) to the second column with the column name “Level” and the dependent variable (y) to the last column, which is the “Salary” to be predicted."
},
{
"code": null,
"e": 3039,
"s": 2649,
"text": "dataset = pd.read_csv('https://raw.githubusercontent.com/mk-gurucharan/Regression/master/PositionSalaries_Data.csv')X = dataset.iloc[:, 1:-1].valuesy = dataset.iloc[:, -1].valuesdataset.head(5)>>Position Level SalaryBusiness Analyst 1 45000Junior Consultant 2 50000Senior Consultant 3 60000Manager 4 80000Country Manager 5 110000"
},
{
"code": null,
"e": 3426,
"s": 3039,
"text": "We use the corresponding .iloc function to slice the DataFrame to assign these indexes to X and Y. In this, the Level is taken as the independent variable and is assigned to X. The dependent variable that is to be predicted is the last column (-1) which is Salary and it is assigned to y. We print the DataFrame “dataset” to see if we have got the correct columns for our training data."
},
{
"code": null,
"e": 3726,
"s": 3426,
"text": "The dataset on which we are using has very few number of rows and hence we train the entire dataset for building the Polynomial Regression model. In this the “PolynomialFeatures” function is used to assign the degree of the polynomial line that we are going to plot. In this, the degree is set as 4."
},
{
"code": null,
"e": 3982,
"s": 3726,
"text": "The independent variable X is then fitted with the PolynomialFeatures class and is converted to a new variable X_poly. In this, the variable X is converted to a new matrix X_Poly which consists of all the polynomial combinations of features with degree=4."
},
{
"code": null,
"e": 4209,
"s": 3982,
"text": "from sklearn.preprocessing import PolynomialFeaturesfrom sklearn.linear_model import LinearRegressionpoly_reg = PolynomialFeatures(degree = 4)X_poly = poly_reg.fit_transform(X)lin_reg = LinearRegression()lin_reg.fit(X_poly, y)"
},
{
"code": null,
"e": 4359,
"s": 4209,
"text": "The class “LinearRegression” is also imported and is assigned to the variable “lin_reg” which is fitted with the X_poly and y for building the model."
},
{
"code": null,
"e": 4674,
"s": 4359,
"text": "In this step, we are going to predict the values Salary based on the Polynomial Regression model built. The “regressor.predict” function is used to predict the values for our independent variable, X_poly. We assign the predicted values as y_pred. We now have two data, y(real values) and y_pred (predicted values)."
},
{
"code": null,
"e": 4707,
"s": 4674,
"text": "y_pred = lin_reg.predict(X_poly)"
},
{
"code": null,
"e": 4849,
"s": 4707,
"text": "In this step , we shall print both the values of y as Real Values and y_pred values as Predicted Values of each X_test in a Pandas DataFrame."
},
{
"code": null,
"e": 5202,
"s": 4849,
"text": "df = pd.DataFrame({'Real Values':y, 'Predicted Values':y_pred})df>>Real Values Predicted Values45000 53356.64335750000 31759.90676060000 58642.19114280000 94632.867133110000 121724.941725150000 143275.058275200000 184003.496504300000 289994.172494500000 528694.6386951000000 988916.083916"
},
{
"code": null,
"e": 5340,
"s": 5202,
"text": "We can see that the model has done a great job in fitting the data and predicting the salary of the employee based on the position level."
},
{
"code": null,
"e": 5512,
"s": 5340,
"text": "In this last step, we shall visualize the polynomial model that was built using the given data and plot the values of “y” and “y_pred” on the graph and analyze the results"
},
{
"code": null,
"e": 5838,
"s": 5512,
"text": "X_grid = np.arange(min(X), max(X), 0.1)X_grid = X_grid.reshape((len(X_grid), 1))plt.scatter(X, y, color = 'red')plt.scatter(X, y_pred, color = 'green')plt.plot(X_grid, lin_reg.predict(poly_reg.fit_transform(X_grid)), color = 'black')plt.title('Polynomial Regression')plt.xlabel('Position level')plt.ylabel('Salary')plt.show()"
},
{
"code": null,
"e": 6027,
"s": 5838,
"text": "In this graph, the Real values are plotted in “Red” color and the Predicted values are plotted in “Green” color. The Polynomial Regression line that is generated is drawn in “Black” color."
},
{
"code": null,
"e": 6157,
"s": 6027,
"text": "I am attaching a link of my github repository where you can find the Google Colab notebook and the data files for your reference."
},
{
"code": null,
"e": 6168,
"s": 6157,
"text": "github.com"
},
{
"code": null,
"e": 6265,
"s": 6168,
"text": "Hope I have been able to clearly explain the program for building a Polynomial Regression model."
},
{
"code": null,
"e": 6349,
"s": 6265,
"text": "You can also find the explanation of the program for other Regression models below:"
},
{
"code": null,
"e": 6374,
"s": 6349,
"text": "Simple Linear Regression"
},
{
"code": null,
"e": 6401,
"s": 6374,
"text": "Multiple Linear Regression"
},
{
"code": null,
"e": 6423,
"s": 6401,
"text": "Polynomial Regression"
},
{
"code": null,
"e": 6449,
"s": 6423,
"text": "Support Vector Regression"
},
{
"code": null,
"e": 6474,
"s": 6449,
"text": "Decision Tree Regression"
},
{
"code": null,
"e": 6499,
"s": 6474,
"text": "Random Forest Regression"
}
] |
D3.js transform.scale() Function - GeeksforGeeks
|
15 Oct, 2020
The transform.scale() function in D3.js library is used to get the transformation whose scale k1 is equal to k0k, where k0 is the transform’s scale.
Syntax:
transform.scale(k)
Parameters: This function accepts a single parameter as mentioned above and described below.
k: This parameter is the scale argument.
Return value: This function returns the transformed zoom behaviour.
Below programs illustrate the transform.scale() function in D3.js library.
Example 1:
HTML
<!DOCTYPE html><html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v4.min.js"> </script> </head> <body> <center> <h1 style="color: green;"> Geeksforgeeks </h1> <h3>D3.js | transform.scale() Function</h3> <script> var svg = d3.select("body").append("svg") .attr("width", 400) .attr("height", 300); var g1 = svg.append("g"), g2 = svg.append("g"); var zoom1 = d3.zoom().on("zoom", function () { g1.attr("transform", d3.event.transform); }); var zoom2 = d3.zoom().on("zoom", function () { g2.attr("transform", d3.event.transform); }); g1.call(zoom1.transform, d3.zoomIdentity .translate(150, 100) .scale(2)); g2.call(zoom2.transform, d3.zoomIdentity .translate(150, 100) .scale(2)); g1.append("rect") .attr("x", 20) .attr("y", 20) .attr("width", 60) .attr("height", 60); g2.append("rect") .attr("x", 25) .attr("y", 25) .attr("width", 50) .attr("height", 50) .attr("fill", "green"); d3.selectAll("rect").on("click", function () { g1.transition() .duration(3000) .attr("transform", d3.zoomIdentity) .on("end", function () { d3.select(this).call(zoom1.transform, d3.zoomIdentity); }) g2.transition() .duration(2000) .call(zoom2.transform, d3.zoomIdentity) }); </script> </center></body> </html>
Output:
Example 2:
HTML
<!DOCTYPE html><html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v4.min.js"> </script></head> <body> <center> <h1 style="color: green;"> Geeksforgeeks </h1> <h3>D3.js | transform.scale() Function</h3> <canvas width="500" height="300"></canvas> <script> var canvas = d3.select("canvas"), context = canvas.node().getContext("2d"), width = canvas.property("width"), height = canvas.property("height"), radius = 2.5; var points = d3.range(300).map(phyllotaxis(10)), point = points.pop(); var zoom = d3.zoom() .on("zoom", zoomed); canvas .call(zoom.transform, transform) .call(transition); function zoomed() { context.save(); context.clearRect(0, 0, width, height); context.translate(d3.event.transform.x, d3.event.transform.y); context.scale(d3.event.transform.k, d3.event.transform.k); drawPoints(); context.restore(); } function drawPoints() { context.beginPath(); points.forEach(drawPoint); context.fillStyle = "#8d0396"; context.fill(); context.beginPath(); drawPoint(point); context.fillStyle = "#00ab1c"; context.fill(); context.stroke(); } function drawPoint(point) { context.moveTo(point[0] + radius, point[1]); context.arc(point[0], point[1], radius, 0, 2 * Math.PI); } function transform() { return d3.zoomIdentity .translate(width / 2, height / 2) .scale(8) .translate(-point[0], -point[1]); } function transition(canvas) { var n = points.length, i = Math.random() * n | 0, c = points[i]; // Pick a random point. points[i] = points[n - 1]; points[n - 1] = point; point = c; canvas.transition() .delay(500) .duration(3000) .call(zoom.transform, transform) .on("end", function () { canvas.call(transition); }); } function phyllotaxis(radius) { var theta = Math.PI * (3 - Math.sqrt(5)); return function (i) { var r = radius * Math.sqrt(i), a = theta * i; return [ width / 2 + r * Math.cos(a), height / 2 + r * Math.sin(a) ]; }; } </script> </center></body> </html>
Output:
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
How to get selected value in dropdown list using JavaScript ?
How to remove duplicate elements from JavaScript Array ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25300,
"s": 25272,
"text": "\n15 Oct, 2020"
},
{
"code": null,
"e": 25449,
"s": 25300,
"text": "The transform.scale() function in D3.js library is used to get the transformation whose scale k1 is equal to k0k, where k0 is the transform’s scale."
},
{
"code": null,
"e": 25457,
"s": 25449,
"text": "Syntax:"
},
{
"code": null,
"e": 25478,
"s": 25457,
"text": " transform.scale(k)\n"
},
{
"code": null,
"e": 25571,
"s": 25478,
"text": "Parameters: This function accepts a single parameter as mentioned above and described below."
},
{
"code": null,
"e": 25612,
"s": 25571,
"text": "k: This parameter is the scale argument."
},
{
"code": null,
"e": 25680,
"s": 25612,
"text": "Return value: This function returns the transformed zoom behaviour."
},
{
"code": null,
"e": 25755,
"s": 25680,
"text": "Below programs illustrate the transform.scale() function in D3.js library."
},
{
"code": null,
"e": 25766,
"s": 25755,
"text": "Example 1:"
},
{
"code": null,
"e": 25771,
"s": 25766,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <script src=\"https://d3js.org/d3.v4.min.js\"> </script> </head> <body> <center> <h1 style=\"color: green;\"> Geeksforgeeks </h1> <h3>D3.js | transform.scale() Function</h3> <script> var svg = d3.select(\"body\").append(\"svg\") .attr(\"width\", 400) .attr(\"height\", 300); var g1 = svg.append(\"g\"), g2 = svg.append(\"g\"); var zoom1 = d3.zoom().on(\"zoom\", function () { g1.attr(\"transform\", d3.event.transform); }); var zoom2 = d3.zoom().on(\"zoom\", function () { g2.attr(\"transform\", d3.event.transform); }); g1.call(zoom1.transform, d3.zoomIdentity .translate(150, 100) .scale(2)); g2.call(zoom2.transform, d3.zoomIdentity .translate(150, 100) .scale(2)); g1.append(\"rect\") .attr(\"x\", 20) .attr(\"y\", 20) .attr(\"width\", 60) .attr(\"height\", 60); g2.append(\"rect\") .attr(\"x\", 25) .attr(\"y\", 25) .attr(\"width\", 50) .attr(\"height\", 50) .attr(\"fill\", \"green\"); d3.selectAll(\"rect\").on(\"click\", function () { g1.transition() .duration(3000) .attr(\"transform\", d3.zoomIdentity) .on(\"end\", function () { d3.select(this).call(zoom1.transform, d3.zoomIdentity); }) g2.transition() .duration(2000) .call(zoom2.transform, d3.zoomIdentity) }); </script> </center></body> </html>",
"e": 27677,
"s": 25771,
"text": null
},
{
"code": null,
"e": 27685,
"s": 27677,
"text": "Output:"
},
{
"code": null,
"e": 27696,
"s": 27685,
"text": "Example 2:"
},
{
"code": null,
"e": 27701,
"s": 27696,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <script src=\"https://d3js.org/d3.v4.min.js\"> </script></head> <body> <center> <h1 style=\"color: green;\"> Geeksforgeeks </h1> <h3>D3.js | transform.scale() Function</h3> <canvas width=\"500\" height=\"300\"></canvas> <script> var canvas = d3.select(\"canvas\"), context = canvas.node().getContext(\"2d\"), width = canvas.property(\"width\"), height = canvas.property(\"height\"), radius = 2.5; var points = d3.range(300).map(phyllotaxis(10)), point = points.pop(); var zoom = d3.zoom() .on(\"zoom\", zoomed); canvas .call(zoom.transform, transform) .call(transition); function zoomed() { context.save(); context.clearRect(0, 0, width, height); context.translate(d3.event.transform.x, d3.event.transform.y); context.scale(d3.event.transform.k, d3.event.transform.k); drawPoints(); context.restore(); } function drawPoints() { context.beginPath(); points.forEach(drawPoint); context.fillStyle = \"#8d0396\"; context.fill(); context.beginPath(); drawPoint(point); context.fillStyle = \"#00ab1c\"; context.fill(); context.stroke(); } function drawPoint(point) { context.moveTo(point[0] + radius, point[1]); context.arc(point[0], point[1], radius, 0, 2 * Math.PI); } function transform() { return d3.zoomIdentity .translate(width / 2, height / 2) .scale(8) .translate(-point[0], -point[1]); } function transition(canvas) { var n = points.length, i = Math.random() * n | 0, c = points[i]; // Pick a random point. points[i] = points[n - 1]; points[n - 1] = point; point = c; canvas.transition() .delay(500) .duration(3000) .call(zoom.transform, transform) .on(\"end\", function () { canvas.call(transition); }); } function phyllotaxis(radius) { var theta = Math.PI * (3 - Math.sqrt(5)); return function (i) { var r = radius * Math.sqrt(i), a = theta * i; return [ width / 2 + r * Math.cos(a), height / 2 + r * Math.sin(a) ]; }; } </script> </center></body> </html>",
"e": 30767,
"s": 27701,
"text": null
},
{
"code": null,
"e": 30775,
"s": 30767,
"text": "Output:"
},
{
"code": null,
"e": 30781,
"s": 30775,
"text": "D3.js"
},
{
"code": null,
"e": 30792,
"s": 30781,
"text": "JavaScript"
},
{
"code": null,
"e": 30809,
"s": 30792,
"text": "Web Technologies"
},
{
"code": null,
"e": 30907,
"s": 30809,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30916,
"s": 30907,
"text": "Comments"
},
{
"code": null,
"e": 30929,
"s": 30916,
"text": "Old Comments"
},
{
"code": null,
"e": 30990,
"s": 30929,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 31031,
"s": 30990,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 31085,
"s": 31031,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 31147,
"s": 31085,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 31204,
"s": 31147,
"text": "How to remove duplicate elements from JavaScript Array ?"
},
{
"code": null,
"e": 31246,
"s": 31204,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 31279,
"s": 31246,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 31341,
"s": 31279,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 31384,
"s": 31341,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
HTML DOM appendChild() Method
|
The HTML DOM appendChild() method is used to create and add a text node at the end of the list of child nodes. The appendChild() method can also be used to move an element from current position to a new position. Using appendChild() you can add new values to a list and can even add a new paragraph under another paragraph.
Following is the syntax for appendChild() Method −
node.appendChild( node )
Here, the parameter node is the object that you want to append. It is a compulsory parameter value.
Let us see an example of appendChild() Method −
Live Demo
<!DOCTYPE html>
<html>
<body>
<p>Click the button to create a paragraph and append it to the div</p>
<div id="SampleDIV">
A DIV element
</div>
<button onclick="AppendP()">Append</button>
<script>
var x=1;
function AppendP() {
var paragraph = document.createElement("P");
paragraph.innerHTML = "This is paragraph "+x;
document.getElementById("SampleDIV").appendChild(paragraph);
x++;
}
</script>
</body>
</html>
This will produce the following output −
After clicking append 3 times: −
In the above example −
We have created a div with id “SampleDIV”. The appended node will act as child of this div.
<div id="SampleDIV">
A DIV element
</div>
We have then a button named “Append” which will execute the function AppendP()
<button onclick="AppendP()">Append</button>
The AppendP() function first creates a paragraph (p) element and assigns it to variable paragraph. Then some text is added to paragraph using innerHTML and a variable x is appended to text. This variable is incremented each time we click the ”Append” button. At last we append the newly created paragraph as a child node of the div element −
var x=1;
function AppendP() {
var paragraph = document.createElement("P");
paragraph.innerHTML = "This is paragraph "+x;
document.getElementById("SampleDIV").appendChild(paragraph);
x++;
}
|
[
{
"code": null,
"e": 1386,
"s": 1062,
"text": "The HTML DOM appendChild() method is used to create and add a text node at the end of the list of child nodes. The appendChild() method can also be used to move an element from current position to a new position. Using appendChild() you can add new values to a list and can even add a new paragraph under another paragraph."
},
{
"code": null,
"e": 1437,
"s": 1386,
"text": "Following is the syntax for appendChild() Method −"
},
{
"code": null,
"e": 1462,
"s": 1437,
"text": "node.appendChild( node )"
},
{
"code": null,
"e": 1562,
"s": 1462,
"text": "Here, the parameter node is the object that you want to append. It is a compulsory parameter value."
},
{
"code": null,
"e": 1610,
"s": 1562,
"text": "Let us see an example of appendChild() Method −"
},
{
"code": null,
"e": 1621,
"s": 1610,
"text": " Live Demo"
},
{
"code": null,
"e": 2065,
"s": 1621,
"text": "<!DOCTYPE html>\n<html>\n<body>\n<p>Click the button to create a paragraph and append it to the div</p>\n<div id=\"SampleDIV\">\nA DIV element\n</div>\n<button onclick=\"AppendP()\">Append</button>\n<script>\n var x=1;\n function AppendP() {\n var paragraph = document.createElement(\"P\");\n paragraph.innerHTML = \"This is paragraph \"+x;\n document.getElementById(\"SampleDIV\").appendChild(paragraph);\n x++;\n }\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2106,
"s": 2065,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2139,
"s": 2106,
"text": "After clicking append 3 times: −"
},
{
"code": null,
"e": 2162,
"s": 2139,
"text": "In the above example −"
},
{
"code": null,
"e": 2254,
"s": 2162,
"text": "We have created a div with id “SampleDIV”. The appended node will act as child of this div."
},
{
"code": null,
"e": 2296,
"s": 2254,
"text": "<div id=\"SampleDIV\">\nA DIV element\n</div>"
},
{
"code": null,
"e": 2375,
"s": 2296,
"text": "We have then a button named “Append” which will execute the function AppendP()"
},
{
"code": null,
"e": 2419,
"s": 2375,
"text": "<button onclick=\"AppendP()\">Append</button>"
},
{
"code": null,
"e": 2761,
"s": 2419,
"text": "The AppendP() function first creates a paragraph (p) element and assigns it to variable paragraph. Then some text is added to paragraph using innerHTML and a variable x is appended to text. This variable is incremented each time we click the ”Append” button. At last we append the newly created paragraph as a child node of the div element −"
},
{
"code": null,
"e": 2962,
"s": 2761,
"text": "var x=1;\nfunction AppendP() {\n var paragraph = document.createElement(\"P\");\n paragraph.innerHTML = \"This is paragraph \"+x;\n document.getElementById(\"SampleDIV\").appendChild(paragraph);\n x++;\n}"
}
] |
Get the items which are not common of two Pandas series - GeeksforGeeks
|
01 Aug, 2020
Pandas does not support specific methods to perform set operations. However, we can use the following formula to get unique items from both the sets :
Algorithm :
Import the Pandas and NumPy modules.Create 2 Pandas Series.Find the union of the series using the union1d() method.Find the intersection of the series using the intersect1d() method.Find the difference between the union and the intersection elements. Use the isin() method to get the boolean list of items present in both ‘union’ and ‘intersect’.Print the result
Import the Pandas and NumPy modules.
Create 2 Pandas Series.
Find the union of the series using the union1d() method.
Find the intersection of the series using the intersect1d() method.
Find the difference between the union and the intersection elements. Use the isin() method to get the boolean list of items present in both ‘union’ and ‘intersect’.
Print the result
# import the modulesimport pandas as pd import numpy as np # create the series ser1 = pd.Series([1, 2, 3, 4, 5])ser2 = pd.Series([3, 4, 5, 6, 7]) # union of the seriesunion = pd.Series(np.union1d(ser1, ser2)) # intersection of the seriesintersect = pd.Series(np.intersect1d(ser1, ser2)) # uncommon elements in both the series notcommonseries = union[~union.isin(intersect)] # displaying the resultprint(notcommonseries)
Output :
1, 2, 6, 7
Python pandas-series
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n01 Aug, 2020"
},
{
"code": null,
"e": 24443,
"s": 24292,
"text": "Pandas does not support specific methods to perform set operations. However, we can use the following formula to get unique items from both the sets :"
},
{
"code": null,
"e": 24455,
"s": 24443,
"text": "Algorithm :"
},
{
"code": null,
"e": 24818,
"s": 24455,
"text": "Import the Pandas and NumPy modules.Create 2 Pandas Series.Find the union of the series using the union1d() method.Find the intersection of the series using the intersect1d() method.Find the difference between the union and the intersection elements. Use the isin() method to get the boolean list of items present in both ‘union’ and ‘intersect’.Print the result"
},
{
"code": null,
"e": 24855,
"s": 24818,
"text": "Import the Pandas and NumPy modules."
},
{
"code": null,
"e": 24879,
"s": 24855,
"text": "Create 2 Pandas Series."
},
{
"code": null,
"e": 24936,
"s": 24879,
"text": "Find the union of the series using the union1d() method."
},
{
"code": null,
"e": 25004,
"s": 24936,
"text": "Find the intersection of the series using the intersect1d() method."
},
{
"code": null,
"e": 25169,
"s": 25004,
"text": "Find the difference between the union and the intersection elements. Use the isin() method to get the boolean list of items present in both ‘union’ and ‘intersect’."
},
{
"code": null,
"e": 25186,
"s": 25169,
"text": "Print the result"
},
{
"code": "# import the modulesimport pandas as pd import numpy as np # create the series ser1 = pd.Series([1, 2, 3, 4, 5])ser2 = pd.Series([3, 4, 5, 6, 7]) # union of the seriesunion = pd.Series(np.union1d(ser1, ser2)) # intersection of the seriesintersect = pd.Series(np.intersect1d(ser1, ser2)) # uncommon elements in both the series notcommonseries = union[~union.isin(intersect)] # displaying the resultprint(notcommonseries)",
"e": 25611,
"s": 25186,
"text": null
},
{
"code": null,
"e": 25620,
"s": 25611,
"text": "Output :"
},
{
"code": null,
"e": 25631,
"s": 25620,
"text": "1, 2, 6, 7"
},
{
"code": null,
"e": 25652,
"s": 25631,
"text": "Python pandas-series"
},
{
"code": null,
"e": 25666,
"s": 25652,
"text": "Python-pandas"
},
{
"code": null,
"e": 25673,
"s": 25666,
"text": "Python"
},
{
"code": null,
"e": 25771,
"s": 25673,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25780,
"s": 25771,
"text": "Comments"
},
{
"code": null,
"e": 25793,
"s": 25780,
"text": "Old Comments"
},
{
"code": null,
"e": 25825,
"s": 25793,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25881,
"s": 25825,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25936,
"s": 25881,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 25978,
"s": 25936,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26020,
"s": 25978,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26051,
"s": 26020,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26090,
"s": 26051,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26112,
"s": 26090,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26141,
"s": 26112,
"text": "Create a directory in Python"
}
] |
C library function - puts()
|
The C library function int puts(const char *str) writes a string to stdout up to but not including the null character. A newline character is appended to the output.
Following is the declaration for puts() function.
int puts(const char *str)
str − This is the C string to be written.
str − This is the C string to be written.
If successful, non-negative value is returned. On error, the function returns EOF.
The following example shows the usage of puts() function.
#include <stdio.h>
#include <string.h>
int main () {
char str1[15];
char str2[15];
strcpy(str1, "tutorialspoint");
strcpy(str2, "compileonline");
puts(str1);
puts(str2);
return(0);
}
Let us compile and run the above program to produce the following result −
tutorialspoint
compileonline
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": 2173,
"s": 2007,
"text": "The C library function int puts(const char *str) writes a string to stdout up to but not including the null character. A newline character is appended to the output."
},
{
"code": null,
"e": 2223,
"s": 2173,
"text": "Following is the declaration for puts() function."
},
{
"code": null,
"e": 2249,
"s": 2223,
"text": "int puts(const char *str)"
},
{
"code": null,
"e": 2291,
"s": 2249,
"text": "str − This is the C string to be written."
},
{
"code": null,
"e": 2333,
"s": 2291,
"text": "str − This is the C string to be written."
},
{
"code": null,
"e": 2416,
"s": 2333,
"text": "If successful, non-negative value is returned. On error, the function returns EOF."
},
{
"code": null,
"e": 2474,
"s": 2416,
"text": "The following example shows the usage of puts() function."
},
{
"code": null,
"e": 2685,
"s": 2474,
"text": "#include <stdio.h>\n#include <string.h>\n\nint main () {\n char str1[15];\n char str2[15];\n\n strcpy(str1, \"tutorialspoint\");\n strcpy(str2, \"compileonline\");\n\n puts(str1);\n puts(str2);\n \n return(0);\n}"
},
{
"code": null,
"e": 2760,
"s": 2685,
"text": "Let us compile and run the above program to produce the following result −"
},
{
"code": null,
"e": 2790,
"s": 2760,
"text": "tutorialspoint\ncompileonline\n"
},
{
"code": null,
"e": 2823,
"s": 2790,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2838,
"s": 2823,
"text": " Nishant Malik"
},
{
"code": null,
"e": 2873,
"s": 2838,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2888,
"s": 2873,
"text": " Nishant Malik"
},
{
"code": null,
"e": 2923,
"s": 2888,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 2937,
"s": 2923,
"text": " Asif Hussain"
},
{
"code": null,
"e": 2970,
"s": 2937,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2988,
"s": 2970,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 3023,
"s": 2988,
"text": "\n 20 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3042,
"s": 3023,
"text": " Vandana Annavaram"
},
{
"code": null,
"e": 3075,
"s": 3042,
"text": "\n 44 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3087,
"s": 3075,
"text": " Amit Diwan"
},
{
"code": null,
"e": 3094,
"s": 3087,
"text": " Print"
},
{
"code": null,
"e": 3105,
"s": 3094,
"text": " Add Notes"
}
] |
C# program to replace n-th character from a given index in a string
|
Firstly, set a string.
string str1 = "Port";
Console.WriteLine("Original String: "+str1);
Now convert the string into character array.
char[] ch = str1.ToCharArray();
Set the character you want to replace with the index of the location. To set a character at position 3rd.
ch[2] = 'F';
To remove nth character from a string, try the following C# code. Here, we are replacing the first character.
Live Demo
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(string[] args) {
string str1 = "Port";
Console.WriteLine("Original String: "+str1);
char[] ch = str1.ToCharArray();
ch[0] = 'F';
string str2 = new string (ch);
Console.WriteLine("New String: "+str2);
}
}
Original String: Port
New String: Fort
|
[
{
"code": null,
"e": 1085,
"s": 1062,
"text": "Firstly, set a string."
},
{
"code": null,
"e": 1152,
"s": 1085,
"text": "string str1 = \"Port\";\nConsole.WriteLine(\"Original String: \"+str1);"
},
{
"code": null,
"e": 1197,
"s": 1152,
"text": "Now convert the string into character array."
},
{
"code": null,
"e": 1229,
"s": 1197,
"text": "char[] ch = str1.ToCharArray();"
},
{
"code": null,
"e": 1335,
"s": 1229,
"text": "Set the character you want to replace with the index of the location. To set a character at position 3rd."
},
{
"code": null,
"e": 1348,
"s": 1335,
"text": "ch[2] = 'F';"
},
{
"code": null,
"e": 1458,
"s": 1348,
"text": "To remove nth character from a string, try the following C# code. Here, we are replacing the first character."
},
{
"code": null,
"e": 1469,
"s": 1458,
"text": " Live Demo"
},
{
"code": null,
"e": 1807,
"s": 1469,
"text": "using System;\nusing System.Collections.Generic;\npublic class Demo {\n public static void Main(string[] args) {\n string str1 = \"Port\";\n Console.WriteLine(\"Original String: \"+str1);\n char[] ch = str1.ToCharArray();\n ch[0] = 'F';\n string str2 = new string (ch);\n Console.WriteLine(\"New String: \"+str2);\n }\n}"
},
{
"code": null,
"e": 1846,
"s": 1807,
"text": "Original String: Port\nNew String: Fort"
}
] |
Count of sub-strings of length n possible from the given string - GeeksforGeeks
|
07 May, 2021
Given a string str and an integer N, the task is to find the number of possible sub-strings of length N.Examples:
Input: str = “geeksforgeeks”, n = 5 Output: 9 All possible sub-strings of length 5 are “geeks”, “eeksf”, “eksfo”, “ksfor”, “sforg”, “forge”, “orgee”, “rgeek” and “geeks”.Input: str = “jgec”, N = 2 Output: 3
Approach: The count of sub-strings of length n will always be len – n + 1 where len is the length of the given string. For example, if str = “geeksforgeeks” and n = 5 then the count of sub-strings having length 5 will be “geeks”, “eeksf”, “eksfo”, “ksfor”, “sforg”, “forge”, “orgee”, “rgeek” and “geeks” which is len – n + 1 = 13 – 5 + 1 = 9.Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of// possible sub-strings of length nint countSubStr(string str, int n){ int len = str.length(); return (len - n + 1);} // Driver codeint main(){ string str = "geeksforgeeks"; int n = 5; cout << countSubStr(str, n); return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ // Function to return the count of// possible sub-strings of length nstatic int countSubStr(String str, int n){ int len = str.length(); return (len - n + 1);} // Driver codepublic static void main(String args[]){ String str = "geeksforgeeks"; int n = 5; System.out.print(countSubStr(str, n));}} // This code is contributed by mohit kumar 29
# Python3 implementation of the approach # Function to return the count of# possible sub-strings of length ndef countSubStr(string, n) : length = len(string); return (length - n + 1); # Driver codeif __name__ == "__main__" : string = "geeksforgeeks"; n = 5; print(countSubStr(string, n)); # This code is contributed by Ryuga
// C# implementation of the approachusing System; class GFG{ // Function to return the count of// possible sub-strings of length nstatic int countSubStr(string str, int n){ int len = str.Length; return (len - n + 1);} // Driver codepublic static void Main(){ string str = "geeksforgeeks"; int n = 5; Console.WriteLine(countSubStr(str, n));}} // This code is contributed by Code_Mech.
<?php// PHP implementation of the approach // Function to return the count of// possible sub-strings of length nfunction countSubStr($str, $n){ $len = strlen($str); return ($len - $n + 1);} // Driver code$str = "geeksforgeeks";$n = 5; echo(countSubStr($str, $n)); // This code is contributed by Code_Mech.?>
<script> // JavaScript implementation of the approach // Function to return the count of // possible sub-strings of length n function countSubStr(str, n) { var len = str.length; return len - n + 1; } // Driver code var str = "geeksforgeeks"; var n = 5; document.write(countSubStr(str, n));</script>
9
ankthon
mohit kumar 29
Code_Mech
rdtank
substring
C++ Programs
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Passing a function as a parameter in C++
Const keyword in C++
Program to implement Singly Linked List in C++ using class
cout in C++
Dynamic _Cast in C++
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
C++ Data Types
Write a program to print all permutations of a given string
|
[
{
"code": null,
"e": 24528,
"s": 24500,
"text": "\n07 May, 2021"
},
{
"code": null,
"e": 24644,
"s": 24528,
"text": "Given a string str and an integer N, the task is to find the number of possible sub-strings of length N.Examples: "
},
{
"code": null,
"e": 24853,
"s": 24644,
"text": "Input: str = “geeksforgeeks”, n = 5 Output: 9 All possible sub-strings of length 5 are “geeks”, “eeksf”, “eksfo”, “ksfor”, “sforg”, “forge”, “orgee”, “rgeek” and “geeks”.Input: str = “jgec”, N = 2 Output: 3 "
},
{
"code": null,
"e": 25250,
"s": 24855,
"text": "Approach: The count of sub-strings of length n will always be len – n + 1 where len is the length of the given string. For example, if str = “geeksforgeeks” and n = 5 then the count of sub-strings having length 5 will be “geeks”, “eeksf”, “eksfo”, “ksfor”, “sforg”, “forge”, “orgee”, “rgeek” and “geeks” which is len – n + 1 = 13 – 5 + 1 = 9.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25254,
"s": 25250,
"text": "C++"
},
{
"code": null,
"e": 25259,
"s": 25254,
"text": "Java"
},
{
"code": null,
"e": 25267,
"s": 25259,
"text": "Python3"
},
{
"code": null,
"e": 25270,
"s": 25267,
"text": "C#"
},
{
"code": null,
"e": 25274,
"s": 25270,
"text": "PHP"
},
{
"code": null,
"e": 25285,
"s": 25274,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of// possible sub-strings of length nint countSubStr(string str, int n){ int len = str.length(); return (len - n + 1);} // Driver codeint main(){ string str = \"geeksforgeeks\"; int n = 5; cout << countSubStr(str, n); return 0;}",
"e": 25646,
"s": 25285,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG{ // Function to return the count of// possible sub-strings of length nstatic int countSubStr(String str, int n){ int len = str.length(); return (len - n + 1);} // Driver codepublic static void main(String args[]){ String str = \"geeksforgeeks\"; int n = 5; System.out.print(countSubStr(str, n));}} // This code is contributed by mohit kumar 29",
"e": 26072,
"s": 25646,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the count of# possible sub-strings of length ndef countSubStr(string, n) : length = len(string); return (length - n + 1); # Driver codeif __name__ == \"__main__\" : string = \"geeksforgeeks\"; n = 5; print(countSubStr(string, n)); # This code is contributed by Ryuga",
"e": 26419,
"s": 26072,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to return the count of// possible sub-strings of length nstatic int countSubStr(string str, int n){ int len = str.Length; return (len - n + 1);} // Driver codepublic static void Main(){ string str = \"geeksforgeeks\"; int n = 5; Console.WriteLine(countSubStr(str, n));}} // This code is contributed by Code_Mech.",
"e": 26819,
"s": 26419,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Function to return the count of// possible sub-strings of length nfunction countSubStr($str, $n){ $len = strlen($str); return ($len - $n + 1);} // Driver code$str = \"geeksforgeeks\";$n = 5; echo(countSubStr($str, $n)); // This code is contributed by Code_Mech.?>",
"e": 27133,
"s": 26819,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach // Function to return the count of // possible sub-strings of length n function countSubStr(str, n) { var len = str.length; return len - n + 1; } // Driver code var str = \"geeksforgeeks\"; var n = 5; document.write(countSubStr(str, n));</script>",
"e": 27449,
"s": 27133,
"text": null
},
{
"code": null,
"e": 27451,
"s": 27449,
"text": "9"
},
{
"code": null,
"e": 27461,
"s": 27453,
"text": "ankthon"
},
{
"code": null,
"e": 27476,
"s": 27461,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 27486,
"s": 27476,
"text": "Code_Mech"
},
{
"code": null,
"e": 27493,
"s": 27486,
"text": "rdtank"
},
{
"code": null,
"e": 27503,
"s": 27493,
"text": "substring"
},
{
"code": null,
"e": 27516,
"s": 27503,
"text": "C++ Programs"
},
{
"code": null,
"e": 27524,
"s": 27516,
"text": "Strings"
},
{
"code": null,
"e": 27532,
"s": 27524,
"text": "Strings"
},
{
"code": null,
"e": 27630,
"s": 27532,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27639,
"s": 27630,
"text": "Comments"
},
{
"code": null,
"e": 27652,
"s": 27639,
"text": "Old Comments"
},
{
"code": null,
"e": 27693,
"s": 27652,
"text": "Passing a function as a parameter in C++"
},
{
"code": null,
"e": 27714,
"s": 27693,
"text": "Const keyword in C++"
},
{
"code": null,
"e": 27773,
"s": 27714,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 27785,
"s": 27773,
"text": "cout in C++"
},
{
"code": null,
"e": 27806,
"s": 27785,
"text": "Dynamic _Cast in C++"
},
{
"code": null,
"e": 27831,
"s": 27806,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 27877,
"s": 27831,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 27911,
"s": 27877,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 27926,
"s": 27911,
"text": "C++ Data Types"
}
] |
Java Online Compiler (Editor / Interpreter)
|
With our online Java compiler, you can edit Java code, and view the result in your browser.
public class Main {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
Click on the "Try it Yourself" button to see how it works.
The window to the left is editable - edit the code and click on the "Run" button to view the result in the right window.
The icons are explained in the table below:
If you don't know Java, we suggest that you read our Java Tutorial from scratch.
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 92,
"s": 0,
"text": "With our online Java compiler, you can edit Java code, and view the result in your browser."
},
{
"code": null,
"e": 202,
"s": 92,
"text": "public class Main {\n public static void main(String[] args) {\n System.out.println(\"Hello World!\");\n }\n}\n"
},
{
"code": null,
"e": 261,
"s": 202,
"text": "Click on the \"Try it Yourself\" button to see how it works."
},
{
"code": null,
"e": 382,
"s": 261,
"text": "The window to the left is editable - edit the code and click on the \"Run\" button to view the result in the right window."
},
{
"code": null,
"e": 426,
"s": 382,
"text": "The icons are explained in the table below:"
},
{
"code": null,
"e": 507,
"s": 426,
"text": "If you don't know Java, we suggest that you read our Java Tutorial from scratch."
},
{
"code": null,
"e": 540,
"s": 507,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 582,
"s": 540,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 689,
"s": 582,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 708,
"s": 689,
"text": "help@w3schools.com"
}
] |
Character Class in Java - GeeksforGeeks
|
14 Feb, 2022
Java provides a wrapper class Character in java.lang package. An object of type Character contains a single field, whose type is char. The Character class offers a number of useful class (i.e., static) methods for manipulating characters. You can create a Character object with the Character constructor.
Creating a Character object:
Character ch = new Character('a');
The above statement creates a Character object which contains ‘a’ of type char. There is only one constructor in the Character class that expects an argument of char data type.
If we pass a primitive char into a method that expects an object, the compiler automatically converts the char to a Character class object. This feature is called Autoboxing and Unboxing.
Note: The Character class is immutable like String class i.e once it’s object is created, it cannot be changed.
The methods of Character class are as follows:
1. boolean isLetter(char ch): This method is used to determine whether the specified char value(ch) is a letter or not. The method will return true if it is letter([A-Z],[a-z]), otherwise return false. In place of character, we can also pass ASCII value as an argument as char to int is implicitly typecasted in java.
Syntax:
boolean isLetter(char ch)
Parameters:
ch – a primitive character
Returns: It returns true if ch is an alphabet, otherwise, return false
Example:
Java
// Java program to demonstrate isLetter() method public class Test { public static void main(String[] args) { System.out.println(Character.isLetter('A')); System.out.println(Character.isLetter('0')); }}
true
false
2. boolean isDigit(char ch): This method is used to determine whether the specified char value(ch) is a digit or not. Here also we can pass ASCII value as an argument.
Syntax:
boolean isDigit(char ch)
Parameters:
ch – a primitive character
Returns: It returns true if ch is a digit, otherwise, return false
Example:
Java
// Java program to demonstrate isDigit() method public class Test { public static void main(String[] args) { // print false as A is character System.out.println(Character.isDigit('A')); System.out.println(Character.isDigit('0')); }}
false
true
3. boolean isWhitespace(char ch): It determines whether the specified char value(ch) is white space. Whitespace includes space, tab, or newline.
Syntax:
boolean isWhitespace(char ch)
Parameters:
ch – a primitive character
Returns: It returns true if ch is whitespace, otherwise, returns false.
Example:
Java
// Java program to demonstrate isWhitespace() method public class Test { public static void main(String[] args) { System.out.println(Character.isWhitespace('A')); System.out.println(Character.isWhitespace(' ')); System.out.println(Character.isWhitespace('\n')); System.out.println(Character.isWhitespace('\t')); // ASCII value of tab System.out.println(Character.isWhitespace(9)); System.out.println(Character.isWhitespace('9')); }}
false
true
true
true
true
false
4. boolean isUpperCase(char ch): It determines whether the specified char value(ch) is uppercase or not.
Syntax:
boolean isUpperCase(char ch)
Parameters:
ch – a primitive character
Returns: It returns true if ch is upper case, otherwise, returns false.
Example:
Java
// Java program to demonstrate isUpperCase() method public class Test { public static void main(String[] args) { System.out.println(Character.isUpperCase('A')); System.out.println(Character.isUpperCase('a')); System.out.println(Character.isUpperCase(65)); }}
true
false
true
5. boolean isLowerCase(char ch): It determines whether the specified char value(ch) is lowercase or not.
Syntax:
boolean isLowerCase(char ch)
Parameters:
ch – a primitive character
Returns: It returns true if ch is lower case, otherwise, returns false.
Example:
Java
// Java program to demonstrate isLowerCase() method public class Test { public static void main(String[] args) { System.out.println(Character.isLowerCase('A')); System.out.println(Character.isLowerCase('a')); System.out.println(Character.isLowerCase(97)); }}
false
true
true
6. char toUpperCase(char ch): It returns the uppercase of the specified char value(ch). If an ASCII value is passed, then the ASCII value of its uppercase will be returned.
Syntax:
char toUpperCase(char ch)
Parameters:
ch – a primitive character
Returns: It returns the uppercase form of the specified char value.
Example:
Java
// Java program to demonstrate toUpperCase() method public class Test { public static void main(String[] args) { System.out.println(Character.toUpperCase('a')); System.out.println(Character.toUpperCase(97)); System.out.println(Character.toUpperCase(48)); }}
A
65
48
7. char toLowerCase(char ch): It returns the lowercase of the specified char value(ch).
Syntax:
char toLowerCase(char ch)
Parameters:
ch – a primitive character
Returns: It returns the lowercase form of the specified char value.
Example:
Java
// Java program to demonstrate toLowerCase() method public class Test { public static void main(String[] args) { System.out.println(Character.toLowerCase('A')); System.out.println(Character.toLowerCase(65)); System.out.println(Character.toLowerCase(48)); }}
a
97
48
8. toString(char ch): It returns a String class object representing the specified character value(ch) i.e a one-character string. Here we cannot pass ASCII value.
Syntax:
String toString(char ch)
Parameters:
ch – a primitive character
Returns: It returns a String object.
Example:
Java
// Java program to demonstrate toString() method public class Test { public static void main(String[] args) { System.out.println(Character.toString('x')); System.out.println(Character.toString('Y')); }}
x
Y
A character preceded by a backslash (\) is an escape sequence and has special meaning to the compiler. The following table shows the Java escape sequences:
When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. For example, if you want to put quotes within quotes you must use the escape sequence, \”, on the interior quotes. To print the sentence
She said "Hello!" to me.
you would write
System.out.println("She said \"Hello!\" to me.");
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nishkarshgandhi
Java-Character
Java-lang package
Java-Library
java-wrapper-class
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
Arrays.sort() in Java with examples
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
|
[
{
"code": null,
"e": 23040,
"s": 23012,
"text": "\n14 Feb, 2022"
},
{
"code": null,
"e": 23345,
"s": 23040,
"text": "Java provides a wrapper class Character in java.lang package. An object of type Character contains a single field, whose type is char. The Character class offers a number of useful class (i.e., static) methods for manipulating characters. You can create a Character object with the Character constructor."
},
{
"code": null,
"e": 23375,
"s": 23345,
"text": "Creating a Character object: "
},
{
"code": null,
"e": 23410,
"s": 23375,
"text": "Character ch = new Character('a');"
},
{
"code": null,
"e": 23587,
"s": 23410,
"text": "The above statement creates a Character object which contains ‘a’ of type char. There is only one constructor in the Character class that expects an argument of char data type."
},
{
"code": null,
"e": 23775,
"s": 23587,
"text": "If we pass a primitive char into a method that expects an object, the compiler automatically converts the char to a Character class object. This feature is called Autoboxing and Unboxing."
},
{
"code": null,
"e": 23887,
"s": 23775,
"text": "Note: The Character class is immutable like String class i.e once it’s object is created, it cannot be changed."
},
{
"code": null,
"e": 23934,
"s": 23887,
"text": "The methods of Character class are as follows:"
},
{
"code": null,
"e": 24252,
"s": 23934,
"text": "1. boolean isLetter(char ch): This method is used to determine whether the specified char value(ch) is a letter or not. The method will return true if it is letter([A-Z],[a-z]), otherwise return false. In place of character, we can also pass ASCII value as an argument as char to int is implicitly typecasted in java."
},
{
"code": null,
"e": 24261,
"s": 24252,
"text": "Syntax: "
},
{
"code": null,
"e": 24287,
"s": 24261,
"text": "boolean isLetter(char ch)"
},
{
"code": null,
"e": 24300,
"s": 24287,
"text": "Parameters: "
},
{
"code": null,
"e": 24327,
"s": 24300,
"text": "ch – a primitive character"
},
{
"code": null,
"e": 24398,
"s": 24327,
"text": "Returns: It returns true if ch is an alphabet, otherwise, return false"
},
{
"code": null,
"e": 24407,
"s": 24398,
"text": "Example:"
},
{
"code": null,
"e": 24412,
"s": 24407,
"text": "Java"
},
{
"code": "// Java program to demonstrate isLetter() method public class Test { public static void main(String[] args) { System.out.println(Character.isLetter('A')); System.out.println(Character.isLetter('0')); }}",
"e": 24641,
"s": 24412,
"text": null
},
{
"code": null,
"e": 24652,
"s": 24641,
"text": "true\nfalse"
},
{
"code": null,
"e": 24821,
"s": 24652,
"text": "2. boolean isDigit(char ch): This method is used to determine whether the specified char value(ch) is a digit or not. Here also we can pass ASCII value as an argument. "
},
{
"code": null,
"e": 24830,
"s": 24821,
"text": "Syntax: "
},
{
"code": null,
"e": 24855,
"s": 24830,
"text": "boolean isDigit(char ch)"
},
{
"code": null,
"e": 24868,
"s": 24855,
"text": "Parameters: "
},
{
"code": null,
"e": 24895,
"s": 24868,
"text": "ch – a primitive character"
},
{
"code": null,
"e": 24962,
"s": 24895,
"text": "Returns: It returns true if ch is a digit, otherwise, return false"
},
{
"code": null,
"e": 24971,
"s": 24962,
"text": "Example:"
},
{
"code": null,
"e": 24976,
"s": 24971,
"text": "Java"
},
{
"code": "// Java program to demonstrate isDigit() method public class Test { public static void main(String[] args) { // print false as A is character System.out.println(Character.isDigit('A')); System.out.println(Character.isDigit('0')); }}",
"e": 25242,
"s": 24976,
"text": null
},
{
"code": null,
"e": 25253,
"s": 25242,
"text": "false\ntrue"
},
{
"code": null,
"e": 25399,
"s": 25253,
"text": "3. boolean isWhitespace(char ch): It determines whether the specified char value(ch) is white space. Whitespace includes space, tab, or newline. "
},
{
"code": null,
"e": 25408,
"s": 25399,
"text": "Syntax: "
},
{
"code": null,
"e": 25438,
"s": 25408,
"text": "boolean isWhitespace(char ch)"
},
{
"code": null,
"e": 25451,
"s": 25438,
"text": "Parameters: "
},
{
"code": null,
"e": 25478,
"s": 25451,
"text": "ch – a primitive character"
},
{
"code": null,
"e": 25550,
"s": 25478,
"text": "Returns: It returns true if ch is whitespace, otherwise, returns false."
},
{
"code": null,
"e": 25559,
"s": 25550,
"text": "Example:"
},
{
"code": null,
"e": 25564,
"s": 25559,
"text": "Java"
},
{
"code": "// Java program to demonstrate isWhitespace() method public class Test { public static void main(String[] args) { System.out.println(Character.isWhitespace('A')); System.out.println(Character.isWhitespace(' ')); System.out.println(Character.isWhitespace('\\n')); System.out.println(Character.isWhitespace('\\t')); // ASCII value of tab System.out.println(Character.isWhitespace(9)); System.out.println(Character.isWhitespace('9')); }}",
"e": 26060,
"s": 25564,
"text": null
},
{
"code": null,
"e": 26092,
"s": 26060,
"text": "false\ntrue\ntrue\ntrue\ntrue\nfalse"
},
{
"code": null,
"e": 26198,
"s": 26092,
"text": "4. boolean isUpperCase(char ch): It determines whether the specified char value(ch) is uppercase or not. "
},
{
"code": null,
"e": 26207,
"s": 26198,
"text": "Syntax: "
},
{
"code": null,
"e": 26236,
"s": 26207,
"text": "boolean isUpperCase(char ch)"
},
{
"code": null,
"e": 26249,
"s": 26236,
"text": "Parameters: "
},
{
"code": null,
"e": 26276,
"s": 26249,
"text": "ch – a primitive character"
},
{
"code": null,
"e": 26348,
"s": 26276,
"text": "Returns: It returns true if ch is upper case, otherwise, returns false."
},
{
"code": null,
"e": 26357,
"s": 26348,
"text": "Example:"
},
{
"code": null,
"e": 26362,
"s": 26357,
"text": "Java"
},
{
"code": "// Java program to demonstrate isUpperCase() method public class Test { public static void main(String[] args) { System.out.println(Character.isUpperCase('A')); System.out.println(Character.isUpperCase('a')); System.out.println(Character.isUpperCase(65)); }}",
"e": 26652,
"s": 26362,
"text": null
},
{
"code": null,
"e": 26668,
"s": 26652,
"text": "true\nfalse\ntrue"
},
{
"code": null,
"e": 26774,
"s": 26668,
"text": "5. boolean isLowerCase(char ch): It determines whether the specified char value(ch) is lowercase or not. "
},
{
"code": null,
"e": 26783,
"s": 26774,
"text": "Syntax: "
},
{
"code": null,
"e": 26812,
"s": 26783,
"text": "boolean isLowerCase(char ch)"
},
{
"code": null,
"e": 26825,
"s": 26812,
"text": "Parameters: "
},
{
"code": null,
"e": 26852,
"s": 26825,
"text": "ch – a primitive character"
},
{
"code": null,
"e": 26924,
"s": 26852,
"text": "Returns: It returns true if ch is lower case, otherwise, returns false."
},
{
"code": null,
"e": 26933,
"s": 26924,
"text": "Example:"
},
{
"code": null,
"e": 26938,
"s": 26933,
"text": "Java"
},
{
"code": "// Java program to demonstrate isLowerCase() method public class Test { public static void main(String[] args) { System.out.println(Character.isLowerCase('A')); System.out.println(Character.isLowerCase('a')); System.out.println(Character.isLowerCase(97)); }}",
"e": 27228,
"s": 26938,
"text": null
},
{
"code": null,
"e": 27244,
"s": 27228,
"text": "false\ntrue\ntrue"
},
{
"code": null,
"e": 27418,
"s": 27244,
"text": "6. char toUpperCase(char ch): It returns the uppercase of the specified char value(ch). If an ASCII value is passed, then the ASCII value of its uppercase will be returned. "
},
{
"code": null,
"e": 27427,
"s": 27418,
"text": "Syntax: "
},
{
"code": null,
"e": 27453,
"s": 27427,
"text": "char toUpperCase(char ch)"
},
{
"code": null,
"e": 27466,
"s": 27453,
"text": "Parameters: "
},
{
"code": null,
"e": 27493,
"s": 27466,
"text": "ch – a primitive character"
},
{
"code": null,
"e": 27561,
"s": 27493,
"text": "Returns: It returns the uppercase form of the specified char value."
},
{
"code": null,
"e": 27570,
"s": 27561,
"text": "Example:"
},
{
"code": null,
"e": 27575,
"s": 27570,
"text": "Java"
},
{
"code": "// Java program to demonstrate toUpperCase() method public class Test { public static void main(String[] args) { System.out.println(Character.toUpperCase('a')); System.out.println(Character.toUpperCase(97)); System.out.println(Character.toUpperCase(48)); }}",
"e": 27864,
"s": 27575,
"text": null
},
{
"code": null,
"e": 27872,
"s": 27864,
"text": "A\n65\n48"
},
{
"code": null,
"e": 27961,
"s": 27872,
"text": "7. char toLowerCase(char ch): It returns the lowercase of the specified char value(ch). "
},
{
"code": null,
"e": 27970,
"s": 27961,
"text": "Syntax: "
},
{
"code": null,
"e": 27996,
"s": 27970,
"text": "char toLowerCase(char ch)"
},
{
"code": null,
"e": 28009,
"s": 27996,
"text": "Parameters: "
},
{
"code": null,
"e": 28036,
"s": 28009,
"text": "ch – a primitive character"
},
{
"code": null,
"e": 28104,
"s": 28036,
"text": "Returns: It returns the lowercase form of the specified char value."
},
{
"code": null,
"e": 28113,
"s": 28104,
"text": "Example:"
},
{
"code": null,
"e": 28118,
"s": 28113,
"text": "Java"
},
{
"code": "// Java program to demonstrate toLowerCase() method public class Test { public static void main(String[] args) { System.out.println(Character.toLowerCase('A')); System.out.println(Character.toLowerCase(65)); System.out.println(Character.toLowerCase(48)); }}",
"e": 28407,
"s": 28118,
"text": null
},
{
"code": null,
"e": 28415,
"s": 28407,
"text": "a\n97\n48"
},
{
"code": null,
"e": 28579,
"s": 28415,
"text": "8. toString(char ch): It returns a String class object representing the specified character value(ch) i.e a one-character string. Here we cannot pass ASCII value. "
},
{
"code": null,
"e": 28588,
"s": 28579,
"text": "Syntax: "
},
{
"code": null,
"e": 28613,
"s": 28588,
"text": "String toString(char ch)"
},
{
"code": null,
"e": 28626,
"s": 28613,
"text": "Parameters: "
},
{
"code": null,
"e": 28653,
"s": 28626,
"text": "ch – a primitive character"
},
{
"code": null,
"e": 28690,
"s": 28653,
"text": "Returns: It returns a String object."
},
{
"code": null,
"e": 28699,
"s": 28690,
"text": "Example:"
},
{
"code": null,
"e": 28704,
"s": 28699,
"text": "Java"
},
{
"code": "// Java program to demonstrate toString() method public class Test { public static void main(String[] args) { System.out.println(Character.toString('x')); System.out.println(Character.toString('Y')); }}",
"e": 28931,
"s": 28704,
"text": null
},
{
"code": null,
"e": 28935,
"s": 28931,
"text": "x\nY"
},
{
"code": null,
"e": 29092,
"s": 28935,
"text": "A character preceded by a backslash (\\) is an escape sequence and has special meaning to the compiler. The following table shows the Java escape sequences: "
},
{
"code": null,
"e": 29330,
"s": 29092,
"text": "When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. For example, if you want to put quotes within quotes you must use the escape sequence, \\”, on the interior quotes. To print the sentence"
},
{
"code": null,
"e": 29355,
"s": 29330,
"text": "She said \"Hello!\" to me."
},
{
"code": null,
"e": 29371,
"s": 29355,
"text": "you would write"
},
{
"code": null,
"e": 29421,
"s": 29371,
"text": "System.out.println(\"She said \\\"Hello!\\\" to me.\");"
},
{
"code": null,
"e": 29844,
"s": 29421,
"text": "This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 29860,
"s": 29844,
"text": "nishkarshgandhi"
},
{
"code": null,
"e": 29875,
"s": 29860,
"text": "Java-Character"
},
{
"code": null,
"e": 29893,
"s": 29875,
"text": "Java-lang package"
},
{
"code": null,
"e": 29906,
"s": 29893,
"text": "Java-Library"
},
{
"code": null,
"e": 29925,
"s": 29906,
"text": "java-wrapper-class"
},
{
"code": null,
"e": 29930,
"s": 29925,
"text": "Java"
},
{
"code": null,
"e": 29935,
"s": 29930,
"text": "Java"
},
{
"code": null,
"e": 30033,
"s": 29935,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30048,
"s": 30033,
"text": "Arrays in Java"
},
{
"code": null,
"e": 30092,
"s": 30048,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 30114,
"s": 30092,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 30139,
"s": 30114,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 30175,
"s": 30139,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 30207,
"s": 30175,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 30258,
"s": 30207,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 30288,
"s": 30258,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 30307,
"s": 30288,
"text": "Interfaces in Java"
}
] |
How to set the unit length of an axis in Matplotlib?
|
To set the unit length of an axis in Matplotlib, we can use xlim or ylim with scale factor of the axes, i.e., of unit length times.
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create x and y data points using numpy.
Create x and y data points using numpy.
Plot the x and y data points using plot() method.
Plot the x and y data points using plot() method.
Get the x and y axes, limit range.
Get the x and y axes, limit range.
Use xlim and ylim methods to set the unit length scale.
Use xlim and ylim methods to set the unit length scale.
To display the figure, use show() method.
To display the figure, use show() method.
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(1, 10, 100)
y = np.log(x)
plt.plot(x, y)
axis_scale = 2
xmin, xmax = plt.xlim()
ymin, ymax = plt.ylim()
plt.xlim(xmin * axis_scale, xmax * axis_scale)
plt.ylim(ymin * axis_scale, ymax * axis_scale)
plt.show()
|
[
{
"code": null,
"e": 1194,
"s": 1062,
"text": "To set the unit length of an axis in Matplotlib, we can use xlim or ylim with scale factor of the axes, i.e., of unit length times."
},
{
"code": null,
"e": 1270,
"s": 1194,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1346,
"s": 1270,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1386,
"s": 1346,
"text": "Create x and y data points using numpy."
},
{
"code": null,
"e": 1426,
"s": 1386,
"text": "Create x and y data points using numpy."
},
{
"code": null,
"e": 1476,
"s": 1426,
"text": "Plot the x and y data points using plot() method."
},
{
"code": null,
"e": 1526,
"s": 1476,
"text": "Plot the x and y data points using plot() method."
},
{
"code": null,
"e": 1561,
"s": 1526,
"text": "Get the x and y axes, limit range."
},
{
"code": null,
"e": 1596,
"s": 1561,
"text": "Get the x and y axes, limit range."
},
{
"code": null,
"e": 1652,
"s": 1596,
"text": "Use xlim and ylim methods to set the unit length scale."
},
{
"code": null,
"e": 1708,
"s": 1652,
"text": "Use xlim and ylim methods to set the unit length scale."
},
{
"code": null,
"e": 1750,
"s": 1708,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1792,
"s": 1750,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 2161,
"s": 1792,
"text": "import matplotlib.pyplot as plt\nimport numpy as np\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nx = np.linspace(1, 10, 100)\ny = np.log(x)\n\nplt.plot(x, y)\naxis_scale = 2\n\nxmin, xmax = plt.xlim()\nymin, ymax = plt.ylim()\n\nplt.xlim(xmin * axis_scale, xmax * axis_scale)\nplt.ylim(ymin * axis_scale, ymax * axis_scale)\n\nplt.show()"
}
] |
C++ Program to Find Minimum Element in an Array using Linear Search
|
This is a C++ Program to find the minimum element of an array using Linear Search approach. The time complexity of this program is O(n).
Begin
Assign the data element to an array.
Assign the value at ‘0’ index to minimum variable.
Compare minimum with other data element sequentially.
Swap values if minimum value is more then the value at that particular index of the array.
print the minimum value.
End
#include<iostream>
using namespace std;
int main() {
int n, i, minimum, a[10] = {1, 6, 7, 10, 12, 14, 12, 16, 20, 26};
char ch;
minimum = a[0];
cout<<"\nThe data element of array:";
for(i = 0; i < 10; i++) {
cout<<" "<<a[i];
if(minimum > a[i])
minimum= a[i];
}
cout<<"\n\nMinimum of the data elements of array using linear search is: "<<minimum;
return 0;
}
The data element of array: 1 6 7 10 12 14 12 16 20 26
Minimum of the data elements of array using linear search is: 1
|
[
{
"code": null,
"e": 1199,
"s": 1062,
"text": "This is a C++ Program to find the minimum element of an array using Linear Search approach. The time complexity of this program is O(n)."
},
{
"code": null,
"e": 1482,
"s": 1199,
"text": "Begin\n Assign the data element to an array.\n Assign the value at ‘0’ index to minimum variable.\n Compare minimum with other data element sequentially.\n Swap values if minimum value is more then the value at that particular index of the array.\n print the minimum value.\nEnd"
},
{
"code": null,
"e": 1885,
"s": 1482,
"text": "#include<iostream>\nusing namespace std;\nint main() {\n int n, i, minimum, a[10] = {1, 6, 7, 10, 12, 14, 12, 16, 20, 26};\n char ch;\n minimum = a[0];\n cout<<\"\\nThe data element of array:\";\n for(i = 0; i < 10; i++) {\n cout<<\" \"<<a[i];\n if(minimum > a[i])\n minimum= a[i];\n }\n cout<<\"\\n\\nMinimum of the data elements of array using linear search is: \"<<minimum;\n return 0;\n}"
},
{
"code": null,
"e": 2003,
"s": 1885,
"text": "The data element of array: 1 6 7 10 12 14 12 16 20 26\nMinimum of the data elements of array using linear search is: 1"
}
] |
NumPy - Statistical Functions
|
NumPy has quite a few useful statistical functions for finding minimum, maximum, percentile standard deviation and variance, etc. from the given elements in the array. The functions are explained as follows −
These functions return the minimum and the maximum from the elements in the given array along the specified axis.
import numpy as np
a = np.array([[3,7,5],[8,4,3],[2,4,9]])
print 'Our array is:'
print a
print '\n'
print 'Applying amin() function:'
print np.amin(a,1)
print '\n'
print 'Applying amin() function again:'
print np.amin(a,0)
print '\n'
print 'Applying amax() function:'
print np.amax(a)
print '\n'
print 'Applying amax() function again:'
print np.amax(a, axis = 0)
It will produce the following output −
Our array is:
[[3 7 5]
[8 4 3]
[2 4 9]]
Applying amin() function:
[3 3 2]
Applying amin() function again:
[2 4 3]
Applying amax() function:
9
Applying amax() function again:
[8 7 9]
The numpy.ptp() function returns the range (maximum-minimum) of values along an axis.
import numpy as np
a = np.array([[3,7,5],[8,4,3],[2,4,9]])
print 'Our array is:'
print a
print '\n'
print 'Applying ptp() function:'
print np.ptp(a)
print '\n'
print 'Applying ptp() function along axis 1:'
print np.ptp(a, axis = 1)
print '\n'
print 'Applying ptp() function along axis 0:'
print np.ptp(a, axis = 0)
It will produce the following output −
Our array is:
[[3 7 5]
[8 4 3]
[2 4 9]]
Applying ptp() function:
7
Applying ptp() function along axis 1:
[4 5 7]
Applying ptp() function along axis 0:
[6 3 6]
Percentile (or a centile) is a measure used in statistics indicating the value below which a given percentage of observations in a group of observations fall. The function numpy.percentile() takes the following arguments.
numpy.percentile(a, q, axis)
Where,
a
Input array
q
The percentile to compute must be between 0-100
axis
The axis along which the percentile is to be calculated
import numpy as np
a = np.array([[30,40,70],[80,20,10],[50,90,60]])
print 'Our array is:'
print a
print '\n'
print 'Applying percentile() function:'
print np.percentile(a,50)
print '\n'
print 'Applying percentile() function along axis 1:'
print np.percentile(a,50, axis = 1)
print '\n'
print 'Applying percentile() function along axis 0:'
print np.percentile(a,50, axis = 0)
It will produce the following output −
Our array is:
[[30 40 70]
[80 20 10]
[50 90 60]]
Applying percentile() function:
50.0
Applying percentile() function along axis 1:
[ 40. 20. 60.]
Applying percentile() function along axis 0:
[ 50. 40. 60.]
Median is defined as the value separating the higher half of a data sample from the lower half. The numpy.median() function is used as shown in the following program.
import numpy as np
a = np.array([[30,65,70],[80,95,10],[50,90,60]])
print 'Our array is:'
print a
print '\n'
print 'Applying median() function:'
print np.median(a)
print '\n'
print 'Applying median() function along axis 0:'
print np.median(a, axis = 0)
print '\n'
print 'Applying median() function along axis 1:'
print np.median(a, axis = 1)
It will produce the following output −
Our array is:
[[30 65 70]
[80 95 10]
[50 90 60]]
Applying median() function:
65.0
Applying median() function along axis 0:
[ 50. 90. 60.]
Applying median() function along axis 1:
[ 65. 80. 60.]
Arithmetic mean is the sum of elements along an axis divided by the number of elements. The numpy.mean() function returns the arithmetic mean of elements in the array. If the axis is mentioned, it is calculated along it.
import numpy as np
a = np.array([[1,2,3],[3,4,5],[4,5,6]])
print 'Our array is:'
print a
print '\n'
print 'Applying mean() function:'
print np.mean(a)
print '\n'
print 'Applying mean() function along axis 0:'
print np.mean(a, axis = 0)
print '\n'
print 'Applying mean() function along axis 1:'
print np.mean(a, axis = 1)
It will produce the following output −
Our array is:
[[1 2 3]
[3 4 5]
[4 5 6]]
Applying mean() function:
3.66666666667
Applying mean() function along axis 0:
[ 2.66666667 3.66666667 4.66666667]
Applying mean() function along axis 1:
[ 2. 4. 5.]
Weighted average is an average resulting from the multiplication of each component by a factor reflecting its importance. The numpy.average() function computes the weighted average of elements in an array according to their respective weight given in another array. The function can have an axis parameter. If the axis is not specified, the array is flattened.
Considering an array [1,2,3,4] and corresponding weights [4,3,2,1], the weighted average is calculated by adding the product of the corresponding elements and dividing the sum by the sum of weights.
Weighted average = (1*4+2*3+3*2+4*1)/(4+3+2+1)
import numpy as np
a = np.array([1,2,3,4])
print 'Our array is:'
print a
print '\n'
print 'Applying average() function:'
print np.average(a)
print '\n'
# this is same as mean when weight is not specified
wts = np.array([4,3,2,1])
print 'Applying average() function again:'
print np.average(a,weights = wts)
print '\n'
# Returns the sum of weights, if the returned parameter is set to True.
print 'Sum of weights'
print np.average([1,2,3, 4],weights = [4,3,2,1], returned = True)
It will produce the following output −
Our array is:
[1 2 3 4]
Applying average() function:
2.5
Applying average() function again:
2.0
Sum of weights
(2.0, 10.0)
In a multi-dimensional array, the axis for computation can be specified.
import numpy as np
a = np.arange(6).reshape(3,2)
print 'Our array is:'
print a
print '\n'
print 'Modified array:'
wt = np.array([3,5])
print np.average(a, axis = 1, weights = wt)
print '\n'
print 'Modified array:'
print np.average(a, axis = 1, weights = wt, returned = True)
It will produce the following output −
Our array is:
[[0 1]
[2 3]
[4 5]]
Modified array:
[ 0.625 2.625 4.625]
Modified array:
(array([ 0.625, 2.625, 4.625]), array([ 8., 8., 8.]))
Standard deviation is the square root of the average of squared deviations from mean. The formula for standard deviation is as follows −
std = sqrt(mean(abs(x - x.mean())**2))
If the array is [1, 2, 3, 4], then its mean is 2.5. Hence the squared deviations are [2.25, 0.25, 0.25, 2.25] and the square root of its mean divided by 4, i.e., sqrt (5/4) is 1.1180339887498949.
import numpy as np
print np.std([1,2,3,4])
It will produce the following output −
1.1180339887498949
Variance is the average of squared deviations, i.e., mean(abs(x - x.mean())**2). In other words, the standard deviation is the square root of variance.
import numpy as np
print np.var([1,2,3,4])
It will produce the following output −
1.25
63 Lectures
6 hours
Abhilash Nelson
19 Lectures
8 hours
DATAhill Solutions Srinivas Reddy
12 Lectures
3 hours
DATAhill Solutions Srinivas Reddy
10 Lectures
2.5 hours
Akbar Khan
20 Lectures
2 hours
Pruthviraja L
63 Lectures
6 hours
Anmol
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2452,
"s": 2243,
"text": "NumPy has quite a few useful statistical functions for finding minimum, maximum, percentile standard deviation and variance, etc. from the given elements in the array. The functions are explained as follows −"
},
{
"code": null,
"e": 2566,
"s": 2452,
"text": "These functions return the minimum and the maximum from the elements in the given array along the specified axis."
},
{
"code": null,
"e": 2954,
"s": 2566,
"text": "import numpy as np \na = np.array([[3,7,5],[8,4,3],[2,4,9]]) \n\nprint 'Our array is:' \nprint a \nprint '\\n' \n\nprint 'Applying amin() function:' \nprint np.amin(a,1) \nprint '\\n' \n\nprint 'Applying amin() function again:' \nprint np.amin(a,0) \nprint '\\n' \n\nprint 'Applying amax() function:' \nprint np.amax(a) \nprint '\\n' \n\nprint 'Applying amax() function again:' \nprint np.amax(a, axis = 0)"
},
{
"code": null,
"e": 2993,
"s": 2954,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 3180,
"s": 2993,
"text": "Our array is:\n[[3 7 5]\n[8 4 3]\n[2 4 9]]\n\nApplying amin() function:\n[3 3 2]\n\nApplying amin() function again:\n[2 4 3]\n\nApplying amax() function:\n9\n\nApplying amax() function again:\n[8 7 9]\n"
},
{
"code": null,
"e": 3266,
"s": 3180,
"text": "The numpy.ptp() function returns the range (maximum-minimum) of values along an axis."
},
{
"code": null,
"e": 3601,
"s": 3266,
"text": "import numpy as np \na = np.array([[3,7,5],[8,4,3],[2,4,9]]) \n\nprint 'Our array is:' \nprint a \nprint '\\n' \n\nprint 'Applying ptp() function:' \nprint np.ptp(a) \nprint '\\n' \n\nprint 'Applying ptp() function along axis 1:' \nprint np.ptp(a, axis = 1) \nprint '\\n' \n\nprint 'Applying ptp() function along axis 0:'\nprint np.ptp(a, axis = 0) "
},
{
"code": null,
"e": 3640,
"s": 3601,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 3803,
"s": 3640,
"text": "Our array is:\n[[3 7 5]\n[8 4 3]\n[2 4 9]]\n\nApplying ptp() function:\n7\n\nApplying ptp() function along axis 1:\n[4 5 7]\n\nApplying ptp() function along axis 0:\n[6 3 6]\n"
},
{
"code": null,
"e": 4025,
"s": 3803,
"text": "Percentile (or a centile) is a measure used in statistics indicating the value below which a given percentage of observations in a group of observations fall. The function numpy.percentile() takes the following arguments."
},
{
"code": null,
"e": 4055,
"s": 4025,
"text": "numpy.percentile(a, q, axis)\n"
},
{
"code": null,
"e": 4062,
"s": 4055,
"text": "Where,"
},
{
"code": null,
"e": 4064,
"s": 4062,
"text": "a"
},
{
"code": null,
"e": 4076,
"s": 4064,
"text": "Input array"
},
{
"code": null,
"e": 4078,
"s": 4076,
"text": "q"
},
{
"code": null,
"e": 4126,
"s": 4078,
"text": "The percentile to compute must be between 0-100"
},
{
"code": null,
"e": 4131,
"s": 4126,
"text": "axis"
},
{
"code": null,
"e": 4187,
"s": 4131,
"text": "The axis along which the percentile is to be calculated"
},
{
"code": null,
"e": 4581,
"s": 4187,
"text": "import numpy as np \na = np.array([[30,40,70],[80,20,10],[50,90,60]]) \n\nprint 'Our array is:' \nprint a \nprint '\\n' \n\nprint 'Applying percentile() function:' \nprint np.percentile(a,50) \nprint '\\n' \n\nprint 'Applying percentile() function along axis 1:' \nprint np.percentile(a,50, axis = 1) \nprint '\\n' \n\nprint 'Applying percentile() function along axis 0:' \nprint np.percentile(a,50, axis = 0)"
},
{
"code": null,
"e": 4620,
"s": 4581,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 4832,
"s": 4620,
"text": "Our array is:\n[[30 40 70]\n [80 20 10]\n [50 90 60]]\n\nApplying percentile() function:\n50.0\n\nApplying percentile() function along axis 1:\n[ 40. 20. 60.]\n\nApplying percentile() function along axis 0:\n[ 50. 40. 60.]\n"
},
{
"code": null,
"e": 4999,
"s": 4832,
"text": "Median is defined as the value separating the higher half of a data sample from the lower half. The numpy.median() function is used as shown in the following program."
},
{
"code": null,
"e": 5361,
"s": 4999,
"text": "import numpy as np \na = np.array([[30,65,70],[80,95,10],[50,90,60]]) \n\nprint 'Our array is:' \nprint a \nprint '\\n' \n\nprint 'Applying median() function:' \nprint np.median(a) \nprint '\\n' \n\nprint 'Applying median() function along axis 0:' \nprint np.median(a, axis = 0) \nprint '\\n' \n \nprint 'Applying median() function along axis 1:' \nprint np.median(a, axis = 1)"
},
{
"code": null,
"e": 5400,
"s": 5361,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 5600,
"s": 5400,
"text": "Our array is:\n[[30 65 70]\n [80 95 10]\n [50 90 60]]\n\nApplying median() function:\n65.0\n\nApplying median() function along axis 0:\n[ 50. 90. 60.]\n\nApplying median() function along axis 1:\n[ 65. 80. 60.]\n"
},
{
"code": null,
"e": 5821,
"s": 5600,
"text": "Arithmetic mean is the sum of elements along an axis divided by the number of elements. The numpy.mean() function returns the arithmetic mean of elements in the array. If the axis is mentioned, it is calculated along it."
},
{
"code": null,
"e": 6161,
"s": 5821,
"text": "import numpy as np \na = np.array([[1,2,3],[3,4,5],[4,5,6]]) \n\nprint 'Our array is:' \nprint a \nprint '\\n' \n\nprint 'Applying mean() function:' \nprint np.mean(a) \nprint '\\n' \n\nprint 'Applying mean() function along axis 0:' \nprint np.mean(a, axis = 0) \nprint '\\n' \n\nprint 'Applying mean() function along axis 1:' \nprint np.mean(a, axis = 1)"
},
{
"code": null,
"e": 6200,
"s": 6161,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 6412,
"s": 6200,
"text": "Our array is:\n[[1 2 3]\n [3 4 5]\n [4 5 6]]\n\nApplying mean() function:\n3.66666666667\n\nApplying mean() function along axis 0:\n[ 2.66666667 3.66666667 4.66666667]\n\nApplying mean() function along axis 1:\n[ 2. 4. 5.]\n"
},
{
"code": null,
"e": 6773,
"s": 6412,
"text": "Weighted average is an average resulting from the multiplication of each component by a factor reflecting its importance. The numpy.average() function computes the weighted average of elements in an array according to their respective weight given in another array. The function can have an axis parameter. If the axis is not specified, the array is flattened."
},
{
"code": null,
"e": 6972,
"s": 6773,
"text": "Considering an array [1,2,3,4] and corresponding weights [4,3,2,1], the weighted average is calculated by adding the product of the corresponding elements and dividing the sum by the sum of weights."
},
{
"code": null,
"e": 7019,
"s": 6972,
"text": "Weighted average = (1*4+2*3+3*2+4*1)/(4+3+2+1)"
},
{
"code": null,
"e": 7521,
"s": 7019,
"text": "import numpy as np \na = np.array([1,2,3,4]) \n\nprint 'Our array is:' \nprint a \nprint '\\n' \n\nprint 'Applying average() function:' \nprint np.average(a) \nprint '\\n' \n\n# this is same as mean when weight is not specified \nwts = np.array([4,3,2,1]) \n\nprint 'Applying average() function again:' \nprint np.average(a,weights = wts) \nprint '\\n' \n\n# Returns the sum of weights, if the returned parameter is set to True. \nprint 'Sum of weights' \nprint np.average([1,2,3, 4],weights = [4,3,2,1], returned = True)"
},
{
"code": null,
"e": 7560,
"s": 7521,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 7687,
"s": 7560,
"text": "Our array is:\n[1 2 3 4]\n\nApplying average() function:\n2.5\n\nApplying average() function again:\n2.0\n\nSum of weights\n(2.0, 10.0)\n"
},
{
"code": null,
"e": 7760,
"s": 7687,
"text": "In a multi-dimensional array, the axis for computation can be specified."
},
{
"code": null,
"e": 8050,
"s": 7760,
"text": "import numpy as np \na = np.arange(6).reshape(3,2) \n\nprint 'Our array is:' \nprint a \nprint '\\n' \n\nprint 'Modified array:' \nwt = np.array([3,5]) \nprint np.average(a, axis = 1, weights = wt) \nprint '\\n' \n\nprint 'Modified array:' \nprint np.average(a, axis = 1, weights = wt, returned = True)"
},
{
"code": null,
"e": 8089,
"s": 8050,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 8235,
"s": 8089,
"text": "Our array is:\n[[0 1]\n [2 3]\n [4 5]]\n\nModified array:\n[ 0.625 2.625 4.625]\n\nModified array:\n(array([ 0.625, 2.625, 4.625]), array([ 8., 8., 8.]))\n"
},
{
"code": null,
"e": 8372,
"s": 8235,
"text": "Standard deviation is the square root of the average of squared deviations from mean. The formula for standard deviation is as follows −"
},
{
"code": null,
"e": 8412,
"s": 8372,
"text": "std = sqrt(mean(abs(x - x.mean())**2))\n"
},
{
"code": null,
"e": 8608,
"s": 8412,
"text": "If the array is [1, 2, 3, 4], then its mean is 2.5. Hence the squared deviations are [2.25, 0.25, 0.25, 2.25] and the square root of its mean divided by 4, i.e., sqrt (5/4) is 1.1180339887498949."
},
{
"code": null,
"e": 8652,
"s": 8608,
"text": "import numpy as np \nprint np.std([1,2,3,4])"
},
{
"code": null,
"e": 8691,
"s": 8652,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 8712,
"s": 8691,
"text": "1.1180339887498949 \n"
},
{
"code": null,
"e": 8864,
"s": 8712,
"text": "Variance is the average of squared deviations, i.e., mean(abs(x - x.mean())**2). In other words, the standard deviation is the square root of variance."
},
{
"code": null,
"e": 8908,
"s": 8864,
"text": "import numpy as np \nprint np.var([1,2,3,4])"
},
{
"code": null,
"e": 8947,
"s": 8908,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 8953,
"s": 8947,
"text": "1.25\n"
},
{
"code": null,
"e": 8986,
"s": 8953,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 9003,
"s": 8986,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 9036,
"s": 9003,
"text": "\n 19 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 9071,
"s": 9036,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 9104,
"s": 9071,
"text": "\n 12 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 9139,
"s": 9104,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 9174,
"s": 9139,
"text": "\n 10 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 9186,
"s": 9174,
"text": " Akbar Khan"
},
{
"code": null,
"e": 9219,
"s": 9186,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 9234,
"s": 9219,
"text": " Pruthviraja L"
},
{
"code": null,
"e": 9267,
"s": 9234,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 9274,
"s": 9267,
"text": " Anmol"
},
{
"code": null,
"e": 9281,
"s": 9274,
"text": " Print"
},
{
"code": null,
"e": 9292,
"s": 9281,
"text": " Add Notes"
}
] |
How to group data with Angular filter ?
|
29 Jul, 2020
The task is to show how to group-data with an Angular-filter.
Steps involved:
1. You can install angular-filter using these four different methods:
Clone & build https://github.com/a8m/angular-filter git repository
Via Bower: by running $ bower install angular-filter from your terminal
Via npm: by running $ npm install angular-filter from your terminal.
Installing via npm
Via cdnjs: add the following script-src to your application.
2. Include angular-filter.js (or angular-filter.min.js) in your index.html, after including Angular itself as shown in the below example.
3. Add ‘angular.filter’ to your main module’s list of dependencies.
Example: In this example, we will group dogs by their breeds using angular-filter.
HTML
<!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.7/angular-filter.js"> </script> <link rel="stylesheet" href= "https://www.w3schools.com/w3css/4/w3.css"> <meta charset="utf-8"></head> <body ng-app="myApp" ng-controller="myCtrl"> <p class="w3-jumbo w3-text-green pad" align="center" style="margin: 0 0 0 0"> GeeksforGeeks </p> <p class="w3-large w3-text-green pad" align="center"> A computer science portal for geeks </p> <ul> <li ng-repeat= "(key, value) in dogs | groupBy:'breed'"> Breed: {{ key }} <ol> <li ng-repeat="dog in value"> Dog name: {{ dog.name }} </li> </ol> </li> </ul> <script type="text/javascript"> //(3) angular.module('myApp', ['angular.filter']) .controller('myCtrl', function ($scope) { $scope.dogs = [ { name: 'Alex', breed: 'German Shepherd' }, { name: 'Rocky', breed: 'Bulldog' }, { name: 'John', breed: 'Beagle' }, { name: 'Paula', breed: 'Bulldog' }, { name: 'Bobby', breed: 'German Shepherd' } ]; }); </script></body> </html>
Output:
AngularJS-Misc
CSS-Misc
HTML-Misc
AngularJS
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Jul, 2020"
},
{
"code": null,
"e": 90,
"s": 28,
"text": "The task is to show how to group-data with an Angular-filter."
},
{
"code": null,
"e": 106,
"s": 90,
"text": "Steps involved:"
},
{
"code": null,
"e": 176,
"s": 106,
"text": "1. You can install angular-filter using these four different methods:"
},
{
"code": null,
"e": 243,
"s": 176,
"text": "Clone & build https://github.com/a8m/angular-filter git repository"
},
{
"code": null,
"e": 315,
"s": 243,
"text": "Via Bower: by running $ bower install angular-filter from your terminal"
},
{
"code": null,
"e": 384,
"s": 315,
"text": "Via npm: by running $ npm install angular-filter from your terminal."
},
{
"code": null,
"e": 404,
"s": 384,
"text": "Installing via npm "
},
{
"code": null,
"e": 465,
"s": 404,
"text": "Via cdnjs: add the following script-src to your application."
},
{
"code": null,
"e": 603,
"s": 465,
"text": "2. Include angular-filter.js (or angular-filter.min.js) in your index.html, after including Angular itself as shown in the below example."
},
{
"code": null,
"e": 671,
"s": 603,
"text": "3. Add ‘angular.filter’ to your main module’s list of dependencies."
},
{
"code": null,
"e": 754,
"s": 671,
"text": "Example: In this example, we will group dogs by their breeds using angular-filter."
},
{
"code": null,
"e": 759,
"s": 754,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.7/angular-filter.js\"> </script> <link rel=\"stylesheet\" href= \"https://www.w3schools.com/w3css/4/w3.css\"> <meta charset=\"utf-8\"></head> <body ng-app=\"myApp\" ng-controller=\"myCtrl\"> <p class=\"w3-jumbo w3-text-green pad\" align=\"center\" style=\"margin: 0 0 0 0\"> GeeksforGeeks </p> <p class=\"w3-large w3-text-green pad\" align=\"center\"> A computer science portal for geeks </p> <ul> <li ng-repeat= \"(key, value) in dogs | groupBy:'breed'\"> Breed: {{ key }} <ol> <li ng-repeat=\"dog in value\"> Dog name: {{ dog.name }} </li> </ol> </li> </ul> <script type=\"text/javascript\"> //(3) angular.module('myApp', ['angular.filter']) .controller('myCtrl', function ($scope) { $scope.dogs = [ { name: 'Alex', breed: 'German Shepherd' }, { name: 'Rocky', breed: 'Bulldog' }, { name: 'John', breed: 'Beagle' }, { name: 'Paula', breed: 'Bulldog' }, { name: 'Bobby', breed: 'German Shepherd' } ]; }); </script></body> </html>",
"e": 2197,
"s": 759,
"text": null
},
{
"code": null,
"e": 2206,
"s": 2197,
"text": "Output: "
},
{
"code": null,
"e": 2221,
"s": 2206,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 2230,
"s": 2221,
"text": "CSS-Misc"
},
{
"code": null,
"e": 2240,
"s": 2230,
"text": "HTML-Misc"
},
{
"code": null,
"e": 2250,
"s": 2240,
"text": "AngularJS"
},
{
"code": null,
"e": 2254,
"s": 2250,
"text": "CSS"
},
{
"code": null,
"e": 2259,
"s": 2254,
"text": "HTML"
},
{
"code": null,
"e": 2276,
"s": 2259,
"text": "Web Technologies"
},
{
"code": null,
"e": 2303,
"s": 2276,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2308,
"s": 2303,
"text": "HTML"
}
] |
Python | Check for None values in given dictionary
|
11 Jul, 2019
Many times, while working with dictionaries, we wish to check for a non-null dictionary, i.e check for None values in given dictionary. This finds application in Machine Learning in which we have to feed data with no none values. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using all() + not operator + values()
The combination of above functions can be used to perform this particular task. In this, we check for all the values using all function extracted using values function. The not operator is used to inverse the result to check for any of None value.
# Python3 code to demonstrate working of# Check for Non None Dictionary values# Using all() + not operator + values() # initializing dictionarytest_dict = {'Gfg' : 1, 'for' : 2, 'CS' : None} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Using all() + not operator + values()# Check for Non None Dictionary valuesres = not all(test_dict.values()) # printing result print("Does Dictionary contain None value ? " + str(res))
The original dictionary is : {'Gfg': 1, 'CS': None, 'for': 2}
Does Dictionary contain None value ? True
Method #2 : Using in operator + values()
This task can also be performed using the in operator and values function. We just check for None in all the values extracted using the values function and check for existence using the in operator.
# Python3 code to demonstrate working of# Check for Non None Dictionary values# Using in operator + values() # initializing dictionarytest_dict = {'Gfg' : 1, 'for' : 2, 'CS' : None} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Using in operator + values()# Check for Non None Dictionary valuesres = None in test_dict.values() # printing result print("Does Dictionary contain None value ? " + str(res))
The original dictionary is : {'Gfg': 1, 'CS': None, 'for': 2}
Does Dictionary contain None value ? True
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Jul, 2019"
},
{
"code": null,
"e": 322,
"s": 28,
"text": "Many times, while working with dictionaries, we wish to check for a non-null dictionary, i.e check for None values in given dictionary. This finds application in Machine Learning in which we have to feed data with no none values. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 372,
"s": 322,
"text": "Method #1 : Using all() + not operator + values()"
},
{
"code": null,
"e": 620,
"s": 372,
"text": "The combination of above functions can be used to perform this particular task. In this, we check for all the values using all function extracted using values function. The not operator is used to inverse the result to check for any of None value."
},
{
"code": "# Python3 code to demonstrate working of# Check for Non None Dictionary values# Using all() + not operator + values() # initializing dictionarytest_dict = {'Gfg' : 1, 'for' : 2, 'CS' : None} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Using all() + not operator + values()# Check for Non None Dictionary valuesres = not all(test_dict.values()) # printing result print(\"Does Dictionary contain None value ? \" + str(res))",
"e": 1088,
"s": 620,
"text": null
},
{
"code": null,
"e": 1193,
"s": 1088,
"text": "The original dictionary is : {'Gfg': 1, 'CS': None, 'for': 2}\nDoes Dictionary contain None value ? True\n"
},
{
"code": null,
"e": 1236,
"s": 1195,
"text": "Method #2 : Using in operator + values()"
},
{
"code": null,
"e": 1435,
"s": 1236,
"text": "This task can also be performed using the in operator and values function. We just check for None in all the values extracted using the values function and check for existence using the in operator."
},
{
"code": "# Python3 code to demonstrate working of# Check for Non None Dictionary values# Using in operator + values() # initializing dictionarytest_dict = {'Gfg' : 1, 'for' : 2, 'CS' : None} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Using in operator + values()# Check for Non None Dictionary valuesres = None in test_dict.values() # printing result print(\"Does Dictionary contain None value ? \" + str(res))",
"e": 1884,
"s": 1435,
"text": null
},
{
"code": null,
"e": 1989,
"s": 1884,
"text": "The original dictionary is : {'Gfg': 1, 'CS': None, 'for': 2}\nDoes Dictionary contain None value ? True\n"
},
{
"code": null,
"e": 2016,
"s": 1989,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 2023,
"s": 2016,
"text": "Python"
},
{
"code": null,
"e": 2039,
"s": 2023,
"text": "Python Programs"
},
{
"code": null,
"e": 2137,
"s": 2039,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2155,
"s": 2137,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2197,
"s": 2155,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2219,
"s": 2197,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2254,
"s": 2219,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2280,
"s": 2254,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2323,
"s": 2280,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2345,
"s": 2323,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2384,
"s": 2345,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2422,
"s": 2384,
"text": "Python | Convert a list to dictionary"
}
] |
Python time asctime() Method
|
Pythom time method asctime() converts a tuple or struct_time representing a time as returned by gmtime() or localtime() to a 24-character string of the following form: 'Tue Feb 17 23:21:05 2009'.
Following is the syntax for asctime() method −
time.asctime([t]))
t − This is a tuple of 9 elements or struct_time representing a time as returned by gmtime() or localtime() function.
t − This is a tuple of 9 elements or struct_time representing a time as returned by gmtime() or localtime() function.
This method returns 24-character string of the following form: 'Tue Feb 17 23:21:05 2009'.
The following example shows the usage of asctime() method.
#!/usr/bin/python
import time
t = time.localtime()
print "time.asctime(t): %s " % time.asctime(t)
When we run above program, it produces following result −
time.asctime(t): Tue Feb 17 09:42:58 2009
|
[
{
"code": null,
"e": 2574,
"s": 2378,
"text": "Pythom time method asctime() converts a tuple or struct_time representing a time as returned by gmtime() or localtime() to a 24-character string of the following form: 'Tue Feb 17 23:21:05 2009'."
},
{
"code": null,
"e": 2621,
"s": 2574,
"text": "Following is the syntax for asctime() method −"
},
{
"code": null,
"e": 2641,
"s": 2621,
"text": "time.asctime([t]))\n"
},
{
"code": null,
"e": 2759,
"s": 2641,
"text": "t − This is a tuple of 9 elements or struct_time representing a time as returned by gmtime() or localtime() function."
},
{
"code": null,
"e": 2877,
"s": 2759,
"text": "t − This is a tuple of 9 elements or struct_time representing a time as returned by gmtime() or localtime() function."
},
{
"code": null,
"e": 2968,
"s": 2877,
"text": "This method returns 24-character string of the following form: 'Tue Feb 17 23:21:05 2009'."
},
{
"code": null,
"e": 3027,
"s": 2968,
"text": "The following example shows the usage of asctime() method."
},
{
"code": null,
"e": 3126,
"s": 3027,
"text": "#!/usr/bin/python\nimport time\n\nt = time.localtime()\nprint \"time.asctime(t): %s \" % time.asctime(t)"
},
{
"code": null,
"e": 3184,
"s": 3126,
"text": "When we run above program, it produces following result −"
}
] |
Python | Ways to remove n characters from start of given string
|
07 Jun, 2019
Given a string and a number ‘n’, the task is to remove a string of length ‘n’ from the start of the string. Let’s a few methods to solve the given task.Method #1: Using Naive Method
# Python3 code to demonstrate # how to remove 'n' characters from starting# of a string # Initialising stringini_string1 = 'garg_akshat' # Initialising number of characters to be removedn = 5 # Printing initial stringprint ("Initial String", ini_string1) # Removing n characters from string using # Naive methodres = ''for i in range(0, len(ini_string1)): if i>= n: res = res + ini_string1[i] # Printing resultant stringprint ("Resultant String", res)
Initial String garg_akshat
Resultant String akshat
Method #2: Using replace()
# Python3 code to demonstrate # how to remove 'n' characters from starting# of a string # Initialising stringini_string1 = 'garg_akshat' # Initialising number of characters to be removedn = 5 # Printing initial stringprint ("Initial String", ini_string1) # Removing n characters from string using # replace() functionres = ini_string1.replace(ini_string1[:5], '', 1) # Printing resultant stringprint ("Resultant String", res)
Initial String garg_akshat
Resultant String akshat
Method #3: String slicing
# Python3 code to demonstrate # how to remove 'n' characters from starting# of a string # Initialising stringini_string1 = 'gargakshat123' # Initialising number of characters to be removedn = 5 # Printing initial stringprint ("Initial String", ini_string1) # Removing n characters from a string# This argument count length from zero # So length to be stripped is passed n-1res = ini_string1[4:] # Printing resultant stringprint ("Resultant String", res)
Initial String gargakshat123
Resultant String akshat123
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Jun, 2019"
},
{
"code": null,
"e": 210,
"s": 28,
"text": "Given a string and a number ‘n’, the task is to remove a string of length ‘n’ from the start of the string. Let’s a few methods to solve the given task.Method #1: Using Naive Method"
},
{
"code": "# Python3 code to demonstrate # how to remove 'n' characters from starting# of a string # Initialising stringini_string1 = 'garg_akshat' # Initialising number of characters to be removedn = 5 # Printing initial stringprint (\"Initial String\", ini_string1) # Removing n characters from string using # Naive methodres = ''for i in range(0, len(ini_string1)): if i>= n: res = res + ini_string1[i] # Printing resultant stringprint (\"Resultant String\", res)",
"e": 685,
"s": 210,
"text": null
},
{
"code": null,
"e": 737,
"s": 685,
"text": "Initial String garg_akshat\nResultant String akshat\n"
},
{
"code": null,
"e": 765,
"s": 737,
"text": " Method #2: Using replace()"
},
{
"code": "# Python3 code to demonstrate # how to remove 'n' characters from starting# of a string # Initialising stringini_string1 = 'garg_akshat' # Initialising number of characters to be removedn = 5 # Printing initial stringprint (\"Initial String\", ini_string1) # Removing n characters from string using # replace() functionres = ini_string1.replace(ini_string1[:5], '', 1) # Printing resultant stringprint (\"Resultant String\", res)",
"e": 1204,
"s": 765,
"text": null
},
{
"code": null,
"e": 1256,
"s": 1204,
"text": "Initial String garg_akshat\nResultant String akshat\n"
},
{
"code": null,
"e": 1283,
"s": 1256,
"text": " Method #3: String slicing"
},
{
"code": "# Python3 code to demonstrate # how to remove 'n' characters from starting# of a string # Initialising stringini_string1 = 'gargakshat123' # Initialising number of characters to be removedn = 5 # Printing initial stringprint (\"Initial String\", ini_string1) # Removing n characters from a string# This argument count length from zero # So length to be stripped is passed n-1res = ini_string1[4:] # Printing resultant stringprint (\"Resultant String\", res) ",
"e": 1755,
"s": 1283,
"text": null
},
{
"code": null,
"e": 1812,
"s": 1755,
"text": "Initial String gargakshat123\nResultant String akshat123\n"
},
{
"code": null,
"e": 1835,
"s": 1812,
"text": "Python string-programs"
},
{
"code": null,
"e": 1842,
"s": 1835,
"text": "Python"
},
{
"code": null,
"e": 1858,
"s": 1842,
"text": "Python Programs"
}
] |
What is contextual selector in CSS ?
|
21 Nov, 2021
In this article, we will learn about the contextual selector in CSS & understand the declaration syntax with the help of code examples.A contextual selector is defined as a selector which considers the context where the style is to be applied. In simple words, the specified style is applied to an element only if the element is in the specified context. Context can be defined as a parent/child relationship or ancestor/descendant relationship between different parts of the document. A contextual selector is made up of two or more simple selectors separated by white space. Class, any type, ID selector is considered as a simple selector.
Descendants: It matches all elements which are contained within another element.
Syntax:
div {color: red}
p {color: red;}
For any specific HTML element, we can apply the general CSS property that is required to style that element. The below code example will illustrate the approach for applying the contextual selector.
Example: In this, there is a parent div tag and its two-child p tags. The parent <p> tag and parent <div> tag turns the elements into red as the program executes.
HTML
<!DOCTYPE html><html> <head> <title>Contextual Selectors</title> <style> div { color: red; } p { color: red; } </style></head> <body> <div> <p>Geeks For Geeks</p> <p>A Computer Science portal for geeks.</p> </div> <p>What are Contextual Selectors in CSS?</p> </body> </html>
Output:
But suppose you have to turn only that paragraph into the green which is under div and not the other one outside div. You want both <p> and <div> tags to stay red for the document as a whole, but for elements inside the <div> tag, you need to turn the <p> tag into green. How can you do this?
Well, here comes the real importance of contextual selector.
Syntax:
div p{color: green;}
Example 2: In this example, any <p> tag that is inside <div> tag, will make it green (and not red like the previous syntax specified). Here, the <p> tag will be made green only in the context of <div> tag. It will be red in all other contexts.
HTML
<!DOCTYPE html><html> <head> <title>Contextual Selectors</title> <style> div p { color: green; } </style></head> <body> <div> <p>Geeks For Geeks</p> <p>A Computer Science portal for geeks.</p> </div> <p>What are Contextual Selectors in CSS?</p> </body> </html>
Output:
From the above examples, we have seen that how a contextual selector is applied to style an element only if the element is in the specified context.
Hello Geeks! Don’t stop learning now. Get hold of all the important competitive programming concepts with the Web Design for Beginners | HTML course.
sumitgumber28
CSS-Questions
CSS-Selectors
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n21 Nov, 2021"
},
{
"code": null,
"e": 695,
"s": 53,
"text": "In this article, we will learn about the contextual selector in CSS & understand the declaration syntax with the help of code examples.A contextual selector is defined as a selector which considers the context where the style is to be applied. In simple words, the specified style is applied to an element only if the element is in the specified context. Context can be defined as a parent/child relationship or ancestor/descendant relationship between different parts of the document. A contextual selector is made up of two or more simple selectors separated by white space. Class, any type, ID selector is considered as a simple selector."
},
{
"code": null,
"e": 776,
"s": 695,
"text": "Descendants: It matches all elements which are contained within another element."
},
{
"code": null,
"e": 784,
"s": 776,
"text": "Syntax:"
},
{
"code": null,
"e": 817,
"s": 784,
"text": "div {color: red}\np {color: red;}"
},
{
"code": null,
"e": 1018,
"s": 817,
"text": "For any specific HTML element, we can apply the general CSS property that is required to style that element. The below code example will illustrate the approach for applying the contextual selector. "
},
{
"code": null,
"e": 1181,
"s": 1018,
"text": "Example: In this, there is a parent div tag and its two-child p tags. The parent <p> tag and parent <div> tag turns the elements into red as the program executes."
},
{
"code": null,
"e": 1186,
"s": 1181,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Contextual Selectors</title> <style> div { color: red; } p { color: red; } </style></head> <body> <div> <p>Geeks For Geeks</p> <p>A Computer Science portal for geeks.</p> </div> <p>What are Contextual Selectors in CSS?</p> </body> </html>",
"e": 1555,
"s": 1186,
"text": null
},
{
"code": null,
"e": 1563,
"s": 1555,
"text": "Output:"
},
{
"code": null,
"e": 1856,
"s": 1563,
"text": "But suppose you have to turn only that paragraph into the green which is under div and not the other one outside div. You want both <p> and <div> tags to stay red for the document as a whole, but for elements inside the <div> tag, you need to turn the <p> tag into green. How can you do this?"
},
{
"code": null,
"e": 1918,
"s": 1856,
"text": "Well, here comes the real importance of contextual selector. "
},
{
"code": null,
"e": 1926,
"s": 1918,
"text": "Syntax:"
},
{
"code": null,
"e": 1947,
"s": 1926,
"text": "div p{color: green;}"
},
{
"code": null,
"e": 2193,
"s": 1947,
"text": "Example 2: In this example, any <p> tag that is inside <div> tag, will make it green (and not red like the previous syntax specified). Here, the <p> tag will be made green only in the context of <div> tag. It will be red in all other contexts. "
},
{
"code": null,
"e": 2198,
"s": 2193,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Contextual Selectors</title> <style> div p { color: green; } </style></head> <body> <div> <p>Geeks For Geeks</p> <p>A Computer Science portal for geeks.</p> </div> <p>What are Contextual Selectors in CSS?</p> </body> </html>",
"e": 2522,
"s": 2198,
"text": null
},
{
"code": null,
"e": 2530,
"s": 2522,
"text": "Output:"
},
{
"code": null,
"e": 2679,
"s": 2530,
"text": "From the above examples, we have seen that how a contextual selector is applied to style an element only if the element is in the specified context."
},
{
"code": null,
"e": 2830,
"s": 2679,
"text": "Hello Geeks! Don’t stop learning now. Get hold of all the important competitive programming concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 2844,
"s": 2830,
"text": "sumitgumber28"
},
{
"code": null,
"e": 2858,
"s": 2844,
"text": "CSS-Questions"
},
{
"code": null,
"e": 2872,
"s": 2858,
"text": "CSS-Selectors"
},
{
"code": null,
"e": 2879,
"s": 2872,
"text": "Picked"
},
{
"code": null,
"e": 2883,
"s": 2879,
"text": "CSS"
},
{
"code": null,
"e": 2900,
"s": 2883,
"text": "Web Technologies"
}
] |
How to prevent Body from scrolling when a modal is opened using jQuery ?
|
12 Jan, 2021
Given an HTML document with a modal, the task is to prevent the body element from scrolling whenever the modal is in an open state. This task can be easily accomplished using JavaScript.
Approach: A simple solution to this problem is to set the value of the “overflow” property of the body element to “hidden” whenever the modal is opened, which disables the scroll on the selected element. Once the modal is closed, we would set the “overflow” property of the body element to “auto” so that scroll functionality is enabled on the body element. To find out whether the modal is opened or not, we would check if it has the “hidden” CSS class in its class list using the classList.contains() method of JavaScript. This “hidden” class is responsible for the opening and closing (changing display property) of the modal on a button click. Check out the given example for a better understanding.
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /> <style> body { padding: 5% 20%; } #container { z-index: 1; } #btn { border: none; font-size: 24px; padding: 12px 36px; color: white; background-color: green; } #modal { height: 200px; width: 400px; padding: 60px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: 999; background-color: green; color: white; } .hidden { display: none; } </style></head> <body> <!--Button to toggle modal--> <button id="btn" onclick="showModal()"> Toggle modal </button> <!--Modal container--> <div id="modal" class="hidden"> <div id="modal-body"> <h1>GeeksforGeeks</h1> <h2>This is a modal</h2> </div> </div> <!--Long text so that the body scrolls--> <div id="container"> <h1> Given a graph and a source vertex in the graph, find shortest paths from source to all vertices in the given graph. Dijkstra’s algorithm is very similar to Prim’s algorithm for minimum spanning tree. Like Prim’s MST, we generate a SPT (shortest path tree) with given source as root. We maintain two sets, one set contains vertices included in shortest path tree, other set includes vertices not yet included in shortest path tree. At every step of the algorithm, we find a vertex which is in the other set (set of not yet included) and has a minimum distance from the source. Below are the detailed steps used in Dijkstra’s algorithm to find the shortest path from a single source vertex to all other vertices in the given graph. Algorithm Create a set sptSet (shortest path tree set) that keeps track of vertices included in shortest path tree, i.e., whose minimum distance from source is calculated and finalized. Initially, this set is empty. Assign a distance value to all vertices in the input graph. Initialize all distance values as INFINITE. Assign distance value as 0 for the source vertex so that it is picked first. While sptSet doesn’t include all vertices Pick a vertex u which is not there in sptSet and has minimum distance value. Include u to sptSet. Update distance value of all adjacent vertices of u. To update the distance values, iterate through all adjacent vertices. For every adjacent vertex v, if sum of distance value of u (from source) and weight of edge u-v, is less than the distance value of v, then update the distance value of v. Given a graph and a source vertex in the graph, find shortest paths from source to all vertices in the given graph. Dijkstra’s algorithm is very similar to Prim’s algorithm for minimum spanning tree. Like Prim’s MST, we generate a SPT (shortest path tree) with given source as root. We maintain two sets, one set contains vertices included in shortest path tree, other set includes vertices not yet included in shortest path tree. At every step of the algorithm, we find a vertex which is in the other set (set of not yet included) and has a minimum distance from the source. Below are the detailed steps used in Dijkstra’s algorithm to find the shortest path from a single source vertex to all other vertices in the given graph. Algorithm Create a set sptSet (shortest path tree set) that keeps track of vertices included in shortest path tree, i.e., whose minimum distance from source is calculated and finalized. Initially, this set is empty. Assign a distance value to all vertices in the input graph. Initialize all distance values as INFINITE. Assign distance value as 0 for the source vertex so that it is picked first. While sptSet doesn’t include all vertices Pick a vertex u which is not there in sptSet and has minimum distance value. Include u to sptSet. Update distance value of all adjacent vertices of u. To update the distance values, iterate through all adjacent vertices. For every adjacent vertex v, if sum of distance value of u (from source) and weight of edge u-v, is less than the distance value of v, then update the distance value of v. </h1> </div> <script> // Select required elements from the DOM const modal = document.querySelector("#modal"); const body = document.querySelector("body"); const showModal = function (e) { modal.classList.toggle("hidden"); if (!modal.classList.contains("hidden")) { // Disable scroll body.style.overflow = "hidden"; } else { // Enable scroll body.style.overflow = "auto"; } }; </script></body> </html>
Output:
CSS-Misc
HTML-Misc
jQuery-Misc
Picked
CSS
HTML
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n12 Jan, 2021"
},
{
"code": null,
"e": 239,
"s": 52,
"text": "Given an HTML document with a modal, the task is to prevent the body element from scrolling whenever the modal is in an open state. This task can be easily accomplished using JavaScript."
},
{
"code": null,
"e": 944,
"s": 239,
"text": "Approach: A simple solution to this problem is to set the value of the “overflow” property of the body element to “hidden” whenever the modal is opened, which disables the scroll on the selected element. Once the modal is closed, we would set the “overflow” property of the body element to “auto” so that scroll functionality is enabled on the body element. To find out whether the modal is opened or not, we would check if it has the “hidden” CSS class in its class list using the classList.contains() method of JavaScript. This “hidden” class is responsible for the opening and closing (changing display property) of the modal on a button click. Check out the given example for a better understanding. "
},
{
"code": null,
"e": 953,
"s": 944,
"text": "Example:"
},
{
"code": null,
"e": 958,
"s": 953,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /> <style> body { padding: 5% 20%; } #container { z-index: 1; } #btn { border: none; font-size: 24px; padding: 12px 36px; color: white; background-color: green; } #modal { height: 200px; width: 400px; padding: 60px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: 999; background-color: green; color: white; } .hidden { display: none; } </style></head> <body> <!--Button to toggle modal--> <button id=\"btn\" onclick=\"showModal()\"> Toggle modal </button> <!--Modal container--> <div id=\"modal\" class=\"hidden\"> <div id=\"modal-body\"> <h1>GeeksforGeeks</h1> <h2>This is a modal</h2> </div> </div> <!--Long text so that the body scrolls--> <div id=\"container\"> <h1> Given a graph and a source vertex in the graph, find shortest paths from source to all vertices in the given graph. Dijkstra’s algorithm is very similar to Prim’s algorithm for minimum spanning tree. Like Prim’s MST, we generate a SPT (shortest path tree) with given source as root. We maintain two sets, one set contains vertices included in shortest path tree, other set includes vertices not yet included in shortest path tree. At every step of the algorithm, we find a vertex which is in the other set (set of not yet included) and has a minimum distance from the source. Below are the detailed steps used in Dijkstra’s algorithm to find the shortest path from a single source vertex to all other vertices in the given graph. Algorithm Create a set sptSet (shortest path tree set) that keeps track of vertices included in shortest path tree, i.e., whose minimum distance from source is calculated and finalized. Initially, this set is empty. Assign a distance value to all vertices in the input graph. Initialize all distance values as INFINITE. Assign distance value as 0 for the source vertex so that it is picked first. While sptSet doesn’t include all vertices Pick a vertex u which is not there in sptSet and has minimum distance value. Include u to sptSet. Update distance value of all adjacent vertices of u. To update the distance values, iterate through all adjacent vertices. For every adjacent vertex v, if sum of distance value of u (from source) and weight of edge u-v, is less than the distance value of v, then update the distance value of v. Given a graph and a source vertex in the graph, find shortest paths from source to all vertices in the given graph. Dijkstra’s algorithm is very similar to Prim’s algorithm for minimum spanning tree. Like Prim’s MST, we generate a SPT (shortest path tree) with given source as root. We maintain two sets, one set contains vertices included in shortest path tree, other set includes vertices not yet included in shortest path tree. At every step of the algorithm, we find a vertex which is in the other set (set of not yet included) and has a minimum distance from the source. Below are the detailed steps used in Dijkstra’s algorithm to find the shortest path from a single source vertex to all other vertices in the given graph. Algorithm Create a set sptSet (shortest path tree set) that keeps track of vertices included in shortest path tree, i.e., whose minimum distance from source is calculated and finalized. Initially, this set is empty. Assign a distance value to all vertices in the input graph. Initialize all distance values as INFINITE. Assign distance value as 0 for the source vertex so that it is picked first. While sptSet doesn’t include all vertices Pick a vertex u which is not there in sptSet and has minimum distance value. Include u to sptSet. Update distance value of all adjacent vertices of u. To update the distance values, iterate through all adjacent vertices. For every adjacent vertex v, if sum of distance value of u (from source) and weight of edge u-v, is less than the distance value of v, then update the distance value of v. </h1> </div> <script> // Select required elements from the DOM const modal = document.querySelector(\"#modal\"); const body = document.querySelector(\"body\"); const showModal = function (e) { modal.classList.toggle(\"hidden\"); if (!modal.classList.contains(\"hidden\")) { // Disable scroll body.style.overflow = \"hidden\"; } else { // Enable scroll body.style.overflow = \"auto\"; } }; </script></body> </html>",
"e": 6767,
"s": 958,
"text": null
},
{
"code": null,
"e": 6775,
"s": 6767,
"text": "Output:"
},
{
"code": null,
"e": 6784,
"s": 6775,
"text": "CSS-Misc"
},
{
"code": null,
"e": 6794,
"s": 6784,
"text": "HTML-Misc"
},
{
"code": null,
"e": 6806,
"s": 6794,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 6813,
"s": 6806,
"text": "Picked"
},
{
"code": null,
"e": 6817,
"s": 6813,
"text": "CSS"
},
{
"code": null,
"e": 6822,
"s": 6817,
"text": "HTML"
},
{
"code": null,
"e": 6829,
"s": 6822,
"text": "JQuery"
},
{
"code": null,
"e": 6846,
"s": 6829,
"text": "Web Technologies"
},
{
"code": null,
"e": 6851,
"s": 6846,
"text": "HTML"
}
] |
How to Install Solidity in Windows?
|
11 May, 2022
To install solidity on windows ensure that you are using windows 10, as only windows 10 provides built-in Linux Subsystem. With the help of this feature, we can run the Ubuntu terminal on the Windows machine. Below are the steps to setup Solidity on windows:
Step 1: Open control panel on your system and toggle to Windows Subsystem for Linux under Control Panel>Programs>Programs and Features>Turn Windows features on or off.
Step 2: After your system restarts install “Ubuntu LTS 18.04” from Microsoft store and after installation set it up.
Step 3: After setting up Bash install and check necessary dependencies like cURL, Node version manager(NVM), NodeJS and Node Packet Manager(NPM) using the following commands:
Installing cURL :sudo apt-get install curlcurl --version Installing NVM:curl -o-https://raw.githubusercontent.com/creationix/nvm/v0.33.0/install.sh | bashnvm --versionInstalling NodeJS and NPM:nvm install nodenode --versionnpm --versionAfter installing the dependencies, install and check solidity compiler solc by using following code:npm install -g solcsolcjs --version
Installing cURL :sudo apt-get install curlcurl --version
sudo apt-get install curl
curl --version
Installing NVM:curl -o-https://raw.githubusercontent.com/creationix/nvm/v0.33.0/install.sh | bashnvm --version
curl -o-https://raw.githubusercontent.com/creationix/nvm/v0.33.0/install.sh | bash
nvm --version
Installing NodeJS and NPM:nvm install nodenode --versionnpm --version
nvm install node
node --version
npm --version
After installing the dependencies, install and check solidity compiler solc by using following code:npm install -g solcsolcjs --version
npm install -g solc
solcjs --version
how-to-install
Blockchain
How To
Installation Guide
Solidity
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Become a Blockchain Developer?
Storage vs Memory in Solidity
How to connect ReactJS with MetaMask ?
Top 7 Interesting Blockchain Project Ideas for Beginners
Proof of Work (PoW) Consensus
How to Install PIP on Windows ?
How to Find the Wi-Fi Password Using CMD in Windows?
How to install Jupyter Notebook on Windows?
Java Tutorial
How to filter object array based on attributes?
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 May, 2022"
},
{
"code": null,
"e": 311,
"s": 52,
"text": "To install solidity on windows ensure that you are using windows 10, as only windows 10 provides built-in Linux Subsystem. With the help of this feature, we can run the Ubuntu terminal on the Windows machine. Below are the steps to setup Solidity on windows:"
},
{
"code": null,
"e": 479,
"s": 311,
"text": "Step 1: Open control panel on your system and toggle to Windows Subsystem for Linux under Control Panel>Programs>Programs and Features>Turn Windows features on or off."
},
{
"code": null,
"e": 596,
"s": 479,
"text": "Step 2: After your system restarts install “Ubuntu LTS 18.04” from Microsoft store and after installation set it up."
},
{
"code": null,
"e": 771,
"s": 596,
"text": "Step 3: After setting up Bash install and check necessary dependencies like cURL, Node version manager(NVM), NodeJS and Node Packet Manager(NPM) using the following commands:"
},
{
"code": null,
"e": 1143,
"s": 771,
"text": "Installing cURL :sudo apt-get install curlcurl --version Installing NVM:curl -o-https://raw.githubusercontent.com/creationix/nvm/v0.33.0/install.sh | bashnvm --versionInstalling NodeJS and NPM:nvm install nodenode --versionnpm --versionAfter installing the dependencies, install and check solidity compiler solc by using following code:npm install -g solcsolcjs --version"
},
{
"code": null,
"e": 1201,
"s": 1143,
"text": "Installing cURL :sudo apt-get install curlcurl --version "
},
{
"code": null,
"e": 1227,
"s": 1201,
"text": "sudo apt-get install curl"
},
{
"code": null,
"e": 1243,
"s": 1227,
"text": "curl --version "
},
{
"code": null,
"e": 1354,
"s": 1243,
"text": "Installing NVM:curl -o-https://raw.githubusercontent.com/creationix/nvm/v0.33.0/install.sh | bashnvm --version"
},
{
"code": null,
"e": 1437,
"s": 1354,
"text": "curl -o-https://raw.githubusercontent.com/creationix/nvm/v0.33.0/install.sh | bash"
},
{
"code": null,
"e": 1451,
"s": 1437,
"text": "nvm --version"
},
{
"code": null,
"e": 1521,
"s": 1451,
"text": "Installing NodeJS and NPM:nvm install nodenode --versionnpm --version"
},
{
"code": null,
"e": 1538,
"s": 1521,
"text": "nvm install node"
},
{
"code": null,
"e": 1553,
"s": 1538,
"text": "node --version"
},
{
"code": null,
"e": 1567,
"s": 1553,
"text": "npm --version"
},
{
"code": null,
"e": 1703,
"s": 1567,
"text": "After installing the dependencies, install and check solidity compiler solc by using following code:npm install -g solcsolcjs --version"
},
{
"code": null,
"e": 1723,
"s": 1703,
"text": "npm install -g solc"
},
{
"code": null,
"e": 1740,
"s": 1723,
"text": "solcjs --version"
},
{
"code": null,
"e": 1755,
"s": 1740,
"text": "how-to-install"
},
{
"code": null,
"e": 1766,
"s": 1755,
"text": "Blockchain"
},
{
"code": null,
"e": 1773,
"s": 1766,
"text": "How To"
},
{
"code": null,
"e": 1792,
"s": 1773,
"text": "Installation Guide"
},
{
"code": null,
"e": 1801,
"s": 1792,
"text": "Solidity"
},
{
"code": null,
"e": 1899,
"s": 1801,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1937,
"s": 1899,
"text": "How to Become a Blockchain Developer?"
},
{
"code": null,
"e": 1967,
"s": 1937,
"text": "Storage vs Memory in Solidity"
},
{
"code": null,
"e": 2006,
"s": 1967,
"text": "How to connect ReactJS with MetaMask ?"
},
{
"code": null,
"e": 2063,
"s": 2006,
"text": "Top 7 Interesting Blockchain Project Ideas for Beginners"
},
{
"code": null,
"e": 2093,
"s": 2063,
"text": "Proof of Work (PoW) Consensus"
},
{
"code": null,
"e": 2125,
"s": 2093,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2178,
"s": 2125,
"text": "How to Find the Wi-Fi Password Using CMD in Windows?"
},
{
"code": null,
"e": 2222,
"s": 2178,
"text": "How to install Jupyter Notebook on Windows?"
},
{
"code": null,
"e": 2236,
"s": 2222,
"text": "Java Tutorial"
}
] |
Int32.MinValue Field in C# with Examples
|
08 Apr, 2019
The MinValue property or Field of Int32 Struct is used to represent the minimum possible value of Int32. The value of this field is constant means that a user cannot change the value of this field. The value of this field is -2,147,483,648. Its hexadecimal value is 0x80000000.
Syntax:
public const int MinValue = -2147483648;
Return Value: This field always returns -2147483648.
Example:
// C# program to illustrate the// Int32.MinValue fieldusing System; class GFG { // Main Method static public void Main() { // display the Minimum value of Int32 struct Console.WriteLine("Minimum Value is: "+ Int32.MinValue); // Taking an array of long i.e Int64 data type long []num = {346, 434443, -33445, -442343263647}; // taking variable of Int32 type int mynum; foreach(long n in num) { if(n >= Int32.MinValue && n <= Int32.MaxValue) { // using the method of Convert class mynum = Convert.ToInt32(n); Console.WriteLine("Conversion is Possible."); } else { Console.WriteLine("Not Possible"); } } }}
Output:
Minimum Value is: -2147483648
Conversion is Possible.
Conversion is Possible.
Conversion is Possible.
Not Possible
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.int32.minvalue?view=netframework-4.7.2
CSharp-Int32-Struct
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to .NET Framework
C# | Delegates
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
C# | Data Types
C# | Constructors
C# | String.IndexOf( ) Method | Set - 1
C# | Class and Object
Extension Method in C#
Difference between Ref and Out keywords in C#
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Apr, 2019"
},
{
"code": null,
"e": 306,
"s": 28,
"text": "The MinValue property or Field of Int32 Struct is used to represent the minimum possible value of Int32. The value of this field is constant means that a user cannot change the value of this field. The value of this field is -2,147,483,648. Its hexadecimal value is 0x80000000."
},
{
"code": null,
"e": 314,
"s": 306,
"text": "Syntax:"
},
{
"code": null,
"e": 355,
"s": 314,
"text": "public const int MinValue = -2147483648;"
},
{
"code": null,
"e": 408,
"s": 355,
"text": "Return Value: This field always returns -2147483648."
},
{
"code": null,
"e": 417,
"s": 408,
"text": "Example:"
},
{
"code": "// C# program to illustrate the// Int32.MinValue fieldusing System; class GFG { // Main Method static public void Main() { // display the Minimum value of Int32 struct Console.WriteLine(\"Minimum Value is: \"+ Int32.MinValue); // Taking an array of long i.e Int64 data type long []num = {346, 434443, -33445, -442343263647}; // taking variable of Int32 type int mynum; foreach(long n in num) { if(n >= Int32.MinValue && n <= Int32.MaxValue) { // using the method of Convert class mynum = Convert.ToInt32(n); Console.WriteLine(\"Conversion is Possible.\"); } else { Console.WriteLine(\"Not Possible\"); } } }}",
"e": 1286,
"s": 417,
"text": null
},
{
"code": null,
"e": 1294,
"s": 1286,
"text": "Output:"
},
{
"code": null,
"e": 1410,
"s": 1294,
"text": "Minimum Value is: -2147483648\nConversion is Possible.\nConversion is Possible.\nConversion is Possible.\nNot Possible\n"
},
{
"code": null,
"e": 1421,
"s": 1410,
"text": "Reference:"
},
{
"code": null,
"e": 1511,
"s": 1421,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.int32.minvalue?view=netframework-4.7.2"
},
{
"code": null,
"e": 1531,
"s": 1511,
"text": "CSharp-Int32-Struct"
},
{
"code": null,
"e": 1534,
"s": 1531,
"text": "C#"
},
{
"code": null,
"e": 1632,
"s": 1534,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1663,
"s": 1632,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 1678,
"s": 1663,
"text": "C# | Delegates"
},
{
"code": null,
"e": 1721,
"s": 1678,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 1770,
"s": 1721,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 1786,
"s": 1770,
"text": "C# | Data Types"
},
{
"code": null,
"e": 1804,
"s": 1786,
"text": "C# | Constructors"
},
{
"code": null,
"e": 1844,
"s": 1804,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 1866,
"s": 1844,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 1889,
"s": 1866,
"text": "Extension Method in C#"
}
] |
Encoding Methods in Genetic Algorithm
|
29 Nov, 2021
Chromosome : All living organisms consists of cells. In each cell there is a same set of Chromosomes. Chromosomes are strings of DNA and consists of genes, blocks of DNA. Each gene encodes a trait, for example color of eyes. Reproduction : During reproduction, combination (or crossover) occurs first. Genes from parents combine to form a whole new chromosome. The newly created offspring can then be mutated. The changes are mainly caused by errors in copying genes from parents. The fitness of an organism is measured by the success of the organism in its life.
Operation of Genetic Algorithms : Two important elements required for any problem before a genetic algorithm can be used for a solution are
Method for representing a solution ex: a string of bits, numbers, character ex: determination total weight.
Method for measuring the quality of any proposed solution, using fitness function.
An individual is characterized by a set of parameters : Genes
The genes are joined into a string : Chromosome
The chromosome forms the genotype
The genotype contains all information to construct an organism : Phenotype
Reproduction is a “dumb” process on the chromosome of the genotype
Fitness is measured in the real world (‘Struggle for life’) of the phenotype.
Algorithmic Phases :
Simple_Genetic_Algorithm()
{
Initialize the population;
Calculate Fitness Function;
while(Fitness Value != Optimal Value)
{
Selection; //Natural Selection, survival of fittest
Crossover; //Reproduction, propagate favorable characteristics
Mutation;
Calculate Fitness Function;
}
}
Encoding using string : Encoding of chromosomes is the first step in solving the problem and it depends entirely on the problem heavily. The process of representing the solution in the form of a string of bits that conveys the necessary information. just as in a chromosome, each gene controls a particular characteristics of the individual, similarly, each bit in the string represents a characteristics of the solution.
Encoding Methods :
Binary Encoding : Most common methods of encoding. Chromosomes are string of 1s and 0s and each position in the chromosome represents a particular characteristics of the problem.
Permutation Encoding : Useful in ordering such as the Travelling Salesman Problem (TSP). In TSP, every chromosome is a string of numbers, each of which represents a city to be visited.
Value Encoding : Used in problems where complicated values, such as real numbers, are used and where binary encoding would not suffice. Good for some problems, nut often necessary to develop some specific crossover and mutation techniques for these chromosomes.
rajeev0719singh
Genetic Algorithms
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Support Vector Machine Algorithm
Introduction to Recurrent Neural Network
ML | Monte Carlo Tree Search (MCTS)
Markov Decision Process
DBSCAN Clustering in ML | Density based clustering
Normalization vs Standardization
Bagging vs Boosting in Machine Learning
Principal Component Analysis with Python
Types of Environments in AI
k-nearest neighbor algorithm in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Nov, 2021"
},
{
"code": null,
"e": 593,
"s": 28,
"text": "Chromosome : All living organisms consists of cells. In each cell there is a same set of Chromosomes. Chromosomes are strings of DNA and consists of genes, blocks of DNA. Each gene encodes a trait, for example color of eyes. Reproduction : During reproduction, combination (or crossover) occurs first. Genes from parents combine to form a whole new chromosome. The newly created offspring can then be mutated. The changes are mainly caused by errors in copying genes from parents. The fitness of an organism is measured by the success of the organism in its life. "
},
{
"code": null,
"e": 734,
"s": 593,
"text": "Operation of Genetic Algorithms : Two important elements required for any problem before a genetic algorithm can be used for a solution are "
},
{
"code": null,
"e": 842,
"s": 734,
"text": "Method for representing a solution ex: a string of bits, numbers, character ex: determination total weight."
},
{
"code": null,
"e": 925,
"s": 842,
"text": "Method for measuring the quality of any proposed solution, using fitness function."
},
{
"code": null,
"e": 987,
"s": 925,
"text": "An individual is characterized by a set of parameters : Genes"
},
{
"code": null,
"e": 1035,
"s": 987,
"text": "The genes are joined into a string : Chromosome"
},
{
"code": null,
"e": 1069,
"s": 1035,
"text": "The chromosome forms the genotype"
},
{
"code": null,
"e": 1144,
"s": 1069,
"text": "The genotype contains all information to construct an organism : Phenotype"
},
{
"code": null,
"e": 1212,
"s": 1144,
"text": "Reproduction is a “dumb” process on the chromosome of the genotype "
},
{
"code": null,
"e": 1290,
"s": 1212,
"text": "Fitness is measured in the real world (‘Struggle for life’) of the phenotype."
},
{
"code": null,
"e": 1312,
"s": 1290,
"text": "Algorithmic Phases : "
},
{
"code": null,
"e": 1662,
"s": 1312,
"text": "Simple_Genetic_Algorithm()\n{\n Initialize the population;\n Calculate Fitness Function;\n\n while(Fitness Value != Optimal Value)\n {\n Selection; //Natural Selection, survival of fittest\n Crossover; //Reproduction, propagate favorable characteristics\n Mutation;\n Calculate Fitness Function;\n }\n}"
},
{
"code": null,
"e": 2085,
"s": 1662,
"text": "Encoding using string : Encoding of chromosomes is the first step in solving the problem and it depends entirely on the problem heavily. The process of representing the solution in the form of a string of bits that conveys the necessary information. just as in a chromosome, each gene controls a particular characteristics of the individual, similarly, each bit in the string represents a characteristics of the solution. "
},
{
"code": null,
"e": 2105,
"s": 2085,
"text": "Encoding Methods : "
},
{
"code": null,
"e": 2285,
"s": 2105,
"text": "Binary Encoding : Most common methods of encoding. Chromosomes are string of 1s and 0s and each position in the chromosome represents a particular characteristics of the problem. "
},
{
"code": null,
"e": 2471,
"s": 2285,
"text": "Permutation Encoding : Useful in ordering such as the Travelling Salesman Problem (TSP). In TSP, every chromosome is a string of numbers, each of which represents a city to be visited. "
},
{
"code": null,
"e": 2734,
"s": 2471,
"text": "Value Encoding : Used in problems where complicated values, such as real numbers, are used and where binary encoding would not suffice. Good for some problems, nut often necessary to develop some specific crossover and mutation techniques for these chromosomes. "
},
{
"code": null,
"e": 2750,
"s": 2734,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 2769,
"s": 2750,
"text": "Genetic Algorithms"
},
{
"code": null,
"e": 2786,
"s": 2769,
"text": "Machine Learning"
},
{
"code": null,
"e": 2803,
"s": 2786,
"text": "Machine Learning"
},
{
"code": null,
"e": 2901,
"s": 2803,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2934,
"s": 2901,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 2975,
"s": 2934,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 3011,
"s": 2975,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 3035,
"s": 3011,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 3086,
"s": 3035,
"text": "DBSCAN Clustering in ML | Density based clustering"
},
{
"code": null,
"e": 3119,
"s": 3086,
"text": "Normalization vs Standardization"
},
{
"code": null,
"e": 3159,
"s": 3119,
"text": "Bagging vs Boosting in Machine Learning"
},
{
"code": null,
"e": 3200,
"s": 3159,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 3228,
"s": 3200,
"text": "Types of Environments in AI"
}
] |
Period between() method in Java with Examples
|
27 Nov, 2018
The between() method of Period class in Java is used to obtain a period consisting of the number of years, months, and days between two given dates (including start date and excluding end date).
This period is obtained as follows:
Remove complete months.
Now, calculate the remaining number of days.
Then, adjust to ensure that both have the same sign.
Now, split the number of months into years and months based on a 12 month year.
Consider a month, if the end day-of-month is greater than or equal to the start day-of-month (Eg.: from 2017-05-12 to 2018-07-18 is one year, two months and six days).
Note: Period obtained from above formula can be a negative, if the end is before the start. The negative sign will be the same in each of year, month and day.
Syntax:
public static Period between(LocalDate startDateInclusive,
LocalDate endDateExclusive)
Parameters:
startDateInclusive – The start date is inclusive and must not be null.
endDateExclusive – The end date is exclusive and must not be null.
Return Value: The between() function of period returns the period between the given start and end date.
Below is the implementation of above function:
// Java code to show the period// between given start and end dateimport java.time.LocalDate;import java.time.Period; public class PeriodClass { // Function to calculate period between // start and end date static void calculatePeriod(LocalDate startDate, LocalDate endDate) { Period period = Period.between(startDate, endDate); System.out.println("Period between start and end " + "date is : " + period); } // Driver Code public static void main(String[] args) { // Start date LocalDate startDate = LocalDate.parse("2017-02-13"); // End date LocalDate endDate = LocalDate.parse("2018-08-20"); calculatePeriod(startDate, endDate); }}
Period between start and end date is : P1Y6M7D
Reference: https://docs.oracle.com/javase/8/docs/api/java/time/Period.html#between-java.time.LocalDate-java.time.LocalDate-
Java-Functions
Java-Period
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Nov, 2018"
},
{
"code": null,
"e": 223,
"s": 28,
"text": "The between() method of Period class in Java is used to obtain a period consisting of the number of years, months, and days between two given dates (including start date and excluding end date)."
},
{
"code": null,
"e": 259,
"s": 223,
"text": "This period is obtained as follows:"
},
{
"code": null,
"e": 283,
"s": 259,
"text": "Remove complete months."
},
{
"code": null,
"e": 328,
"s": 283,
"text": "Now, calculate the remaining number of days."
},
{
"code": null,
"e": 381,
"s": 328,
"text": "Then, adjust to ensure that both have the same sign."
},
{
"code": null,
"e": 461,
"s": 381,
"text": "Now, split the number of months into years and months based on a 12 month year."
},
{
"code": null,
"e": 629,
"s": 461,
"text": "Consider a month, if the end day-of-month is greater than or equal to the start day-of-month (Eg.: from 2017-05-12 to 2018-07-18 is one year, two months and six days)."
},
{
"code": null,
"e": 788,
"s": 629,
"text": "Note: Period obtained from above formula can be a negative, if the end is before the start. The negative sign will be the same in each of year, month and day."
},
{
"code": null,
"e": 796,
"s": 788,
"text": "Syntax:"
},
{
"code": null,
"e": 913,
"s": 796,
"text": "public static Period between(LocalDate startDateInclusive,\n LocalDate endDateExclusive)\n"
},
{
"code": null,
"e": 925,
"s": 913,
"text": "Parameters:"
},
{
"code": null,
"e": 996,
"s": 925,
"text": "startDateInclusive – The start date is inclusive and must not be null."
},
{
"code": null,
"e": 1063,
"s": 996,
"text": "endDateExclusive – The end date is exclusive and must not be null."
},
{
"code": null,
"e": 1167,
"s": 1063,
"text": "Return Value: The between() function of period returns the period between the given start and end date."
},
{
"code": null,
"e": 1214,
"s": 1167,
"text": "Below is the implementation of above function:"
},
{
"code": "// Java code to show the period// between given start and end dateimport java.time.LocalDate;import java.time.Period; public class PeriodClass { // Function to calculate period between // start and end date static void calculatePeriod(LocalDate startDate, LocalDate endDate) { Period period = Period.between(startDate, endDate); System.out.println(\"Period between start and end \" + \"date is : \" + period); } // Driver Code public static void main(String[] args) { // Start date LocalDate startDate = LocalDate.parse(\"2017-02-13\"); // End date LocalDate endDate = LocalDate.parse(\"2018-08-20\"); calculatePeriod(startDate, endDate); }}",
"e": 1990,
"s": 1214,
"text": null
},
{
"code": null,
"e": 2038,
"s": 1990,
"text": "Period between start and end date is : P1Y6M7D\n"
},
{
"code": null,
"e": 2162,
"s": 2038,
"text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/time/Period.html#between-java.time.LocalDate-java.time.LocalDate-"
},
{
"code": null,
"e": 2177,
"s": 2162,
"text": "Java-Functions"
},
{
"code": null,
"e": 2189,
"s": 2177,
"text": "Java-Period"
},
{
"code": null,
"e": 2207,
"s": 2189,
"text": "Java-time package"
},
{
"code": null,
"e": 2212,
"s": 2207,
"text": "Java"
},
{
"code": null,
"e": 2217,
"s": 2212,
"text": "Java"
},
{
"code": null,
"e": 2315,
"s": 2217,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2366,
"s": 2315,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 2397,
"s": 2366,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 2416,
"s": 2397,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 2446,
"s": 2416,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 2461,
"s": 2446,
"text": "Stream In Java"
},
{
"code": null,
"e": 2479,
"s": 2461,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 2499,
"s": 2479,
"text": "Collections in Java"
},
{
"code": null,
"e": 2523,
"s": 2499,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 2555,
"s": 2523,
"text": "Multidimensional Arrays in Java"
}
] |
Fixed-priority pre-emptive scheduling
|
16 Apr, 2020
Prerequisite – CPU Scheduling in Operating SystemsFixed priority pre-emptive scheduling algorithm is mostly used in real time systems.In this scheduling algorithm the processor make sure that the highest priority task is to be performed first ignoring the other task to be executed.
The process having highest priority is served first.
Decision Mode:Pre-emptive: When a process arrives its priority is compared with the current process’s priority.If the new job have higher priority then the current process, the current process is suspended and new process is started.
Implementation:Sorted FIFO queue is used for this strategy. As the new process is identified it is placed in the queue according to it’s priority.Hence the process having higher priority is considered first as it is placed at higher position.
Example:Let us take the following example having 4 set of processes along with its arrival time and time taken to complete the process.Also the priority of all the process are mentioned.Consider all time values in millisecond and small value of priority means higher priority of process.
Gantt chart:
Initially only P0 is present and it is allowed to run.But when P1 comes, it has higher priority.So, P0 is pre-empted and P1 is allowed to run.This process repeated till all processes complete their execution.
Statistic :
Average Turnaround time:
= (22+12+2+4) / 4
= 40 / 4
= 10 ms
Average Waiting time:
= (12+6+0+0) / 4
= 18 / 4
= 4.5 ms
Advantages:Priority is considered.Critical process can get even better response.
Disadvantage:Starvation is possible for low priority process.It can be overcome by using technique called “Aging“. Aging gradually increases the priority of the process that wait in the system for long time. Context switch overhead is there.
Picked
Operating Systems
Write From Home
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
File Allocation Methods
Memory Management in Operating System
Logical and Physical Address in Operating System
Segmentation in Operating System
Structures of Directory in Operating System
Convert integer to string in Python
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Factory method design pattern in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Apr, 2020"
},
{
"code": null,
"e": 311,
"s": 28,
"text": "Prerequisite – CPU Scheduling in Operating SystemsFixed priority pre-emptive scheduling algorithm is mostly used in real time systems.In this scheduling algorithm the processor make sure that the highest priority task is to be performed first ignoring the other task to be executed."
},
{
"code": null,
"e": 364,
"s": 311,
"text": "The process having highest priority is served first."
},
{
"code": null,
"e": 598,
"s": 364,
"text": "Decision Mode:Pre-emptive: When a process arrives its priority is compared with the current process’s priority.If the new job have higher priority then the current process, the current process is suspended and new process is started."
},
{
"code": null,
"e": 841,
"s": 598,
"text": "Implementation:Sorted FIFO queue is used for this strategy. As the new process is identified it is placed in the queue according to it’s priority.Hence the process having higher priority is considered first as it is placed at higher position."
},
{
"code": null,
"e": 1129,
"s": 841,
"text": "Example:Let us take the following example having 4 set of processes along with its arrival time and time taken to complete the process.Also the priority of all the process are mentioned.Consider all time values in millisecond and small value of priority means higher priority of process."
},
{
"code": null,
"e": 1142,
"s": 1129,
"text": "Gantt chart:"
},
{
"code": null,
"e": 1351,
"s": 1142,
"text": "Initially only P0 is present and it is allowed to run.But when P1 comes, it has higher priority.So, P0 is pre-empted and P1 is allowed to run.This process repeated till all processes complete their execution."
},
{
"code": null,
"e": 1363,
"s": 1351,
"text": "Statistic :"
},
{
"code": null,
"e": 1388,
"s": 1363,
"text": "Average Turnaround time:"
},
{
"code": null,
"e": 1428,
"s": 1388,
"text": "= (22+12+2+4) / 4 \n= 40 / 4\n= 10 ms "
},
{
"code": null,
"e": 1450,
"s": 1428,
"text": "Average Waiting time:"
},
{
"code": null,
"e": 1490,
"s": 1450,
"text": "= (12+6+0+0) / 4 \n= 18 / 4\n= 4.5 ms "
},
{
"code": null,
"e": 1571,
"s": 1490,
"text": "Advantages:Priority is considered.Critical process can get even better response."
},
{
"code": null,
"e": 1813,
"s": 1571,
"text": "Disadvantage:Starvation is possible for low priority process.It can be overcome by using technique called “Aging“. Aging gradually increases the priority of the process that wait in the system for long time. Context switch overhead is there."
},
{
"code": null,
"e": 1820,
"s": 1813,
"text": "Picked"
},
{
"code": null,
"e": 1838,
"s": 1820,
"text": "Operating Systems"
},
{
"code": null,
"e": 1854,
"s": 1838,
"text": "Write From Home"
},
{
"code": null,
"e": 1872,
"s": 1854,
"text": "Operating Systems"
},
{
"code": null,
"e": 1970,
"s": 1872,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1994,
"s": 1970,
"text": "File Allocation Methods"
},
{
"code": null,
"e": 2032,
"s": 1994,
"text": "Memory Management in Operating System"
},
{
"code": null,
"e": 2081,
"s": 2032,
"text": "Logical and Physical Address in Operating System"
},
{
"code": null,
"e": 2114,
"s": 2081,
"text": "Segmentation in Operating System"
},
{
"code": null,
"e": 2158,
"s": 2114,
"text": "Structures of Directory in Operating System"
},
{
"code": null,
"e": 2194,
"s": 2158,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 2230,
"s": 2194,
"text": "Convert string to integer in Python"
},
{
"code": null,
"e": 2291,
"s": 2230,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 2307,
"s": 2291,
"text": "Python infinity"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.