title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
C++ Inline Functions | C++ inline function is powerful concept that is commonly used with classes. If a function is inline, the compiler places a copy of the code of that function at each point where the function is called at compile time.
Any change to an inline function could require all clients of the function to be recompiled because compiler would need to replace all the code once again otherwise it will continue with old functionality.
To inline a function, place the keyword inline before the function name and define the function before any calls are made to the function. The compiler can ignore the inline qualifier in case defined function is more than a line.
A function definition in a class definition is an inline function definition, even without the use of the inline specifier.
Following is an example, which makes use of inline function to return max of two numbers −
#include <iostream>
using namespace std;
inline int Max(int x, int y) {
return (x > y)? x : y;
}
// Main function for the program
int main() {
cout << "Max (20,10): " << Max(20,10) << endl;
cout << "Max (0,200): " << Max(0,200) << endl;
cout << "Max (100,1010): " << Max(100,1010) << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Max (20,10): 20
Max (0,200): 200
Max (100,1010): 1010
154 Lectures
11.5 hours
Arnab Chakraborty
14 Lectures
57 mins
Kaushik Roy Chowdhury
30 Lectures
12.5 hours
Frahaan Hussain
54 Lectures
3.5 hours
Frahaan Hussain
77 Lectures
5.5 hours
Frahaan Hussain
12 Lectures
3.5 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2535,
"s": 2318,
"text": "C++ inline function is powerful concept that is commonly used with classes. If a function is inline, the compiler places a copy of the code of that function at each point where the function is called at compile time."
},
{
"code": null,
"e": 2741,
"s": 2535,
"text": "Any change to an inline function could require all clients of the function to be recompiled because compiler would need to replace all the code once again otherwise it will continue with old functionality."
},
{
"code": null,
"e": 2971,
"s": 2741,
"text": "To inline a function, place the keyword inline before the function name and define the function before any calls are made to the function. The compiler can ignore the inline qualifier in case defined function is more than a line."
},
{
"code": null,
"e": 3096,
"s": 2971,
"text": "A function definition in a class definition is an inline function definition, even without the use of the inline specifier."
},
{
"code": null,
"e": 3187,
"s": 3096,
"text": "Following is an example, which makes use of inline function to return max of two numbers −"
},
{
"code": null,
"e": 3512,
"s": 3187,
"text": "#include <iostream>\n \nusing namespace std;\n\ninline int Max(int x, int y) {\n return (x > y)? x : y;\n}\n\n// Main function for the program\nint main() {\n cout << \"Max (20,10): \" << Max(20,10) << endl;\n cout << \"Max (0,200): \" << Max(0,200) << endl;\n cout << \"Max (100,1010): \" << Max(100,1010) << endl;\n \n return 0;\n}"
},
{
"code": null,
"e": 3593,
"s": 3512,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3648,
"s": 3593,
"text": "Max (20,10): 20\nMax (0,200): 200\nMax (100,1010): 1010\n"
},
{
"code": null,
"e": 3685,
"s": 3648,
"text": "\n 154 Lectures \n 11.5 hours \n"
},
{
"code": null,
"e": 3704,
"s": 3685,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3736,
"s": 3704,
"text": "\n 14 Lectures \n 57 mins\n"
},
{
"code": null,
"e": 3759,
"s": 3736,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 3795,
"s": 3759,
"text": "\n 30 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 3812,
"s": 3795,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3847,
"s": 3812,
"text": "\n 54 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3864,
"s": 3847,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3899,
"s": 3864,
"text": "\n 77 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3916,
"s": 3899,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3951,
"s": 3916,
"text": "\n 12 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3968,
"s": 3951,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3975,
"s": 3968,
"text": " Print"
},
{
"code": null,
"e": 3986,
"s": 3975,
"text": " Add Notes"
}
]
|
Change the background color of a button with CSS | To change the background color of a button, use the background-color property.
You can try to run the following code to change button’s background color
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
.btn {
background-color: yellow;
color: black;
text-align: center;
font-size: 13px;
}
</style>
</head>
<body>
<h2>Result</h2>
<p>Click below for result:</p>
<button class = "btn">Result</button>
</body>
</html> | [
{
"code": null,
"e": 1141,
"s": 1062,
"text": "To change the background color of a button, use the background-color property."
},
{
"code": null,
"e": 1215,
"s": 1141,
"text": "You can try to run the following code to change button’s background color"
},
{
"code": null,
"e": 1225,
"s": 1215,
"text": "Live Demo"
},
{
"code": null,
"e": 1582,
"s": 1225,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n .btn {\n background-color: yellow;\n color: black;\n text-align: center;\n font-size: 13px;\n }\n </style>\n </head>\n <body>\n <h2>Result</h2>\n <p>Click below for result:</p>\n <button class = \"btn\">Result</button>\n </body>\n</html>"
}
]
|
Program to reverse an array up to a given position in Python | In this tutorial, we will learn how to reverse an array upto a given position. Let's see the problem statement.
We have an array of integers and a number n. Our goal is to reverse the elements of the array from the 0th index to (n-1)th index. For example,
Input
array = [1, 2, 3, 4, 5, 6, 7, 8, 9] n = 5
Output
[5, 4, 3, 2, 1, 6, 7, 8, 9]
Procedure to achieve the goal.
Initialize an array and a number
Loop until n / 2. Swap the (i)th index and (n-i-1)th elements.
Swap the (i)th index and (n-i-1)th elements.
Print the array you will get the result.
## initializing array and a number
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
n = 5
## checking whether the n value is less than length of the array or not
if n > len(arr):
print(f"{n} value is not valid")
else:
## loop until n / 2
for i in range(n // 2):
arr[i], arr[n - i - 1] = arr[n - i - 1], arr[i]
## printing the array
print(arr)
If you run the above program, you will get the following results.
[5, 4, 3, 2, 1, 6, 7, 8, 9]
A simple way to do this is to use the slicing in Python.
1. Initialize an array and a number
2. Slice from (n-1) to 0 and n to length(Add both of them).
Let's see the code.
## initializing array and a number
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
n = 5
## checking whether the n value is less than length of the array or not
if n > len(arr):
print(f"{n} value is not valid")
else:
## reversing the arr upto n
## [n-1::-1] n - 0 -1 is for decrementing the index
## [n:] from n - length
arr = arr[n-1::-1] + arr[n:]
## printing the arr
print(arr)
If you run the above program, you will get the following result.
[5, 4, 3, 2, 1, 6, 7, 8, 9]
If you have any doubts regarding the program, please do mention them in the comment section. | [
{
"code": null,
"e": 1174,
"s": 1062,
"text": "In this tutorial, we will learn how to reverse an array upto a given position. Let's see the problem statement."
},
{
"code": null,
"e": 1318,
"s": 1174,
"text": "We have an array of integers and a number n. Our goal is to reverse the elements of the array from the 0th index to (n-1)th index. For example,"
},
{
"code": null,
"e": 1401,
"s": 1318,
"text": "Input\narray = [1, 2, 3, 4, 5, 6, 7, 8, 9] n = 5\nOutput\n[5, 4, 3, 2, 1, 6, 7, 8, 9]"
},
{
"code": null,
"e": 1432,
"s": 1401,
"text": "Procedure to achieve the goal."
},
{
"code": null,
"e": 1466,
"s": 1432,
"text": " Initialize an array and a number"
},
{
"code": null,
"e": 1530,
"s": 1466,
"text": " Loop until n / 2. Swap the (i)th index and (n-i-1)th elements."
},
{
"code": null,
"e": 1576,
"s": 1530,
"text": " Swap the (i)th index and (n-i-1)th elements."
},
{
"code": null,
"e": 1617,
"s": 1576,
"text": "Print the array you will get the result."
},
{
"code": null,
"e": 1966,
"s": 1617,
"text": "## initializing array and a number\narr = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nn = 5\n## checking whether the n value is less than length of the array or not\nif n > len(arr):\n print(f\"{n} value is not valid\")\nelse:\n ## loop until n / 2\n for i in range(n // 2):\n arr[i], arr[n - i - 1] = arr[n - i - 1], arr[i]\n ## printing the array\n print(arr)"
},
{
"code": null,
"e": 2032,
"s": 1966,
"text": "If you run the above program, you will get the following results."
},
{
"code": null,
"e": 2060,
"s": 2032,
"text": "[5, 4, 3, 2, 1, 6, 7, 8, 9]"
},
{
"code": null,
"e": 2117,
"s": 2060,
"text": "A simple way to do this is to use the slicing in Python."
},
{
"code": null,
"e": 2153,
"s": 2117,
"text": "1. Initialize an array and a number"
},
{
"code": null,
"e": 2213,
"s": 2153,
"text": "2. Slice from (n-1) to 0 and n to length(Add both of them)."
},
{
"code": null,
"e": 2233,
"s": 2213,
"text": "Let's see the code."
},
{
"code": null,
"e": 2621,
"s": 2233,
"text": "## initializing array and a number\narr = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nn = 5\n## checking whether the n value is less than length of the array or not\nif n > len(arr):\n print(f\"{n} value is not valid\")\nelse:\n ## reversing the arr upto n\n ## [n-1::-1] n - 0 -1 is for decrementing the index\n ## [n:] from n - length\n arr = arr[n-1::-1] + arr[n:]\n ## printing the arr\n print(arr)"
},
{
"code": null,
"e": 2686,
"s": 2621,
"text": "If you run the above program, you will get the following result."
},
{
"code": null,
"e": 2714,
"s": 2686,
"text": "[5, 4, 3, 2, 1, 6, 7, 8, 9]"
},
{
"code": null,
"e": 2807,
"s": 2714,
"text": "If you have any doubts regarding the program, please do mention them in the comment section."
}
]
|
Shortest Path Distance Approximation Using Deep Learning: Node2Vec | by Asutosh Nayak | Towards Data Science | This article is an implementation of a research paper titled “Shortest Path Distance Approximation using Deep Learning Techniques”, where the authors explain a new method to approximate the shortest path distance between the nodes of a graph. I will explain the paper and my implementation of it. You can find the project on my GitHub account here. First I will give an overview of the method proposed in this paper, then we will go through some of the concepts used in this paper to solve the problem and finally the implementation.
1.1 Motivation: Why do we need to use deep learning to approximate distance between nodes when we have traditional exact methods like Dijkstra’s and A* algorithms? The problem with these traditional algorithms is that they are slow on very large graphs and would consume a lot of memory to store the precomputed distances. And since for most of the applications an approximation of actual distance is good enough, it encourages one to explore various ways to approximate the distances. Also, once a neural network is trained, the inference time (finding node distance) is constant (O(1)).
1.2 Algorithm: Now that we know the ‘why’, let’s look into the ‘how’. The paper uses the ideas presented in another excellent paper “node2vec: Scalable Feature Learning for Networks”. In fact, I would say that some of the ideas used in the paper under discussion were already presented in Node2Vec paper (for instance, the use of binary operators to represent an edge using corresponding node embeddings was proposed in Node2Vec paper, which was extended to represent path in this paper. We will discuss embeddings later). This paper is more of an application of Node2Vec. The Node2Vec itself is an extension of Word2Vec. Word2Vec is an algorithm to represent words with embeddings (vector of numbers) in a vector space, such that the semantically similar words are located closer to each other. It’s a fascinating topic in itself.
Here is a summary of the method proposed:
Collect your graph data.Use Node2Vec algorithm to find node embeddings for each node. We don’t need to write this algorithm from scratch. The authors have provided an implementation.Use a certain number of nodes in the graph as, what they call, “landmarks” and compute their distances from all the rest of the nodes. Now you have samples of form ((landmark_i, node_x), distance).For each sample found above fetch the corresponding node embeddings of the landmark and the node, and combine them with any of the suitable binary operators (average, element-wise multiplication etc.). So now you should have samples of form (embedding, distance).Now you have input-output pairs, so you do what you do best. Find a good neural net configuration and train the hell out of the model. But we will see later, as with AI in general, it’s not that easy.
Collect your graph data.
Use Node2Vec algorithm to find node embeddings for each node. We don’t need to write this algorithm from scratch. The authors have provided an implementation.
Use a certain number of nodes in the graph as, what they call, “landmarks” and compute their distances from all the rest of the nodes. Now you have samples of form ((landmark_i, node_x), distance).
For each sample found above fetch the corresponding node embeddings of the landmark and the node, and combine them with any of the suitable binary operators (average, element-wise multiplication etc.). So now you should have samples of form (embedding, distance).
Now you have input-output pairs, so you do what you do best. Find a good neural net configuration and train the hell out of the model. But we will see later, as with AI in general, it’s not that easy.
The project has following folders:
data — which holds all the data consumed by the program, both downloaded and processed.
outputs —this holds all the outputs, including text logs, tensorboard logs, model backups etc.
src — source code is placed here.
tests — any relevant test cases
Note: Please note that for this project I have worked on notebooks mostly because it involved a lot of exploration and experimentation with various approaches. As such, work is not polished since I am still exploring better ways. I have tried to explain the cells as much as I could. Feel free to reach out to me if something is unclear.
2.1 Data
I have used Facebook datasets from here. The downloaded graph data is in “mtx” format. This is just another format for sharing matrix data. It looks like this:
%%MatrixMarket matrix coordinate pattern symmetric6386 6386 217662195 1414 1458 1474 1510 1...
The first line is called “header” and defines some properties, which are used to decide how to parse the file to form the matrix. The line below it (size line) defines the size of data. The header always begins with “%%MatrixMarket” and the four fields that follow it are object, format, field, symmetry. Object field can be ‘matrix’ or ‘vector’ (in our case it will be matrix), format can be ‘coordinate’ or ‘array’. “coordinate” format stores only non-zero values in the mtx file, so the “size line” holds, number of rows, number of columns in the matrix and the number of non-zero entries. If format is “array”, the “size line” is of form [number of rows number of columns]. The next section is “data lines”, which hold the actual data. If format is “coordinate” there would be “number of non-zero entries” number of lines of data, else in case of “array” you should expect {number of rows * number of columns} number of data lines, where each line represents an edge between two nodes. The data lines could have a 3rd column “edge weight” for weighted graphs. The rest of the details can be found in above “mtx” link. I have shared this information to get you acquainted with it a little bit so that if you face parsing errors you can write your own implementation. Most of the times we may not need to, as Scipy supports reading/writing mtx format. But here we will need to first convert mtx to edgelist format as both Networkx (the package I use to process graph data) and Node2Vec script use this format.
Edgelist is just the data lines after stripping away the header, comments and size lines, like this:
2.2 Construct node embeddings
To calculate the node embeddings for our graph we will use the script provided by Node2Vec authors. But let me first introduce the algorithm briefly, since it’s quite interesting and also because it’s such an integral part of what we are doing here. Even if we don’t have to implement the algorithm, it shouldn’t stop us from learning about it. But you can choose to skip to next section.
2.2.1 Node2Vec
The idea is to sample the neighborhood of each node in the graph, also called a “walk” (which is a fancy way of saying: collect the nearby nodes), convert the visited nodes’ list to string (so that now you have samples of form ([list of nearby nodes as strings including source node])) and then pass all such lists to Word2Vec model to train and learn embeddings just like we train on list of sentences. But the best part of Node2Vec is how it samples the neighborhood. The authors argue that the classical approaches like BFS and DFS lie on two opposite ends of the spectrum. BFS tends to sample nodes closer to source node which causes the learned embeddings to capture structural similarity of nodes better (for e.g. whether a node acts as a hub/center in its neighborhood). But it only samples a small portion of the graph. On the other hand, DFS, tends to sample nodes far off from the source and thus learning from such ‘walks’ leads to embeddings which are better at capturing macroscopic view of graph (connectivity and “homophily” as then mention in the paper) but fail to capture finer details since walks are of finite length and they have a lot of grounds to cover.
Hence, they propose a new way of sampling a node’s neighborhood called “2nd order Random Walk”. Just to make it clearer, we are doing all this just to sample node neighborhood in a controlled way so that the walks include qualities of both BFS and DFS. Let’s consider a walk ‘c’ of fixed length ‘l’ and assume you have started your walk from node ‘u’. Assume that you have traveled from node t to v. Instead of choosing the next node randomly or based on the edge of weights, they use the following probability distribution:
which means if previous node in the walk was v then the probability of next node being x is given by pi_{vx}/z (can’t use inline latex because Medium screws it up every time I edit something), if nodes v and x are connected by an edge, else 0. pi_{vx} is the unnormalized transition probability and z is the normalizing constant (which could be the sum of all the probabilities of edges from node v). They define pi_{vx} as :
where w_{vx} is weight of edge between node v and x and $\alpha_{pq}(t,x)$ is:
where d_{tx} is the shortest path distance between t and x. Let’s understand the role of p and q, because these are the two parameters which control the nature of random walk (BFS or DFS), hence the term “2nd order Random Walk”.
If we recap a bit, we reached at node v from node t, and now we need to decide which node to visit next from v. If you set p to be a low value then the walk would prefer to revisit the previous nodes. How, you ask? Imagine that you have reached from t to v, now you have following options — go to other neighbors of v (x1, x2...xn) or go back to t (don’t forget ‘t’ is also a neighbor), in which case d_{tx} is zero, since x here is t itself (corresponds to the first option 1/p in the above equation). So if p is a very low value then 1/p would be quite large and random walk would prefer to go back to previous nodes and thus simulate the behavior of BFS. Please refer to the (ugly) image below to visualize this:
The paper has a similar image but without distance values. Similarly, if we choose a lower value for q then we are encouraging the algorithm to venture farther away from t by assigning higher probability to 3rd option in equation defining alpha. This kind of decision is made for every node in the walk. And several such walks are done.
If you have understood above explanation, you have an idea of how node2vec random walk works. You can also check the implementation of it on author’s GitHub repository (but it’s in python 2 format). In my project, I have also included the author’s script but converted to Python3 format.
2.2.2 Running the node2vec script
Running the script is quite simple. You can choose to run with all the default values for its parameters or change it to suit your needs. I ran with default values:
python node2vec/main3.py --input ../data/socfb-American75.edgelist --output ../data/emb/socfb-American75.emd
Just modify the input and output paths.
2.3 Construct Dataset
From previous step we have a file with node and their embeddings in following format:
6386 128224 0.3206627 -0.0963422 -0.039677385 -0.03290484 0.4414181 ....4046 -0.036134206 -0.082308784 0.49080133 -0.36878866 0.13950641 ......
First two numbers represent the number of nodes and dimension of embeddings respectively. Our next step is to select a certain number of nodes in the graph as landmarks and compute their distances from all the rest of the nodes. This would give us (number of landmarks*(number of nodes-1)) number of samples. We choose landmarks because finding distances for all the nodes would require a lot more compute.
“distance_map” dict holds distance of every node from a given landmark (as key). Now we need to get the corresponding node2vec embedding for each node/landmark pair and combine them to form a single embedding.
Here emd_map is a dict which holds each node as key and it’s embedding as value.
Next, we need to form numpy ndarrays from embedding-distance dict like shown above. Please note two things from the output of the cell above — the number of samples is not equal to num_of_landmarks*(num_of_nodes-1). This is because I have ignored node pairs which have inf distance i.e. no path connecting them. Second, the size of training array is massive at ~927MB, since it is ‘float64’ type array. I have converted them to float32 to save space.
As you can see we could save ~50% space. If you are worried about the precision loss due to this conversion, you can verify the data loss:
This seems insignificant. Next, let’s look at the distribution of target variable.
As you can see distance values 2 and 3 really dominate the data. On the graph 6, 7, 8 can’t be seen but they are present in the data, with the only sample for distance 8 which I dropped. Also note that in the paper, they ignore samples with distance value 1, but I have included them in training.
Since data is massively imbalanced, I have stratified the train/test split:
... and then normalized it:
I have saved the split data so that this preprocessing can be done once only. Whew!! Dataset formation was a big portion of this project and finally I have explained the major steps. I may have missed some, for more details you can check the data_prep.ipynb in the project repository.
2.4 Training the Neural Network
Now comes the exciting part. The code for training is in train.ipynb file. You will notice that some of the cells look unfinished/note-to-self. I have left these deliberately to let the interested readers gain experience from my failed attempts and the steps taken after each failure. I have even uploaded the tensorboard logs (which include changes made, result, notes etc) into the GitHub repo so that all the history is available for me and others to follow later. If you are not interested in the logs, you can delete the folders without any issues.
Since the data is skewed, I had to oversample the minority target values (I am not using the term “class” here because I have trained a regression model).
I have first undersampled the majority values and then oversampled the minority values. The intuition was to oversample the minority distance values to make them comparable to number of samples of majority values, while keeping the overall data size as small as possible. The fraction values “0.7” is not really calculated/derived from anywhere, it just seemed reasonable by looking at the frequencies of each distance values. And yes... don’t forget to shuffle the data after over/under sampling. It may seem like a trivial thing, something you can ignore but as it turned out many of the batches had same distance values (like all 1s or 2s etc) which made training impossible!
Now, let’s define a baseline, a simple model and it’s result to which we can compare to see how good we did:
Linear Regression does surprisingly good! 50% is a good baseline to compare with, considering that the chance prediction in this case is ~14% (1/7).
PyTroch Model
For all of my previous projects, I had used Keras but recently I switched to PyTorch and I haven’t regretted it ever since. I was working on another project which involved writing a custom loss function which required some calculations on output of intermediate layer of the model and other custom stuffs. If you have ever tried such things with Keras, you know it’s not straightforward. Even with eager execution I couldn’t get it to work. To make matters worse, one fine day, Keras started throwing CUDA compatibility errors, and it wouldn’t go away no matter how many times I built a new environment with required drivers. This was my breaking point. With PyTorch you may have to write a little bit of extra code for training loop but it’s worth it. Now, I am not saying these issues couldn’t have been solved with more effort, but, in a world where you have PyTorch, why break your head? So that concludes my rant about why I switched to PyTorch.
But for readers who are not acquainted with PyTorch, don’t be disheartened. Almost all the components used are available in Keras (except for may be Cyclic LR scheduler, but there are implementations of it that you can use). Explaining PyTorch would be out of the scope of this article.
The model which gave the best result (yet) has following configuration (with Cyclic LR Scheduler, RMSProp optimizer and Poisson Loss):
{'batch_size': 1000, 'input_size': 128, 'hidden_units_1': 200, 'hidden_units_2': 100, 'hidden_units_3': 50, 'do_1': 0.2, 'do_2': 0.1, 'do_3': 0.05, 'output_size': 1, 'lr': 0.001, 'min_lr': 1e-05, 'max_lr': 0.001, 'epochs': 500, 'lr_sched': 'clr', 'lr_sched_mode': 'triangular', 'gamma': 0.95}
It’s a 5 layer (3 hidden layers) model with dropouts, trained with cyclic learning rate.
You may not find this model in the GitHub code if I have tried other configurations after this and thus parameters could have changed. But you could find the corresponding model and parameters in run47 folder. Please note that this configuration is different from what they have mentioned in the paper. As with almost every other paper I have read, they have skipped the low level details of the NN.
Here is how you initialize Data Loaders for train/val/test data:
Now we are all set to train the model:
People who have only worked on Keras/Fastai yet, don’t get scared. Code to train PyTorch model is not always this big. I am doing a lot of other stuff like early stopping, checkpoint saves etc. It’s definitely more complicated than Keras, but nothing you can’t learn in a day or two. But like I have mentioned before all these components are already there in Keras (including Poisson Loss) so you can easily try it out on the framework of your choice.
I trained the model for ~110 epochs.
Here are the results:
Poisson Loss = -0.11MAE Loss = 0.32MSE Loss = 0.17Accuracy = 76.40% vsBaseline :MAE Loss = 0.59 MSE Loss = 0.56Accuracy = 50.57%
Although this was a regression problem, I have still recorded accuracy because I find it more intuitive (it’s not a metric, just something I used to compare models). It’s not a boastful result but it’s not bad. Also, I think, there is lot of margin for more improvements, which I will mention later.
If you are wondering why does longer path distances have worse accuracy, similar observations were made by authors as well. Here’s what they say:
Observe that the larger errors caused by longer paths utilizing node2vec embeddings. In one hand, we do not have enough samples for longer distances in the training set. On the other hand, node2vec fails to learn structural features of faraway nodes.
Note: There is one thing that’s bugging me about this model. Despite using exp_range as CLR mode, the learning rate didn’t change throughout the training (at least as per the plot). This happens for gamma value 0.95 always. Need to look into it. Or if you have faced this before and have any solutions, you are welcome to share here.
In retrospect, here are some of the things that improved the model performance:
Poisson Loss: I had tried MSE and MAE (used in the paper) earlier, but both didn’t work.Batch Normalization: The training loss improvement was really slow before batch normalization. Before batch norm I was training for at least 1000 epochs before reaching anywhere near these figures.Under/Over samplingCyclic LR SchedulerStandardScaler instead of MinMaxScalerChanging optimizer from SGD to RMSProp (SGD was used the paper)
Poisson Loss: I had tried MSE and MAE (used in the paper) earlier, but both didn’t work.
Batch Normalization: The training loss improvement was really slow before batch normalization. Before batch norm I was training for at least 1000 epochs before reaching anywhere near these figures.
Under/Over sampling
Cyclic LR Scheduler
StandardScaler instead of MinMaxScaler
Changing optimizer from SGD to RMSProp (SGD was used the paper)
3. Further Improvements
There are a lot of things that could be explored and thus requires a lot of patience. Here is a non-exhaustive list:
Better Hyperparameters: Especially learning rate range and different network architecture.Try using Convolutional Neural Networks on this data. I am quite sure it will improve the results.Different node2vec embedding dimensions (we used 128).You may remember we used “average” operator to combine embeddings of both nodes. We could try other operators. In the paper, authors observe that —
Better Hyperparameters: Especially learning rate range and different network architecture.
Try using Convolutional Neural Networks on this data. I am quite sure it will improve the results.
Different node2vec embedding dimensions (we used 128).
You may remember we used “average” operator to combine embeddings of both nodes. We could try other operators. In the paper, authors observe that —
“binary operators do not have a consistent behavior over different datasets and different dimension sizes. For instance, the average operator outperforms others in Facebook graph while concatenation works better for Youtube dataset”
5. Feature selection: We could try to reduce the number of features by selecting only important features. (not used in the paper)
6. Better sampling techniques: like KMeansSMOTE, SMOTE, Cluster Centroids etc. I tried using these techniques, but they took too long to finish.
7. There is a large gap in training loss and val loss, suggesting that we could reduce the over-fitting to get a better result. Maybe try a smaller model and see if it’s capable of learning.
4. Conclusion
Well, this has already become a long post, so I will just end it without much blabbering. This has been an interesting project with lots of cool concepts to learn. I couldn’t accommodate many of them here, but I have recorded and will record more fun facts about this problem, as and when I find them, in fun.ipynb file in the project. Thanks for sticking till the end. Happy coding! | [
{
"code": null,
"e": 706,
"s": 172,
"text": "This article is an implementation of a research paper titled “Shortest Path Distance Approximation using Deep Learning Techniques”, where the authors explain a new method to approximate the shortest path distance between the nodes of a graph. I will explain the paper and my implementation of it. You can find the project on my GitHub account here. First I will give an overview of the method proposed in this paper, then we will go through some of the concepts used in this paper to solve the problem and finally the implementation."
},
{
"code": null,
"e": 1295,
"s": 706,
"text": "1.1 Motivation: Why do we need to use deep learning to approximate distance between nodes when we have traditional exact methods like Dijkstra’s and A* algorithms? The problem with these traditional algorithms is that they are slow on very large graphs and would consume a lot of memory to store the precomputed distances. And since for most of the applications an approximation of actual distance is good enough, it encourages one to explore various ways to approximate the distances. Also, once a neural network is trained, the inference time (finding node distance) is constant (O(1))."
},
{
"code": null,
"e": 2127,
"s": 1295,
"text": "1.2 Algorithm: Now that we know the ‘why’, let’s look into the ‘how’. The paper uses the ideas presented in another excellent paper “node2vec: Scalable Feature Learning for Networks”. In fact, I would say that some of the ideas used in the paper under discussion were already presented in Node2Vec paper (for instance, the use of binary operators to represent an edge using corresponding node embeddings was proposed in Node2Vec paper, which was extended to represent path in this paper. We will discuss embeddings later). This paper is more of an application of Node2Vec. The Node2Vec itself is an extension of Word2Vec. Word2Vec is an algorithm to represent words with embeddings (vector of numbers) in a vector space, such that the semantically similar words are located closer to each other. It’s a fascinating topic in itself."
},
{
"code": null,
"e": 2169,
"s": 2127,
"text": "Here is a summary of the method proposed:"
},
{
"code": null,
"e": 3012,
"s": 2169,
"text": "Collect your graph data.Use Node2Vec algorithm to find node embeddings for each node. We don’t need to write this algorithm from scratch. The authors have provided an implementation.Use a certain number of nodes in the graph as, what they call, “landmarks” and compute their distances from all the rest of the nodes. Now you have samples of form ((landmark_i, node_x), distance).For each sample found above fetch the corresponding node embeddings of the landmark and the node, and combine them with any of the suitable binary operators (average, element-wise multiplication etc.). So now you should have samples of form (embedding, distance).Now you have input-output pairs, so you do what you do best. Find a good neural net configuration and train the hell out of the model. But we will see later, as with AI in general, it’s not that easy."
},
{
"code": null,
"e": 3037,
"s": 3012,
"text": "Collect your graph data."
},
{
"code": null,
"e": 3196,
"s": 3037,
"text": "Use Node2Vec algorithm to find node embeddings for each node. We don’t need to write this algorithm from scratch. The authors have provided an implementation."
},
{
"code": null,
"e": 3394,
"s": 3196,
"text": "Use a certain number of nodes in the graph as, what they call, “landmarks” and compute their distances from all the rest of the nodes. Now you have samples of form ((landmark_i, node_x), distance)."
},
{
"code": null,
"e": 3658,
"s": 3394,
"text": "For each sample found above fetch the corresponding node embeddings of the landmark and the node, and combine them with any of the suitable binary operators (average, element-wise multiplication etc.). So now you should have samples of form (embedding, distance)."
},
{
"code": null,
"e": 3859,
"s": 3658,
"text": "Now you have input-output pairs, so you do what you do best. Find a good neural net configuration and train the hell out of the model. But we will see later, as with AI in general, it’s not that easy."
},
{
"code": null,
"e": 3894,
"s": 3859,
"text": "The project has following folders:"
},
{
"code": null,
"e": 3982,
"s": 3894,
"text": "data — which holds all the data consumed by the program, both downloaded and processed."
},
{
"code": null,
"e": 4077,
"s": 3982,
"text": "outputs —this holds all the outputs, including text logs, tensorboard logs, model backups etc."
},
{
"code": null,
"e": 4111,
"s": 4077,
"text": "src — source code is placed here."
},
{
"code": null,
"e": 4143,
"s": 4111,
"text": "tests — any relevant test cases"
},
{
"code": null,
"e": 4481,
"s": 4143,
"text": "Note: Please note that for this project I have worked on notebooks mostly because it involved a lot of exploration and experimentation with various approaches. As such, work is not polished since I am still exploring better ways. I have tried to explain the cells as much as I could. Feel free to reach out to me if something is unclear."
},
{
"code": null,
"e": 4490,
"s": 4481,
"text": "2.1 Data"
},
{
"code": null,
"e": 4650,
"s": 4490,
"text": "I have used Facebook datasets from here. The downloaded graph data is in “mtx” format. This is just another format for sharing matrix data. It looks like this:"
},
{
"code": null,
"e": 4745,
"s": 4650,
"text": "%%MatrixMarket matrix coordinate pattern symmetric6386 6386 217662195 1414 1458 1474 1510 1..."
},
{
"code": null,
"e": 6257,
"s": 4745,
"text": "The first line is called “header” and defines some properties, which are used to decide how to parse the file to form the matrix. The line below it (size line) defines the size of data. The header always begins with “%%MatrixMarket” and the four fields that follow it are object, format, field, symmetry. Object field can be ‘matrix’ or ‘vector’ (in our case it will be matrix), format can be ‘coordinate’ or ‘array’. “coordinate” format stores only non-zero values in the mtx file, so the “size line” holds, number of rows, number of columns in the matrix and the number of non-zero entries. If format is “array”, the “size line” is of form [number of rows number of columns]. The next section is “data lines”, which hold the actual data. If format is “coordinate” there would be “number of non-zero entries” number of lines of data, else in case of “array” you should expect {number of rows * number of columns} number of data lines, where each line represents an edge between two nodes. The data lines could have a 3rd column “edge weight” for weighted graphs. The rest of the details can be found in above “mtx” link. I have shared this information to get you acquainted with it a little bit so that if you face parsing errors you can write your own implementation. Most of the times we may not need to, as Scipy supports reading/writing mtx format. But here we will need to first convert mtx to edgelist format as both Networkx (the package I use to process graph data) and Node2Vec script use this format."
},
{
"code": null,
"e": 6358,
"s": 6257,
"text": "Edgelist is just the data lines after stripping away the header, comments and size lines, like this:"
},
{
"code": null,
"e": 6388,
"s": 6358,
"text": "2.2 Construct node embeddings"
},
{
"code": null,
"e": 6777,
"s": 6388,
"text": "To calculate the node embeddings for our graph we will use the script provided by Node2Vec authors. But let me first introduce the algorithm briefly, since it’s quite interesting and also because it’s such an integral part of what we are doing here. Even if we don’t have to implement the algorithm, it shouldn’t stop us from learning about it. But you can choose to skip to next section."
},
{
"code": null,
"e": 6792,
"s": 6777,
"text": "2.2.1 Node2Vec"
},
{
"code": null,
"e": 7970,
"s": 6792,
"text": "The idea is to sample the neighborhood of each node in the graph, also called a “walk” (which is a fancy way of saying: collect the nearby nodes), convert the visited nodes’ list to string (so that now you have samples of form ([list of nearby nodes as strings including source node])) and then pass all such lists to Word2Vec model to train and learn embeddings just like we train on list of sentences. But the best part of Node2Vec is how it samples the neighborhood. The authors argue that the classical approaches like BFS and DFS lie on two opposite ends of the spectrum. BFS tends to sample nodes closer to source node which causes the learned embeddings to capture structural similarity of nodes better (for e.g. whether a node acts as a hub/center in its neighborhood). But it only samples a small portion of the graph. On the other hand, DFS, tends to sample nodes far off from the source and thus learning from such ‘walks’ leads to embeddings which are better at capturing macroscopic view of graph (connectivity and “homophily” as then mention in the paper) but fail to capture finer details since walks are of finite length and they have a lot of grounds to cover."
},
{
"code": null,
"e": 8495,
"s": 7970,
"text": "Hence, they propose a new way of sampling a node’s neighborhood called “2nd order Random Walk”. Just to make it clearer, we are doing all this just to sample node neighborhood in a controlled way so that the walks include qualities of both BFS and DFS. Let’s consider a walk ‘c’ of fixed length ‘l’ and assume you have started your walk from node ‘u’. Assume that you have traveled from node t to v. Instead of choosing the next node randomly or based on the edge of weights, they use the following probability distribution:"
},
{
"code": null,
"e": 8921,
"s": 8495,
"text": "which means if previous node in the walk was v then the probability of next node being x is given by pi_{vx}/z (can’t use inline latex because Medium screws it up every time I edit something), if nodes v and x are connected by an edge, else 0. pi_{vx} is the unnormalized transition probability and z is the normalizing constant (which could be the sum of all the probabilities of edges from node v). They define pi_{vx} as :"
},
{
"code": null,
"e": 9000,
"s": 8921,
"text": "where w_{vx} is weight of edge between node v and x and $\\alpha_{pq}(t,x)$ is:"
},
{
"code": null,
"e": 9229,
"s": 9000,
"text": "where d_{tx} is the shortest path distance between t and x. Let’s understand the role of p and q, because these are the two parameters which control the nature of random walk (BFS or DFS), hence the term “2nd order Random Walk”."
},
{
"code": null,
"e": 9945,
"s": 9229,
"text": "If we recap a bit, we reached at node v from node t, and now we need to decide which node to visit next from v. If you set p to be a low value then the walk would prefer to revisit the previous nodes. How, you ask? Imagine that you have reached from t to v, now you have following options — go to other neighbors of v (x1, x2...xn) or go back to t (don’t forget ‘t’ is also a neighbor), in which case d_{tx} is zero, since x here is t itself (corresponds to the first option 1/p in the above equation). So if p is a very low value then 1/p would be quite large and random walk would prefer to go back to previous nodes and thus simulate the behavior of BFS. Please refer to the (ugly) image below to visualize this:"
},
{
"code": null,
"e": 10282,
"s": 9945,
"text": "The paper has a similar image but without distance values. Similarly, if we choose a lower value for q then we are encouraging the algorithm to venture farther away from t by assigning higher probability to 3rd option in equation defining alpha. This kind of decision is made for every node in the walk. And several such walks are done."
},
{
"code": null,
"e": 10570,
"s": 10282,
"text": "If you have understood above explanation, you have an idea of how node2vec random walk works. You can also check the implementation of it on author’s GitHub repository (but it’s in python 2 format). In my project, I have also included the author’s script but converted to Python3 format."
},
{
"code": null,
"e": 10604,
"s": 10570,
"text": "2.2.2 Running the node2vec script"
},
{
"code": null,
"e": 10769,
"s": 10604,
"text": "Running the script is quite simple. You can choose to run with all the default values for its parameters or change it to suit your needs. I ran with default values:"
},
{
"code": null,
"e": 10878,
"s": 10769,
"text": "python node2vec/main3.py --input ../data/socfb-American75.edgelist --output ../data/emb/socfb-American75.emd"
},
{
"code": null,
"e": 10918,
"s": 10878,
"text": "Just modify the input and output paths."
},
{
"code": null,
"e": 10940,
"s": 10918,
"text": "2.3 Construct Dataset"
},
{
"code": null,
"e": 11026,
"s": 10940,
"text": "From previous step we have a file with node and their embeddings in following format:"
},
{
"code": null,
"e": 11170,
"s": 11026,
"text": "6386 128224 0.3206627 -0.0963422 -0.039677385 -0.03290484 0.4414181 ....4046 -0.036134206 -0.082308784 0.49080133 -0.36878866 0.13950641 ......"
},
{
"code": null,
"e": 11577,
"s": 11170,
"text": "First two numbers represent the number of nodes and dimension of embeddings respectively. Our next step is to select a certain number of nodes in the graph as landmarks and compute their distances from all the rest of the nodes. This would give us (number of landmarks*(number of nodes-1)) number of samples. We choose landmarks because finding distances for all the nodes would require a lot more compute."
},
{
"code": null,
"e": 11787,
"s": 11577,
"text": "“distance_map” dict holds distance of every node from a given landmark (as key). Now we need to get the corresponding node2vec embedding for each node/landmark pair and combine them to form a single embedding."
},
{
"code": null,
"e": 11868,
"s": 11787,
"text": "Here emd_map is a dict which holds each node as key and it’s embedding as value."
},
{
"code": null,
"e": 12319,
"s": 11868,
"text": "Next, we need to form numpy ndarrays from embedding-distance dict like shown above. Please note two things from the output of the cell above — the number of samples is not equal to num_of_landmarks*(num_of_nodes-1). This is because I have ignored node pairs which have inf distance i.e. no path connecting them. Second, the size of training array is massive at ~927MB, since it is ‘float64’ type array. I have converted them to float32 to save space."
},
{
"code": null,
"e": 12458,
"s": 12319,
"text": "As you can see we could save ~50% space. If you are worried about the precision loss due to this conversion, you can verify the data loss:"
},
{
"code": null,
"e": 12541,
"s": 12458,
"text": "This seems insignificant. Next, let’s look at the distribution of target variable."
},
{
"code": null,
"e": 12838,
"s": 12541,
"text": "As you can see distance values 2 and 3 really dominate the data. On the graph 6, 7, 8 can’t be seen but they are present in the data, with the only sample for distance 8 which I dropped. Also note that in the paper, they ignore samples with distance value 1, but I have included them in training."
},
{
"code": null,
"e": 12914,
"s": 12838,
"text": "Since data is massively imbalanced, I have stratified the train/test split:"
},
{
"code": null,
"e": 12942,
"s": 12914,
"text": "... and then normalized it:"
},
{
"code": null,
"e": 13227,
"s": 12942,
"text": "I have saved the split data so that this preprocessing can be done once only. Whew!! Dataset formation was a big portion of this project and finally I have explained the major steps. I may have missed some, for more details you can check the data_prep.ipynb in the project repository."
},
{
"code": null,
"e": 13259,
"s": 13227,
"text": "2.4 Training the Neural Network"
},
{
"code": null,
"e": 13813,
"s": 13259,
"text": "Now comes the exciting part. The code for training is in train.ipynb file. You will notice that some of the cells look unfinished/note-to-self. I have left these deliberately to let the interested readers gain experience from my failed attempts and the steps taken after each failure. I have even uploaded the tensorboard logs (which include changes made, result, notes etc) into the GitHub repo so that all the history is available for me and others to follow later. If you are not interested in the logs, you can delete the folders without any issues."
},
{
"code": null,
"e": 13968,
"s": 13813,
"text": "Since the data is skewed, I had to oversample the minority target values (I am not using the term “class” here because I have trained a regression model)."
},
{
"code": null,
"e": 14647,
"s": 13968,
"text": "I have first undersampled the majority values and then oversampled the minority values. The intuition was to oversample the minority distance values to make them comparable to number of samples of majority values, while keeping the overall data size as small as possible. The fraction values “0.7” is not really calculated/derived from anywhere, it just seemed reasonable by looking at the frequencies of each distance values. And yes... don’t forget to shuffle the data after over/under sampling. It may seem like a trivial thing, something you can ignore but as it turned out many of the batches had same distance values (like all 1s or 2s etc) which made training impossible!"
},
{
"code": null,
"e": 14756,
"s": 14647,
"text": "Now, let’s define a baseline, a simple model and it’s result to which we can compare to see how good we did:"
},
{
"code": null,
"e": 14905,
"s": 14756,
"text": "Linear Regression does surprisingly good! 50% is a good baseline to compare with, considering that the chance prediction in this case is ~14% (1/7)."
},
{
"code": null,
"e": 14919,
"s": 14905,
"text": "PyTroch Model"
},
{
"code": null,
"e": 15870,
"s": 14919,
"text": "For all of my previous projects, I had used Keras but recently I switched to PyTorch and I haven’t regretted it ever since. I was working on another project which involved writing a custom loss function which required some calculations on output of intermediate layer of the model and other custom stuffs. If you have ever tried such things with Keras, you know it’s not straightforward. Even with eager execution I couldn’t get it to work. To make matters worse, one fine day, Keras started throwing CUDA compatibility errors, and it wouldn’t go away no matter how many times I built a new environment with required drivers. This was my breaking point. With PyTorch you may have to write a little bit of extra code for training loop but it’s worth it. Now, I am not saying these issues couldn’t have been solved with more effort, but, in a world where you have PyTorch, why break your head? So that concludes my rant about why I switched to PyTorch."
},
{
"code": null,
"e": 16157,
"s": 15870,
"text": "But for readers who are not acquainted with PyTorch, don’t be disheartened. Almost all the components used are available in Keras (except for may be Cyclic LR scheduler, but there are implementations of it that you can use). Explaining PyTorch would be out of the scope of this article."
},
{
"code": null,
"e": 16292,
"s": 16157,
"text": "The model which gave the best result (yet) has following configuration (with Cyclic LR Scheduler, RMSProp optimizer and Poisson Loss):"
},
{
"code": null,
"e": 16585,
"s": 16292,
"text": "{'batch_size': 1000, 'input_size': 128, 'hidden_units_1': 200, 'hidden_units_2': 100, 'hidden_units_3': 50, 'do_1': 0.2, 'do_2': 0.1, 'do_3': 0.05, 'output_size': 1, 'lr': 0.001, 'min_lr': 1e-05, 'max_lr': 0.001, 'epochs': 500, 'lr_sched': 'clr', 'lr_sched_mode': 'triangular', 'gamma': 0.95}"
},
{
"code": null,
"e": 16674,
"s": 16585,
"text": "It’s a 5 layer (3 hidden layers) model with dropouts, trained with cyclic learning rate."
},
{
"code": null,
"e": 17074,
"s": 16674,
"text": "You may not find this model in the GitHub code if I have tried other configurations after this and thus parameters could have changed. But you could find the corresponding model and parameters in run47 folder. Please note that this configuration is different from what they have mentioned in the paper. As with almost every other paper I have read, they have skipped the low level details of the NN."
},
{
"code": null,
"e": 17139,
"s": 17074,
"text": "Here is how you initialize Data Loaders for train/val/test data:"
},
{
"code": null,
"e": 17178,
"s": 17139,
"text": "Now we are all set to train the model:"
},
{
"code": null,
"e": 17630,
"s": 17178,
"text": "People who have only worked on Keras/Fastai yet, don’t get scared. Code to train PyTorch model is not always this big. I am doing a lot of other stuff like early stopping, checkpoint saves etc. It’s definitely more complicated than Keras, but nothing you can’t learn in a day or two. But like I have mentioned before all these components are already there in Keras (including Poisson Loss) so you can easily try it out on the framework of your choice."
},
{
"code": null,
"e": 17667,
"s": 17630,
"text": "I trained the model for ~110 epochs."
},
{
"code": null,
"e": 17689,
"s": 17667,
"text": "Here are the results:"
},
{
"code": null,
"e": 17818,
"s": 17689,
"text": "Poisson Loss = -0.11MAE Loss = 0.32MSE Loss = 0.17Accuracy = 76.40% vsBaseline :MAE Loss = 0.59 MSE Loss = 0.56Accuracy = 50.57%"
},
{
"code": null,
"e": 18118,
"s": 17818,
"text": "Although this was a regression problem, I have still recorded accuracy because I find it more intuitive (it’s not a metric, just something I used to compare models). It’s not a boastful result but it’s not bad. Also, I think, there is lot of margin for more improvements, which I will mention later."
},
{
"code": null,
"e": 18264,
"s": 18118,
"text": "If you are wondering why does longer path distances have worse accuracy, similar observations were made by authors as well. Here’s what they say:"
},
{
"code": null,
"e": 18515,
"s": 18264,
"text": "Observe that the larger errors caused by longer paths utilizing node2vec embeddings. In one hand, we do not have enough samples for longer distances in the training set. On the other hand, node2vec fails to learn structural features of faraway nodes."
},
{
"code": null,
"e": 18849,
"s": 18515,
"text": "Note: There is one thing that’s bugging me about this model. Despite using exp_range as CLR mode, the learning rate didn’t change throughout the training (at least as per the plot). This happens for gamma value 0.95 always. Need to look into it. Or if you have faced this before and have any solutions, you are welcome to share here."
},
{
"code": null,
"e": 18929,
"s": 18849,
"text": "In retrospect, here are some of the things that improved the model performance:"
},
{
"code": null,
"e": 19354,
"s": 18929,
"text": "Poisson Loss: I had tried MSE and MAE (used in the paper) earlier, but both didn’t work.Batch Normalization: The training loss improvement was really slow before batch normalization. Before batch norm I was training for at least 1000 epochs before reaching anywhere near these figures.Under/Over samplingCyclic LR SchedulerStandardScaler instead of MinMaxScalerChanging optimizer from SGD to RMSProp (SGD was used the paper)"
},
{
"code": null,
"e": 19443,
"s": 19354,
"text": "Poisson Loss: I had tried MSE and MAE (used in the paper) earlier, but both didn’t work."
},
{
"code": null,
"e": 19641,
"s": 19443,
"text": "Batch Normalization: The training loss improvement was really slow before batch normalization. Before batch norm I was training for at least 1000 epochs before reaching anywhere near these figures."
},
{
"code": null,
"e": 19661,
"s": 19641,
"text": "Under/Over sampling"
},
{
"code": null,
"e": 19681,
"s": 19661,
"text": "Cyclic LR Scheduler"
},
{
"code": null,
"e": 19720,
"s": 19681,
"text": "StandardScaler instead of MinMaxScaler"
},
{
"code": null,
"e": 19784,
"s": 19720,
"text": "Changing optimizer from SGD to RMSProp (SGD was used the paper)"
},
{
"code": null,
"e": 19808,
"s": 19784,
"text": "3. Further Improvements"
},
{
"code": null,
"e": 19925,
"s": 19808,
"text": "There are a lot of things that could be explored and thus requires a lot of patience. Here is a non-exhaustive list:"
},
{
"code": null,
"e": 20315,
"s": 19925,
"text": "Better Hyperparameters: Especially learning rate range and different network architecture.Try using Convolutional Neural Networks on this data. I am quite sure it will improve the results.Different node2vec embedding dimensions (we used 128).You may remember we used “average” operator to combine embeddings of both nodes. We could try other operators. In the paper, authors observe that —"
},
{
"code": null,
"e": 20406,
"s": 20315,
"text": "Better Hyperparameters: Especially learning rate range and different network architecture."
},
{
"code": null,
"e": 20505,
"s": 20406,
"text": "Try using Convolutional Neural Networks on this data. I am quite sure it will improve the results."
},
{
"code": null,
"e": 20560,
"s": 20505,
"text": "Different node2vec embedding dimensions (we used 128)."
},
{
"code": null,
"e": 20708,
"s": 20560,
"text": "You may remember we used “average” operator to combine embeddings of both nodes. We could try other operators. In the paper, authors observe that —"
},
{
"code": null,
"e": 20941,
"s": 20708,
"text": "“binary operators do not have a consistent behavior over different datasets and different dimension sizes. For instance, the average operator outperforms others in Facebook graph while concatenation works better for Youtube dataset”"
},
{
"code": null,
"e": 21071,
"s": 20941,
"text": "5. Feature selection: We could try to reduce the number of features by selecting only important features. (not used in the paper)"
},
{
"code": null,
"e": 21216,
"s": 21071,
"text": "6. Better sampling techniques: like KMeansSMOTE, SMOTE, Cluster Centroids etc. I tried using these techniques, but they took too long to finish."
},
{
"code": null,
"e": 21407,
"s": 21216,
"text": "7. There is a large gap in training loss and val loss, suggesting that we could reduce the over-fitting to get a better result. Maybe try a smaller model and see if it’s capable of learning."
},
{
"code": null,
"e": 21421,
"s": 21407,
"text": "4. Conclusion"
}
]
|
How to create a random sample of values between 0 and 1 in R? | The continuous uniform distribution can take values between 0 and 1 in R if the range is not defined. To create a random sample of continuous uniform distribution we can use runif function, if we will not pass the minimum and maximum values the default will be 0 and 1 and we can also use different range of values.
runif(5)
[1] 0.8667731 0.7109824 0.4466423 0.1644701 0.5611908
runif(10)
[1] 0.5923782 0.8793613 0.6912947 0.2963916 0.6076762 0.7683766 0.1143595
[8] 0.4782710 0.1143383 0.4540217
runif(50)
[1] 0.841674685 0.325249762 0.640847906 0.203868249 0.495230429 0.897175830
[7] 0.744447459 0.490173680 0.254711280 0.144844443 0.867749180 0.004405166
[13] 0.539785687 0.739637398 0.062214554 0.648021581 0.768686809 0.305543906
[19] 0.757496413 0.527085302 0.633331579 0.700118363 0.857950259 0.929350618
[25] 0.167015719 0.775870043 0.430343200 0.528408273 0.600575697 0.612206968
[31] 0.065904791 0.061135682 0.082027863 0.193586800 0.013956337 0.156875620
[37] 0.837501421 0.971202297 0.930835689 0.292126061 0.599263353 0.826630821
[43] 0.509235736 0.741715013 0.224485511 0.113099235 0.395143355 0.375654137
[49] 0.973050494 0.107550270
round(runif(50),2)
[1] 0.51 0.70 0.90 0.45 0.41 0.74 0.31 0.40 0.10 0.05 0.18 0.05 0.63 0.34 0.57
[16] 0.06 0.73 0.37 0.79 0.85 0.82 0.41 0.32 0.34 0.37 0.14 0.21 0.11 0.43 0.86
[31] 0.83 0.09 0.88 0.04 0.62 0.64 0.15 0.75 0.78 0.16 0.67 0.97 0.79 0.64 0.56
[46] 0.40 0.07 0.69 0.82 0.63
round(runif(50),4)
[1] 0.2951 0.2916 0.9049 0.2669 0.7613 0.2080 0.4739 0.1110 0.6155 0.5429
[11] 0.4490 0.2941 0.8262 0.7719 0.7896 0.7634 0.6260 0.7812 0.7600 0.6852
[21] 0.9142 0.0165 0.2324 0.0821 0.0814 0.4009 0.3315 0.8843 0.9684 0.1966
[31] 0.4841 0.5795 0.7898 0.1865 0.6929 0.8599 0.0492 0.8275 0.7431 0.3122
[41] 0.8480 0.3327 0.4872 0.0503 0.1887 0.0296 0.6011 0.1162 0.7776 0.6874
round(runif(50),5)
[1] 0.40368 0.33585 0.03557 0.06047 0.95041 0.18260 0.70011 0.75148 0.12414
[10] 0.01310 0.42343 0.05846 0.21341 0.05454 0.77823 0.66151 0.61406 0.59459
[19] 0.50299 0.96780 0.43033 0.64652 0.39697 0.05897 0.47169 0.79828 0.74154
[28] 0.56074 0.97303 0.35301 0.36110 0.67452 0.14553 0.45195 0.05780 0.90489
[37] 0.96745 0.28014 0.02089 0.77789 0.04797 0.03550 0.40495 0.08924 0.59908
[46] 0.89074 0.48498 0.47335 0.59422 0.00719
round(runif(100),2)
[1] 0.10 0.06 0.51 0.89 0.80 0.68 0.97 0.58 0.60 0.79 0.96 0.48 0.29 0.16 0.42
[16] 0.35 0.46 0.18 0.46 0.34 0.48 0.35 0.72 0.10 0.50 0.93 0.30 0.54 0.85 0.19
[31] 0.12 0.10 0.47 0.66 0.43 0.09 0.44 0.86 0.99 0.31 0.10 0.61 0.20 0.15 0.02
[46] 0.25 0.33 0.75 0.98 0.23 0.21 0.70 0.42 0.24 0.87 0.84 0.99 0.06 0.75 0.48
[61] 0.84 0.35 0.48 0.62 0.40 0.25 0.07 0.08 0.75 0.40 0.83 0.95 0.00 0.87 0.27
[76] 0.53 0.21 0.41 0.28 0.83 0.90 0.26 0.50 0.19 0.70 0.93 0.24 0.45 0.33 0.84
[91] 0.15 0.81 0.62 0.17 0.08 0.76 0.74 0.11 0.20 0.49
round(runif(150),1)
[1] 0.6 0.3 0.3 0.3 0.9 0.7 0.1 0.1 0.1 0.9 0.4 0.6 1.0 0.0 0.4 1.0 0.1 1.0
[19] 0.8 0.0 0.9 0.9 0.7 0.7 0.7 0.7 0.3 0.7 0.1 0.1 0.9 0.0 0.1 1.0 0.9 1.0
[37] 0.9 0.6 0.0 0.4 0.4 1.0 0.2 0.4 0.2 0.8 0.3 0.9 0.8 0.6 0.3 0.3 0.4 0.7
[55] 0.2 0.9 1.0 0.9 0.8 0.7 0.9 1.0 0.5 0.8 0.6 0.8 0.6 0.8 0.3 0.3 1.0 0.6
[73] 0.9 0.3 0.0 1.0 0.5 0.6 0.7 0.7 0.6 0.3 0.4 0.0 0.3 0.1 0.6 0.2 0.1 0.7
[91] 0.9 0.8 0.3 0.2 0.5 0.6 0.6 0.1 0.0 0.9 0.4 0.6 0.3 0.2 0.9 0.6 0.0 0.2
[109] 0.3 0.3 0.3 0.7 0.4 0.8 0.5 0.9 0.6 0.5 0.3 1.0 0.6 0.7 0.9 0.1 0.8 1.0
[127] 0.3 1.0 0.2 0.9 0.2 0.3 0.5 0.4 0.1 0.6 0.6 0.0 0.3 0.3 0.0 0.3 0.3 1.0
[145] 0.6 0.5 0.1 0.7 0.6 0.4
round(runif(75),1)
[1] 0.7 0.3 0.7 0.9 0.8 0.1 0.4 0.2 0.5 0.4 0.1 0.7 0.1 0.6 1.0 0.3 0.4 0.7 0.2
[20] 0.2 0.3 0.4 0.4 0.0 0.1 0.2 0.3 0.5 0.1 1.0 0.3 0.5 0.3 0.7 0.1 0.6 0.6 0.6
[39] 0.5 0.7 0.5 0.8 0.1 1.0 0.7 0.4 0.6 0.1 0.5 0.5 0.9 0.3 0.8 0.9 0.3 0.9 0.7
[58] 0.6 0.8 0.4 0.4 0.7 0.4 0.1 0.2 0.6 0.6 0.9 0.3 0.6 0.5 0.9 0.2 0.3 0.2
round(runif(75),3)
[1] 0.712 0.355 0.130 0.768 0.134 0.681 0.273 0.663 0.849 0.851 0.842 0.430
[13] 0.371 0.903 0.148 0.879 0.812 0.330 0.567 0.646 0.199 0.159 0.056 0.448
[25] 0.637 0.204 0.101 0.389 0.797 0.030 0.021 0.167 0.440 0.359 0.670 0.435
[37] 0.807 0.669 0.738 0.546 0.535 0.969 0.055 0.201 0.436 0.336 0.841 0.548
[49] 0.901 0.850 0.369 0.770 0.678 0.922 0.252 0.132 0.635 0.544 0.291 0.715
[61] 0.601 0.399 0.585 0.161 0.423 0.244 0.451 0.397 0.951 0.382 0.123 0.959
[73] 0.252 0.330 0.238 | [
{
"code": null,
"e": 1378,
"s": 1062,
"text": "The continuous uniform distribution can take values between 0 and 1 in R if the range is not defined. To create a random sample of continuous uniform distribution we can use runif function, if we will not pass the minimum and maximum values the default will be 0 and 1 and we can also use different range of values."
},
{
"code": null,
"e": 5403,
"s": 1378,
"text": "runif(5)\n[1] 0.8667731 0.7109824 0.4466423 0.1644701 0.5611908\nrunif(10)\n[1] 0.5923782 0.8793613 0.6912947 0.2963916 0.6076762 0.7683766 0.1143595\n[8] 0.4782710 0.1143383 0.4540217\nrunif(50)\n[1] 0.841674685 0.325249762 0.640847906 0.203868249 0.495230429 0.897175830\n[7] 0.744447459 0.490173680 0.254711280 0.144844443 0.867749180 0.004405166\n[13] 0.539785687 0.739637398 0.062214554 0.648021581 0.768686809 0.305543906\n[19] 0.757496413 0.527085302 0.633331579 0.700118363 0.857950259 0.929350618\n[25] 0.167015719 0.775870043 0.430343200 0.528408273 0.600575697 0.612206968\n[31] 0.065904791 0.061135682 0.082027863 0.193586800 0.013956337 0.156875620\n[37] 0.837501421 0.971202297 0.930835689 0.292126061 0.599263353 0.826630821\n[43] 0.509235736 0.741715013 0.224485511 0.113099235 0.395143355 0.375654137\n[49] 0.973050494 0.107550270\nround(runif(50),2)\n[1] 0.51 0.70 0.90 0.45 0.41 0.74 0.31 0.40 0.10 0.05 0.18 0.05 0.63 0.34 0.57\n[16] 0.06 0.73 0.37 0.79 0.85 0.82 0.41 0.32 0.34 0.37 0.14 0.21 0.11 0.43 0.86\n[31] 0.83 0.09 0.88 0.04 0.62 0.64 0.15 0.75 0.78 0.16 0.67 0.97 0.79 0.64 0.56\n[46] 0.40 0.07 0.69 0.82 0.63\nround(runif(50),4)\n[1] 0.2951 0.2916 0.9049 0.2669 0.7613 0.2080 0.4739 0.1110 0.6155 0.5429\n[11] 0.4490 0.2941 0.8262 0.7719 0.7896 0.7634 0.6260 0.7812 0.7600 0.6852\n[21] 0.9142 0.0165 0.2324 0.0821 0.0814 0.4009 0.3315 0.8843 0.9684 0.1966\n[31] 0.4841 0.5795 0.7898 0.1865 0.6929 0.8599 0.0492 0.8275 0.7431 0.3122\n[41] 0.8480 0.3327 0.4872 0.0503 0.1887 0.0296 0.6011 0.1162 0.7776 0.6874\nround(runif(50),5)\n[1] 0.40368 0.33585 0.03557 0.06047 0.95041 0.18260 0.70011 0.75148 0.12414\n[10] 0.01310 0.42343 0.05846 0.21341 0.05454 0.77823 0.66151 0.61406 0.59459\n[19] 0.50299 0.96780 0.43033 0.64652 0.39697 0.05897 0.47169 0.79828 0.74154\n[28] 0.56074 0.97303 0.35301 0.36110 0.67452 0.14553 0.45195 0.05780 0.90489\n[37] 0.96745 0.28014 0.02089 0.77789 0.04797 0.03550 0.40495 0.08924 0.59908\n[46] 0.89074 0.48498 0.47335 0.59422 0.00719\nround(runif(100),2)\n[1] 0.10 0.06 0.51 0.89 0.80 0.68 0.97 0.58 0.60 0.79 0.96 0.48 0.29 0.16 0.42\n[16] 0.35 0.46 0.18 0.46 0.34 0.48 0.35 0.72 0.10 0.50 0.93 0.30 0.54 0.85 0.19\n[31] 0.12 0.10 0.47 0.66 0.43 0.09 0.44 0.86 0.99 0.31 0.10 0.61 0.20 0.15 0.02\n[46] 0.25 0.33 0.75 0.98 0.23 0.21 0.70 0.42 0.24 0.87 0.84 0.99 0.06 0.75 0.48\n[61] 0.84 0.35 0.48 0.62 0.40 0.25 0.07 0.08 0.75 0.40 0.83 0.95 0.00 0.87 0.27\n[76] 0.53 0.21 0.41 0.28 0.83 0.90 0.26 0.50 0.19 0.70 0.93 0.24 0.45 0.33 0.84\n[91] 0.15 0.81 0.62 0.17 0.08 0.76 0.74 0.11 0.20 0.49\nround(runif(150),1)\n[1] 0.6 0.3 0.3 0.3 0.9 0.7 0.1 0.1 0.1 0.9 0.4 0.6 1.0 0.0 0.4 1.0 0.1 1.0\n[19] 0.8 0.0 0.9 0.9 0.7 0.7 0.7 0.7 0.3 0.7 0.1 0.1 0.9 0.0 0.1 1.0 0.9 1.0\n[37] 0.9 0.6 0.0 0.4 0.4 1.0 0.2 0.4 0.2 0.8 0.3 0.9 0.8 0.6 0.3 0.3 0.4 0.7\n[55] 0.2 0.9 1.0 0.9 0.8 0.7 0.9 1.0 0.5 0.8 0.6 0.8 0.6 0.8 0.3 0.3 1.0 0.6\n[73] 0.9 0.3 0.0 1.0 0.5 0.6 0.7 0.7 0.6 0.3 0.4 0.0 0.3 0.1 0.6 0.2 0.1 0.7\n[91] 0.9 0.8 0.3 0.2 0.5 0.6 0.6 0.1 0.0 0.9 0.4 0.6 0.3 0.2 0.9 0.6 0.0 0.2\n[109] 0.3 0.3 0.3 0.7 0.4 0.8 0.5 0.9 0.6 0.5 0.3 1.0 0.6 0.7 0.9 0.1 0.8 1.0\n[127] 0.3 1.0 0.2 0.9 0.2 0.3 0.5 0.4 0.1 0.6 0.6 0.0 0.3 0.3 0.0 0.3 0.3 1.0\n[145] 0.6 0.5 0.1 0.7 0.6 0.4\nround(runif(75),1)\n[1] 0.7 0.3 0.7 0.9 0.8 0.1 0.4 0.2 0.5 0.4 0.1 0.7 0.1 0.6 1.0 0.3 0.4 0.7 0.2\n[20] 0.2 0.3 0.4 0.4 0.0 0.1 0.2 0.3 0.5 0.1 1.0 0.3 0.5 0.3 0.7 0.1 0.6 0.6 0.6\n[39] 0.5 0.7 0.5 0.8 0.1 1.0 0.7 0.4 0.6 0.1 0.5 0.5 0.9 0.3 0.8 0.9 0.3 0.9 0.7\n[58] 0.6 0.8 0.4 0.4 0.7 0.4 0.1 0.2 0.6 0.6 0.9 0.3 0.6 0.5 0.9 0.2 0.3 0.2\nround(runif(75),3)\n[1] 0.712 0.355 0.130 0.768 0.134 0.681 0.273 0.663 0.849 0.851 0.842 0.430\n[13] 0.371 0.903 0.148 0.879 0.812 0.330 0.567 0.646 0.199 0.159 0.056 0.448\n[25] 0.637 0.204 0.101 0.389 0.797 0.030 0.021 0.167 0.440 0.359 0.670 0.435\n[37] 0.807 0.669 0.738 0.546 0.535 0.969 0.055 0.201 0.436 0.336 0.841 0.548\n[49] 0.901 0.850 0.369 0.770 0.678 0.922 0.252 0.132 0.635 0.544 0.291 0.715\n[61] 0.601 0.399 0.585 0.161 0.423 0.244 0.451 0.397 0.951 0.382 0.123 0.959\n[73] 0.252 0.330 0.238"
}
]
|
Back Propagation, the Easy Way (Part 2) | by Ziad SALLOUM | Towards Data Science | Update: The best way of learning and practicing Reinforcement Learning is by going to http://rl-lab.com
In the first part we have seen how back propagation is derived in a way to minimize the cost function. In this article we will see the implementation aspect, and some best practices to avoid common pitfalls.
We are still in the simple mode, where input is handled one at a time.
Consider a fully connected neural network such as in the figure below.
Each layer will be modelled by a Layer object containing the weights, the activation values (output of the layer), the gradient dZ (not represented in the image), the cumulative error delta (Δ), as well as the activation function f(x) and its derivative f’(x). The reason for storing intermediate is to avoid computing them each time they are needed.
Advice: It is better to organize the code around few classes, and avoid cramming everything into arrays, as it is very easy to get lost.
Note that the input layer won’t be represented by a Layer object since it consists only of a vector.
class Layer: def __init__(self, dim, id, act, act_prime, isoutputLayer = False): self.weight = 2 * np.random.random(dim) - 1 self.delta = None self.A = None self.activation = act self.activation_prime = act_prime self.isoutputLayer = isoutputLayer self.id = id
The constructor of the Layer class, takes as parameters:
dim: dimensions of the weight matrix,
id: integer as id of the layer,
act, act_prime: the activation function and its derivative,
isoutputlayer: True if this layer is the output, False otherwise.
It initializes the weights randomly to numbers between -1 and +1, and set the different variables to be used inside the object.
The layer object has three methods:
forward, to compute the layer output.
backward, to propagate the error between the target and the output back to the newtwork.
update, to update the weights according to a gradient descent.
def forward(self, x): z = np.dot(x, self.weight) self.A = self.activation(z) self.dZ = self.activation_prime(z);
The forward function, computes and returns the output of the Layer, by taking the input x and computes and stores the output A = activation (W.X). It also computes and stores dZ which the derivative of the output relative to the input.
The backward functions takes two parameters, the target y and rightLayer which is the layer (l-1) assuming that the current one is l.
It computes the cumulative error delta that is propagating from the output going leftward to the beginning of the network.
IMPORTANT: a common mistake, is to think that the backward propagation is some kind of loopback in which the output is injected again in the network. So instead of using dZ = self.activation_prime(z); some uses self.activation_prime(A). This is wrong, simply because what we are trying to do is figure out how the output A would vary relative to input z. This means computing the derivative ∂a/∂z = ∂g(z)/∂z = g’(z) according to the chain rule.This error might be due to the fact that in the case of sigmoid activation function a = σ(z), the derivative σ’(z) = σ(z)*(1-σ(z)) = a*(1-a). Which gives the illusion that the output is injected into to the network, while the truth is that we are computing σ’(z).
def backward(self, y, rightLayer): if self.isoutputLayer: error = self.A - y self.delta = np.atleast_2d(error * self.dZ) else: self.delta = np.atleast_2d( rightLayer.delta.dot(rightLayer.weight.T) * self.dZ) return self.delta
What the backward function does is to compute and return the delta, based on the formula:
Finally the update function uses the gradient descent to update the weights of the current layer.
def update(self, learning_rate, left_a): a = np.atleast_2d(left_a) d = np.atleast_2d(self.delta) ad = a.T.dot(d) self.weight -= learning_rate * ad
As one might guess layers form a network, so the class NeuralNetwork is used to organize and coordinate the layers.It’s constructor takes the configuration of the layers that is an array which length determines the number of layers in the network and each element defines the number of nodes in the corresponding layer. For example [2, 4, 5, ] means that the network has 4 layers with the input layer having 2 nodes, the next hidden layers have 4 and 5 nodes respectively and the output layer has 1 node. The second parameter is the type of activation function to use for all layers.
The fit function is where all the training happens. It starts by selecting one input sample, computes the forward over all the layers, then computes the error between the output of the network and the target value and propagate this error to the network by calling backward function of each layer in reverse order, starting by the last one up to the first.Finally, the update function is called for each layer to update the weights.
These steps are repeated a number of times determined by the parameter epoch.
After the training is complete, the predict function can be called to test input. The predict function is simply a feed forward of all the network.
class NeuralNetwork: def __init__(self, layersDim, activation='tanh'): if activation == 'sigmoid': self.activation = sigmoid self.activation_prime = sigmoid_prime elif activation == 'tanh': self.activation = tanh self.activation_prime = tanh_prime elif activation == 'relu': self.activation = relu self.activation_prime = relu_prime self.layers = [] for i in range(1, len(layersDim) - 1): dim = (layersDim[i - 1] + 1, layersDim[i] + 1) self.layers.append(Layer(dim, i, self.activation, self.activation_prime)) dim = (layersDim[i] + 1, layersDim[i + 1]) self.layers.append(Layer(dim, len(layersDim) - 1, self.activation, self.activation_prime, True))# train the network def fit(self, X, y, learning_rate=0.1, epochs=10000): # Add column of ones to X # This is to add the bias unit to the input layer ones = np.atleast_2d(np.ones(X.shape[0])) X = np.concatenate((ones.T, X), axis=1) for k in range(epochs): i = np.random.randint(X.shape[0]) a = X[i] # compute the feed forward for l in range(len(self.layers)): a = self.layers[l].forward(a) # compute the backward propagation delta = self.layers[-1].backward(y[i], None) for l in range(len(self.layers) - 2, -1, -1): delta = self.layers[l].backward(delta, self.layers[l+1]) # update weights a = X[i] for layer in self.layers: layer.update(learning_rate, a) a = layer.A# predict input def predict(self, x): a = np.concatenate((np.ones(1).T, np.array(x)), axis=0) for l in range(0, len(self.layers)): a = self.layers[l].forward(a) return a
To run the network we take as example the approximation of the Xor function.
We try the several network configurations, using different learning rates and epoch iterations. Results are liste below:
Result with tanh[0 0] [-0.00011187][0 1] [ 0.98090146][1 0] [ 0.97569382][1 1] [ 0.00128179]Result with sigmoid[0 0] [ 0.01958287][0 1] [ 0.96476513][1 0] [ 0.97699611][1 1] [ 0.05132127]Result with relu[0 0] [ 0.][0 1] [ 1.][1 0] [ 1.][1 1] [ 4.23272528e-16]
It is advisable that you try different configurations and see for yourself which one gives the best and most stable results.
The full code can be downloaded here.
Back propagation can be confusing and tricky to implement. You might have the illusion that you get a grasp of it through the theory, but the truth is that when implementing it, it is easy to fall into many traps. You should be patient and persistent, as back propagation is a corner stone of Neural Networks.
Part 1: Simple detailed explanation of the back propagationPart 3: How to handle dimensions of matrices | [
{
"code": null,
"e": 276,
"s": 172,
"text": "Update: The best way of learning and practicing Reinforcement Learning is by going to http://rl-lab.com"
},
{
"code": null,
"e": 484,
"s": 276,
"text": "In the first part we have seen how back propagation is derived in a way to minimize the cost function. In this article we will see the implementation aspect, and some best practices to avoid common pitfalls."
},
{
"code": null,
"e": 555,
"s": 484,
"text": "We are still in the simple mode, where input is handled one at a time."
},
{
"code": null,
"e": 626,
"s": 555,
"text": "Consider a fully connected neural network such as in the figure below."
},
{
"code": null,
"e": 977,
"s": 626,
"text": "Each layer will be modelled by a Layer object containing the weights, the activation values (output of the layer), the gradient dZ (not represented in the image), the cumulative error delta (Δ), as well as the activation function f(x) and its derivative f’(x). The reason for storing intermediate is to avoid computing them each time they are needed."
},
{
"code": null,
"e": 1114,
"s": 977,
"text": "Advice: It is better to organize the code around few classes, and avoid cramming everything into arrays, as it is very easy to get lost."
},
{
"code": null,
"e": 1215,
"s": 1114,
"text": "Note that the input layer won’t be represented by a Layer object since it consists only of a vector."
},
{
"code": null,
"e": 1545,
"s": 1215,
"text": "class Layer: def __init__(self, dim, id, act, act_prime, isoutputLayer = False): self.weight = 2 * np.random.random(dim) - 1 self.delta = None self.A = None self.activation = act self.activation_prime = act_prime self.isoutputLayer = isoutputLayer self.id = id"
},
{
"code": null,
"e": 1602,
"s": 1545,
"text": "The constructor of the Layer class, takes as parameters:"
},
{
"code": null,
"e": 1640,
"s": 1602,
"text": "dim: dimensions of the weight matrix,"
},
{
"code": null,
"e": 1672,
"s": 1640,
"text": "id: integer as id of the layer,"
},
{
"code": null,
"e": 1732,
"s": 1672,
"text": "act, act_prime: the activation function and its derivative,"
},
{
"code": null,
"e": 1798,
"s": 1732,
"text": "isoutputlayer: True if this layer is the output, False otherwise."
},
{
"code": null,
"e": 1926,
"s": 1798,
"text": "It initializes the weights randomly to numbers between -1 and +1, and set the different variables to be used inside the object."
},
{
"code": null,
"e": 1962,
"s": 1926,
"text": "The layer object has three methods:"
},
{
"code": null,
"e": 2000,
"s": 1962,
"text": "forward, to compute the layer output."
},
{
"code": null,
"e": 2089,
"s": 2000,
"text": "backward, to propagate the error between the target and the output back to the newtwork."
},
{
"code": null,
"e": 2152,
"s": 2089,
"text": "update, to update the weights according to a gradient descent."
},
{
"code": null,
"e": 2274,
"s": 2152,
"text": "def forward(self, x): z = np.dot(x, self.weight) self.A = self.activation(z) self.dZ = self.activation_prime(z);"
},
{
"code": null,
"e": 2510,
"s": 2274,
"text": "The forward function, computes and returns the output of the Layer, by taking the input x and computes and stores the output A = activation (W.X). It also computes and stores dZ which the derivative of the output relative to the input."
},
{
"code": null,
"e": 2644,
"s": 2510,
"text": "The backward functions takes two parameters, the target y and rightLayer which is the layer (l-1) assuming that the current one is l."
},
{
"code": null,
"e": 2767,
"s": 2644,
"text": "It computes the cumulative error delta that is propagating from the output going leftward to the beginning of the network."
},
{
"code": null,
"e": 3475,
"s": 2767,
"text": "IMPORTANT: a common mistake, is to think that the backward propagation is some kind of loopback in which the output is injected again in the network. So instead of using dZ = self.activation_prime(z); some uses self.activation_prime(A). This is wrong, simply because what we are trying to do is figure out how the output A would vary relative to input z. This means computing the derivative ∂a/∂z = ∂g(z)/∂z = g’(z) according to the chain rule.This error might be due to the fact that in the case of sigmoid activation function a = σ(z), the derivative σ’(z) = σ(z)*(1-σ(z)) = a*(1-a). Which gives the illusion that the output is injected into to the network, while the truth is that we are computing σ’(z)."
},
{
"code": null,
"e": 3754,
"s": 3475,
"text": "def backward(self, y, rightLayer): if self.isoutputLayer: error = self.A - y self.delta = np.atleast_2d(error * self.dZ) else: self.delta = np.atleast_2d( rightLayer.delta.dot(rightLayer.weight.T) * self.dZ) return self.delta"
},
{
"code": null,
"e": 3844,
"s": 3754,
"text": "What the backward function does is to compute and return the delta, based on the formula:"
},
{
"code": null,
"e": 3942,
"s": 3844,
"text": "Finally the update function uses the gradient descent to update the weights of the current layer."
},
{
"code": null,
"e": 4101,
"s": 3942,
"text": "def update(self, learning_rate, left_a): a = np.atleast_2d(left_a) d = np.atleast_2d(self.delta) ad = a.T.dot(d) self.weight -= learning_rate * ad"
},
{
"code": null,
"e": 4685,
"s": 4101,
"text": "As one might guess layers form a network, so the class NeuralNetwork is used to organize and coordinate the layers.It’s constructor takes the configuration of the layers that is an array which length determines the number of layers in the network and each element defines the number of nodes in the corresponding layer. For example [2, 4, 5, ] means that the network has 4 layers with the input layer having 2 nodes, the next hidden layers have 4 and 5 nodes respectively and the output layer has 1 node. The second parameter is the type of activation function to use for all layers."
},
{
"code": null,
"e": 5118,
"s": 4685,
"text": "The fit function is where all the training happens. It starts by selecting one input sample, computes the forward over all the layers, then computes the error between the output of the network and the target value and propagate this error to the network by calling backward function of each layer in reverse order, starting by the last one up to the first.Finally, the update function is called for each layer to update the weights."
},
{
"code": null,
"e": 5196,
"s": 5118,
"text": "These steps are repeated a number of times determined by the parameter epoch."
},
{
"code": null,
"e": 5344,
"s": 5196,
"text": "After the training is complete, the predict function can be called to test input. The predict function is simply a feed forward of all the network."
},
{
"code": null,
"e": 7213,
"s": 5344,
"text": "class NeuralNetwork: def __init__(self, layersDim, activation='tanh'): if activation == 'sigmoid': self.activation = sigmoid self.activation_prime = sigmoid_prime elif activation == 'tanh': self.activation = tanh self.activation_prime = tanh_prime elif activation == 'relu': self.activation = relu self.activation_prime = relu_prime self.layers = [] for i in range(1, len(layersDim) - 1): dim = (layersDim[i - 1] + 1, layersDim[i] + 1) self.layers.append(Layer(dim, i, self.activation, self.activation_prime)) dim = (layersDim[i] + 1, layersDim[i + 1]) self.layers.append(Layer(dim, len(layersDim) - 1, self.activation, self.activation_prime, True))# train the network def fit(self, X, y, learning_rate=0.1, epochs=10000): # Add column of ones to X # This is to add the bias unit to the input layer ones = np.atleast_2d(np.ones(X.shape[0])) X = np.concatenate((ones.T, X), axis=1) for k in range(epochs): i = np.random.randint(X.shape[0]) a = X[i] # compute the feed forward for l in range(len(self.layers)): a = self.layers[l].forward(a) # compute the backward propagation delta = self.layers[-1].backward(y[i], None) for l in range(len(self.layers) - 2, -1, -1): delta = self.layers[l].backward(delta, self.layers[l+1]) # update weights a = X[i] for layer in self.layers: layer.update(learning_rate, a) a = layer.A# predict input def predict(self, x): a = np.concatenate((np.ones(1).T, np.array(x)), axis=0) for l in range(0, len(self.layers)): a = self.layers[l].forward(a) return a"
},
{
"code": null,
"e": 7290,
"s": 7213,
"text": "To run the network we take as example the approximation of the Xor function."
},
{
"code": null,
"e": 7411,
"s": 7290,
"text": "We try the several network configurations, using different learning rates and epoch iterations. Results are liste below:"
},
{
"code": null,
"e": 7671,
"s": 7411,
"text": "Result with tanh[0 0] [-0.00011187][0 1] [ 0.98090146][1 0] [ 0.97569382][1 1] [ 0.00128179]Result with sigmoid[0 0] [ 0.01958287][0 1] [ 0.96476513][1 0] [ 0.97699611][1 1] [ 0.05132127]Result with relu[0 0] [ 0.][0 1] [ 1.][1 0] [ 1.][1 1] [ 4.23272528e-16]"
},
{
"code": null,
"e": 7796,
"s": 7671,
"text": "It is advisable that you try different configurations and see for yourself which one gives the best and most stable results."
},
{
"code": null,
"e": 7834,
"s": 7796,
"text": "The full code can be downloaded here."
},
{
"code": null,
"e": 8144,
"s": 7834,
"text": "Back propagation can be confusing and tricky to implement. You might have the illusion that you get a grasp of it through the theory, but the truth is that when implementing it, it is easy to fall into many traps. You should be patient and persistent, as back propagation is a corner stone of Neural Networks."
}
]
|
Java Examples - Copy a File | How to copy one file into another file ?
This example shows how to copy contents of one file into another file using read & write methods of BufferedWriter class.
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
BufferedWriter out1 = new BufferedWriter(new FileWriter("srcfile"));
out1.write("string to be copied\n");
out1.close();
InputStream in = new FileInputStream(new File("srcfile"));
OutputStream out = new FileOutputStream(new File("destnfile"));
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
BufferedReader in1 = new BufferedReader(new FileReader("destnfile"));
String str;
while ((str = in1.readLine()) != null) {
System.out.println(str);
}
in.close();
}
}
The above code sample will produce the following result.
string to be copied
The following is another sample example of copy one file into another file in java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyExample {
public static void main(String[] args) {
FileInputStream ins = null;
FileOutputStream outs = null;
try {
File infile = new File("C:\\Users\\TutorialsPoint7\\Desktop\\abc.txt");
File outfile = new File("C:\\Users\\TutorialsPoint7\\Desktop\\bbc.txt");
ins = new FileInputStream(infile);
outs = new FileOutputStream(outfile);
byte[] buffer = new byte[1024];
int length;
while ((length = ins.read(buffer)) > 0) {
outs.write(buffer, 0, length);
}
ins.close();
outs.close();
System.out.println("File copied successfully!!");
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
}
The above code sample will produce the following result.
File copied successfully!!
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2109,
"s": 2068,
"text": "How to copy one file into another file ?"
},
{
"code": null,
"e": 2231,
"s": 2109,
"text": "This example shows how to copy contents of one file into another file using read & write methods of BufferedWriter class."
},
{
"code": null,
"e": 2995,
"s": 2231,
"text": "import java.io.*;\n\npublic class Main {\n public static void main(String[] args) throws Exception {\n BufferedWriter out1 = new BufferedWriter(new FileWriter(\"srcfile\"));\n out1.write(\"string to be copied\\n\");\n out1.close();\n InputStream in = new FileInputStream(new File(\"srcfile\"));\n OutputStream out = new FileOutputStream(new File(\"destnfile\"));\n byte[] buf = new byte[1024];\n int len;\n \n while ((len = in.read(buf)) > 0) {\n out.write(buf, 0, len);\n }\n in.close();\n out.close();\n BufferedReader in1 = new BufferedReader(new FileReader(\"destnfile\"));\n String str;\n \n while ((str = in1.readLine()) != null) {\n System.out.println(str);\n }\n in.close();\n }\n}"
},
{
"code": null,
"e": 3052,
"s": 2995,
"text": "The above code sample will produce the following result."
},
{
"code": null,
"e": 3073,
"s": 3052,
"text": "string to be copied\n"
},
{
"code": null,
"e": 3156,
"s": 3073,
"text": "The following is another sample example of copy one file into another file in java"
},
{
"code": null,
"e": 4042,
"s": 3156,
"text": "import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\n \npublic class CopyExample {\n public static void main(String[] args) {\n FileInputStream ins = null;\n FileOutputStream outs = null;\n try {\n File infile = new File(\"C:\\\\Users\\\\TutorialsPoint7\\\\Desktop\\\\abc.txt\");\n File outfile = new File(\"C:\\\\Users\\\\TutorialsPoint7\\\\Desktop\\\\bbc.txt\");\n ins = new FileInputStream(infile);\n outs = new FileOutputStream(outfile);\n byte[] buffer = new byte[1024];\n int length;\n \n while ((length = ins.read(buffer)) > 0) {\n outs.write(buffer, 0, length);\n } \n ins.close();\n outs.close();\n System.out.println(\"File copied successfully!!\");\n } catch(IOException ioe) {\n ioe.printStackTrace();\n } \n }\n}"
},
{
"code": null,
"e": 4099,
"s": 4042,
"text": "The above code sample will produce the following result."
},
{
"code": null,
"e": 4127,
"s": 4099,
"text": "File copied successfully!!\n"
},
{
"code": null,
"e": 4134,
"s": 4127,
"text": " Print"
},
{
"code": null,
"e": 4145,
"s": 4134,
"text": " Add Notes"
}
]
|
Apache Derby - Alter Table Statement | The ALTER TABLE statement, allows you to alter an existing table. Using this you can do the following −
Add a column, add a constraint
Add a column, add a constraint
Drop a column, drop a constraint
Drop a column, drop a constraint
Change the row level locking of a table
Change the row level locking of a table
Let us assume we have created a table named Employees as shown below −
ij> CREATE TABLE Employees (
Id INT NOT NULL GENERATED ALWAYS AS IDENTITY,
Name VARCHAR(255),
Salary INT NOT NULL,
Location VARCHAR(255),
PRIMARY KEY (Id)
);
And, inserted four records using the insert statement as −
ij> INSERT INTO Employees (Name, Salary, Location) VALUES
('Amit', 30000, 'Hyderabad'),
('Kalyan', 40000, 'Vishakhapatnam'),
('Renuka', 50000, 'Delhi'),
('Archana', 15000, 'Mumbai');
Following is the syntax to add a column to a table using ALTER statement.
ALTER TABLE table_name ADD COLUMN column_name column_type;
Using ALTER statement, we are trying to add a new column named Age with the type integer.
ALTER TABLE Employees ADD COLUMN Age INT;
0 rows inserted/updated/deleted
Add another column named Phone_No with the type integer.
ALTER TABLE Employees ADD COLUMN Phone_No BIGINT;
0 rows inserted/updated/deleted
The DESCRIBE command describes specified table by listing the columns and their details, if the table exists. If you DESCRIBE, the table Employees you can observe the newly added columns as shown below −
ij> DESCRIBE Employees;
COLUMN_NAME |TYPE_NAME|DEC&|NUM&|COLUM&|COLUMN_DEF|CHAR_OCTE&|IS_NULL&
------------------------------------------------------------------------------
ID |INTEGER |0 |10 |10 |AUTOINCRE&|NULL |NO
NAME |VARCHAR |NULL|NULL |255 |NULL |510 |YES
SALARY |INTEGER |0 |10 |10 |NULL |NULL |NO
LOCATION |VARCHAR |NULL|NULL |255 |NULL |510 |YES
AGE |INTEGER |0 |10 |10 |NULL |NULL |YES
PHONE_NO |INTEGER |0 |10 |10 |NULL |NULL |YES
6 rows selected
Following is the syntax to add a constraint to a column of a table using ALTER statement.
ALTER TABLE table_name ADD CONSTRAINT constraint_name constraint (column_name);
Where constraint can be NOT NULL, NULL, PRIMARY KEY, UNIQUE, FOREIGN KEY, CHECK.
Using ALTER statement, we are trying to add constraint UNIQUE to the Phone_No column.
ij> ALTER TABLE Employees ADD CONSTRAINT New_Constraint UNIQUE(Phone_No);
0 rows inserted/updated/deleted
Once, you add a UNIQUE constraint to a column, it cannot have the same values for two rows, i.e., phone number should be unique for each employee.
If you try to add two columns with a same phone number, you will get an exception as shown below.
ij> INSERT INTO Employees (Name, Salary, Location, Age, Phone_No) VALUES
('Amit', 30000, 'Hyderabad', 30, 9848022338);
1 row inserted/updated/deleted
ij> INSERT INTO Employees (Name, Salary, Location, Age, Phone_No) VALUES
('Sumit', 35000, 'Chennai', 25, 9848022338);
ERROR 23505: The statement was aborted because it would have caused a duplicate
key value in a unique or primary key constraint or unique index identified by
'NEW_CONSTRAINT' defined on 'EMPLOYEES'.
Following is the syntax to drop a constraint of a column −
ALTER TABLE table_name DROP CONSTRAINT constraint_name;
The following query deletes the constraint name New_Constraint on the column Phone_No created above.
ij> ALTER TABLE Employees DROP CONSTRAINT New_Constraint;
0 rows inserted/updated/deleted
Since we have removed the UNIQUE constraint on the column Phone_No, you can add columns with the same phone number.
ij> INSERT INTO Employees (Name, Salary, Location, Age, Phone_No) VALUES
('Sumit', 35000, 'Chennai', 25, 9848022338);
1 row inserted/updated/deleted
You can verify the contents of the table ij> select * from Employees as follows −
ID |NAME |SALARY |LOCATION |AGE |PHONE_NO
-------------------------------------------------------------------------
1 |Amit |30000 |Hyderabad|30 |9848022338
2 |Sumit |35000 |Chennai |25 |9848022338
2 rows selected
Following is the syntax to drop a column of a column.
ALTER TABLE table_name DROP COLUMN column_name;
Following query deletes the column named age of the employee −
ij> ALTER TABLE Employees DROP COLUMN Age;
0 rows inserted/updated/deleted
If you describe the table, you can see only 4 columns.
ij> DESCRIBE Employees;
COLUMN_NAME |TYPE_NAME|DEC&|NUM&|COLUM&|COLUMN_DEF |CHAR_OCTE&|IS_NULL&
------------------------------------------------------------------------------
ID |INTEGER |0 |10 |10 |AUTOINCRE& |NULL |NO
NAME |VARCHAR |NULL|NULL|255 |NULL |510 |YES
SALARY |INTEGER |0 |10 |10 |NULL |NULL |NO
LOCATION |VARCHAR |NULL|NULL|255 |NULL |510 |YES
PHONE_NO |BIGINT |0 |10 |19 |NULL |NULL |YES
Following is the JDBC program to alter a table using the ALTER query −
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class AlterTableExample {
public static void main(String args[]) throws Exception {
//Registering the driver
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
//Getting the Connection object
String URL = "jdbc:derby:sampleDB;create=true";
Connection conn = DriverManager.getConnection(URL);
//Creating the Statement object
Statement stmt = conn.createStatement();
//Executing the query
String createQuery = "CREATE TABLE Employees( "
+ "Id INT NOT NULL GENERATED ALWAYS AS IDENTITY, "
+ "Name VARCHAR(255), "
+ "Salary INT NOT NULL, "
+ "Location VARCHAR(255), "
+ "PRIMARY KEY (Id))";
stmt.execute(createQuery);
System.out.println("Table created");
System.out.println(" ");
//Executing the query
String insertQuery = "INSERT INTO Employees("
+ "Name, Salary, Location) VALUES "
+ "('Amit', 30000, 'Hyderabad'), "
+ "('Kalyan', 40000, 'Vishakhapatnam'), "
+ "('Renuka', 50000, 'Delhi'), "
+ "('Archana', 15000, 'Mumbai'), "
+ "('Trupti', 45000, 'Kochin')";
stmt.execute(insertQuery);
System.out.println("Values inserted");
System.out.println(" ");
//Executing the query
String selectQuery = "SELECT * FROM Employees";
ResultSet rs = stmt.executeQuery(selectQuery);
System.out.println("Contents of the table after inserting the table");
while(rs.next()) {
System.out.println("Id: "+rs.getString("Id"));
System.out.println("Name: "+rs.getString("Name"));
System.out.println("Salary: "+rs.getString("Salary"));
System.out.println("Location: "+rs.getString("Location"));
}
System.out.println(" ");
//Altering the table
stmt.execute("ALTER TABLE Employees ADD COLUMN Age INT");
stmt.execute("ALTER TABLE Employees ADD COLUMN Phone_No BigINT");
stmt.execute("ALTER TABLE Employees " + "ADD CONSTRAINT New_Constraint UNIQUE(Phone_No)");
stmt.execute("INSERT INTO Employees "
+ "(Name, Salary, Location, Age, Phone_No) "
+ "VALUES ('Amit', 30000, 'Hyderabad', 30, 9848022338)");
ResultSet alterResult = stmt.executeQuery("Select * from Employees");
System.out.println("Contents of the table after altering "
+ "the table and inserting values to it: ");
while(alterResult.next()) {
System.out.println("Id: "+alterResult.getString("Id"));
System.out.println("Name: "+alterResult.getString("Name"));
System.out.println("Salary: "+alterResult.getString("Salary"));
System.out.println("Location: "+alterResult.getString("Location"));
System.out.println("Age: "+alterResult.getString("Age"));
System.out.println("Phone_No: "+alterResult.getString("Phone_No"));
}
}
}
On executing the above program, the following output will be generated −
Table created
Values inserted
Contents of the table after inserting the table
Id: 1
Name: Amit
Salary: 30000
Location: Hyderabad
Id: 2
Name: Kalyan
Salary: 40000
Location: Vishakhapatnam
Id: 3
Name: Renuka
Salary: 50000
Location: Delhi
Id: 4
Name: Archana
Salary: 15000
Location: Mumbai
Id: 5
Name: Trupti
Salary: 45000
Location: Kochin
Contents of the table after altering the table and inserting values to it:
Id: 1
Name: Amit
Salary: 30000
Location: Hyderabad
Age: null
Phone_No: null
Id: 2
Name: Kalyan
Salary: 40000
Location: Vishakhapatnam
Age: null
Phone_No: null
Id: 3
Name: Renuka
Salary: 50000
Location: Delhi
Age: null
Phone_No: null
Id: 4
Name: Archana
Salary: 15000
Location: Mumbai
Age: null
Phone_No: null
Id: 5
Name: Trupti
Salary: 45000
Location: Kochin
Age: null
Phone_No: null
Id: 6
Name: Amit
Salary: 30000
Location: Hyderabad
Age: 30
Phone_No: 9848022338
46 Lectures
3.5 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
16 Lectures
1 hours
Nilay Mehta
52 Lectures
1.5 hours
Bigdata Engineer
14 Lectures
1 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2284,
"s": 2180,
"text": "The ALTER TABLE statement, allows you to alter an existing table. Using this you can do the following −"
},
{
"code": null,
"e": 2315,
"s": 2284,
"text": "Add a column, add a constraint"
},
{
"code": null,
"e": 2346,
"s": 2315,
"text": "Add a column, add a constraint"
},
{
"code": null,
"e": 2379,
"s": 2346,
"text": "Drop a column, drop a constraint"
},
{
"code": null,
"e": 2412,
"s": 2379,
"text": "Drop a column, drop a constraint"
},
{
"code": null,
"e": 2452,
"s": 2412,
"text": "Change the row level locking of a table"
},
{
"code": null,
"e": 2492,
"s": 2452,
"text": "Change the row level locking of a table"
},
{
"code": null,
"e": 2563,
"s": 2492,
"text": "Let us assume we have created a table named Employees as shown below −"
},
{
"code": null,
"e": 2737,
"s": 2563,
"text": "ij> CREATE TABLE Employees (\n Id INT NOT NULL GENERATED ALWAYS AS IDENTITY,\n Name VARCHAR(255),\n Salary INT NOT NULL,\n Location VARCHAR(255),\n PRIMARY KEY (Id)\n);\n"
},
{
"code": null,
"e": 2796,
"s": 2737,
"text": "And, inserted four records using the insert statement as −"
},
{
"code": null,
"e": 2992,
"s": 2796,
"text": "ij> INSERT INTO Employees (Name, Salary, Location) VALUES\n ('Amit', 30000, 'Hyderabad'),\n ('Kalyan', 40000, 'Vishakhapatnam'),\n ('Renuka', 50000, 'Delhi'),\n ('Archana', 15000, 'Mumbai');\n"
},
{
"code": null,
"e": 3066,
"s": 2992,
"text": "Following is the syntax to add a column to a table using ALTER statement."
},
{
"code": null,
"e": 3126,
"s": 3066,
"text": "ALTER TABLE table_name ADD COLUMN column_name column_type;\n"
},
{
"code": null,
"e": 3216,
"s": 3126,
"text": "Using ALTER statement, we are trying to add a new column named Age with the type integer."
},
{
"code": null,
"e": 3291,
"s": 3216,
"text": "ALTER TABLE Employees ADD COLUMN Age INT;\n0 rows inserted/updated/deleted\n"
},
{
"code": null,
"e": 3348,
"s": 3291,
"text": "Add another column named Phone_No with the type integer."
},
{
"code": null,
"e": 3431,
"s": 3348,
"text": "ALTER TABLE Employees ADD COLUMN Phone_No BIGINT;\n0 rows inserted/updated/deleted\n"
},
{
"code": null,
"e": 3635,
"s": 3431,
"text": "The DESCRIBE command describes specified table by listing the columns and their details, if the table exists. If you DESCRIBE, the table Employees you can observe the newly added columns as shown below −"
},
{
"code": null,
"e": 4220,
"s": 3635,
"text": "ij> DESCRIBE Employees;\nCOLUMN_NAME |TYPE_NAME|DEC&|NUM&|COLUM&|COLUMN_DEF|CHAR_OCTE&|IS_NULL&\n------------------------------------------------------------------------------\nID |INTEGER |0 |10 |10 |AUTOINCRE&|NULL |NO\nNAME |VARCHAR |NULL|NULL |255 |NULL |510 |YES\nSALARY |INTEGER |0 |10 |10 |NULL |NULL |NO\nLOCATION |VARCHAR |NULL|NULL |255 |NULL |510 |YES\nAGE |INTEGER |0 |10 |10 |NULL |NULL |YES\nPHONE_NO |INTEGER |0 |10 |10 |NULL |NULL |YES\n6 rows selected\n"
},
{
"code": null,
"e": 4310,
"s": 4220,
"text": "Following is the syntax to add a constraint to a column of a table using ALTER statement."
},
{
"code": null,
"e": 4391,
"s": 4310,
"text": "ALTER TABLE table_name ADD CONSTRAINT constraint_name constraint (column_name);\n"
},
{
"code": null,
"e": 4472,
"s": 4391,
"text": "Where constraint can be NOT NULL, NULL, PRIMARY KEY, UNIQUE, FOREIGN KEY, CHECK."
},
{
"code": null,
"e": 4558,
"s": 4472,
"text": "Using ALTER statement, we are trying to add constraint UNIQUE to the Phone_No column."
},
{
"code": null,
"e": 4665,
"s": 4558,
"text": "ij> ALTER TABLE Employees ADD CONSTRAINT New_Constraint UNIQUE(Phone_No);\n0 rows inserted/updated/deleted\n"
},
{
"code": null,
"e": 4812,
"s": 4665,
"text": "Once, you add a UNIQUE constraint to a column, it cannot have the same values for two rows, i.e., phone number should be unique for each employee."
},
{
"code": null,
"e": 4910,
"s": 4812,
"text": "If you try to add two columns with a same phone number, you will get an exception as shown below."
},
{
"code": null,
"e": 5378,
"s": 4910,
"text": "ij> INSERT INTO Employees (Name, Salary, Location, Age, Phone_No) VALUES\n('Amit', 30000, 'Hyderabad', 30, 9848022338);\n1 row inserted/updated/deleted\nij> INSERT INTO Employees (Name, Salary, Location, Age, Phone_No) VALUES\n('Sumit', 35000, 'Chennai', 25, 9848022338);\nERROR 23505: The statement was aborted because it would have caused a duplicate\nkey value in a unique or primary key constraint or unique index identified by\n'NEW_CONSTRAINT' defined on 'EMPLOYEES'.\n"
},
{
"code": null,
"e": 5437,
"s": 5378,
"text": "Following is the syntax to drop a constraint of a column −"
},
{
"code": null,
"e": 5494,
"s": 5437,
"text": "ALTER TABLE table_name DROP CONSTRAINT constraint_name;\n"
},
{
"code": null,
"e": 5595,
"s": 5494,
"text": "The following query deletes the constraint name New_Constraint on the column Phone_No created above."
},
{
"code": null,
"e": 5686,
"s": 5595,
"text": "ij> ALTER TABLE Employees DROP CONSTRAINT New_Constraint;\n0 rows inserted/updated/deleted\n"
},
{
"code": null,
"e": 5802,
"s": 5686,
"text": "Since we have removed the UNIQUE constraint on the column Phone_No, you can add columns with the same phone number."
},
{
"code": null,
"e": 5952,
"s": 5802,
"text": "ij> INSERT INTO Employees (Name, Salary, Location, Age, Phone_No) VALUES\n('Sumit', 35000, 'Chennai', 25, 9848022338);\n1 row inserted/updated/deleted\n"
},
{
"code": null,
"e": 6034,
"s": 5952,
"text": "You can verify the contents of the table ij> select * from Employees as follows −"
},
{
"code": null,
"e": 6258,
"s": 6034,
"text": "ID |NAME |SALARY |LOCATION |AGE |PHONE_NO\n-------------------------------------------------------------------------\n1 |Amit |30000 |Hyderabad|30 |9848022338\n2 |Sumit |35000 |Chennai |25 |9848022338\n2 rows selected\n"
},
{
"code": null,
"e": 6312,
"s": 6258,
"text": "Following is the syntax to drop a column of a column."
},
{
"code": null,
"e": 6361,
"s": 6312,
"text": "ALTER TABLE table_name DROP COLUMN column_name;\n"
},
{
"code": null,
"e": 6424,
"s": 6361,
"text": "Following query deletes the column named age of the employee −"
},
{
"code": null,
"e": 6500,
"s": 6424,
"text": "ij> ALTER TABLE Employees DROP COLUMN Age;\n0 rows inserted/updated/deleted\n"
},
{
"code": null,
"e": 6555,
"s": 6500,
"text": "If you describe the table, you can see only 4 columns."
},
{
"code": null,
"e": 7064,
"s": 6555,
"text": "ij> DESCRIBE Employees;\nCOLUMN_NAME |TYPE_NAME|DEC&|NUM&|COLUM&|COLUMN_DEF |CHAR_OCTE&|IS_NULL&\n------------------------------------------------------------------------------\nID |INTEGER |0 |10 |10 |AUTOINCRE& |NULL |NO\nNAME |VARCHAR |NULL|NULL|255 |NULL |510 |YES\nSALARY |INTEGER |0 |10 |10 |NULL |NULL |NO\nLOCATION |VARCHAR |NULL|NULL|255 |NULL |510 |YES\nPHONE_NO |BIGINT |0 |10 |19 |NULL |NULL |YES\n"
},
{
"code": null,
"e": 7135,
"s": 7064,
"text": "Following is the JDBC program to alter a table using the ALTER query −"
},
{
"code": null,
"e": 10171,
"s": 7135,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\npublic class AlterTableExample {\n public static void main(String args[]) throws Exception {\n //Registering the driver\n Class.forName(\"org.apache.derby.jdbc.EmbeddedDriver\");\n //Getting the Connection object\n String URL = \"jdbc:derby:sampleDB;create=true\";\n Connection conn = DriverManager.getConnection(URL);\n\n //Creating the Statement object\n Statement stmt = conn.createStatement();\n\n //Executing the query\n String createQuery = \"CREATE TABLE Employees( \"\n + \"Id INT NOT NULL GENERATED ALWAYS AS IDENTITY, \"\n + \"Name VARCHAR(255), \"\n + \"Salary INT NOT NULL, \"\n + \"Location VARCHAR(255), \"\n + \"PRIMARY KEY (Id))\";\n\n stmt.execute(createQuery);\n System.out.println(\"Table created\");\n System.out.println(\" \");\n\n //Executing the query\n String insertQuery = \"INSERT INTO Employees(\"\n + \"Name, Salary, Location) VALUES \"\n + \"('Amit', 30000, 'Hyderabad'), \"\n + \"('Kalyan', 40000, 'Vishakhapatnam'), \"\n + \"('Renuka', 50000, 'Delhi'), \"\n + \"('Archana', 15000, 'Mumbai'), \"\n + \"('Trupti', 45000, 'Kochin')\";\n\n stmt.execute(insertQuery);\n System.out.println(\"Values inserted\");\n System.out.println(\" \");\n\n //Executing the query\n String selectQuery = \"SELECT * FROM Employees\";\n ResultSet rs = stmt.executeQuery(selectQuery);\n System.out.println(\"Contents of the table after inserting the table\");\n while(rs.next()) {\n System.out.println(\"Id: \"+rs.getString(\"Id\"));\n System.out.println(\"Name: \"+rs.getString(\"Name\"));\n System.out.println(\"Salary: \"+rs.getString(\"Salary\"));\n System.out.println(\"Location: \"+rs.getString(\"Location\"));\n }\n System.out.println(\" \");\n\n //Altering the table\n stmt.execute(\"ALTER TABLE Employees ADD COLUMN Age INT\");\n stmt.execute(\"ALTER TABLE Employees ADD COLUMN Phone_No BigINT\");\n stmt.execute(\"ALTER TABLE Employees \" + \"ADD CONSTRAINT New_Constraint UNIQUE(Phone_No)\");\n\n stmt.execute(\"INSERT INTO Employees \"\n + \"(Name, Salary, Location, Age, Phone_No) \"\n + \"VALUES ('Amit', 30000, 'Hyderabad', 30, 9848022338)\");\n ResultSet alterResult = stmt.executeQuery(\"Select * from Employees\");\n System.out.println(\"Contents of the table after altering \"\n + \"the table and inserting values to it: \");\n while(alterResult.next()) {\n System.out.println(\"Id: \"+alterResult.getString(\"Id\"));\n System.out.println(\"Name: \"+alterResult.getString(\"Name\"));\n System.out.println(\"Salary: \"+alterResult.getString(\"Salary\"));\n System.out.println(\"Location: \"+alterResult.getString(\"Location\"));\n System.out.println(\"Age: \"+alterResult.getString(\"Age\"));\n System.out.println(\"Phone_No: \"+alterResult.getString(\"Phone_No\"));\n }\n }\n}"
},
{
"code": null,
"e": 10244,
"s": 10171,
"text": "On executing the above program, the following output will be generated −"
},
{
"code": null,
"e": 11124,
"s": 10244,
"text": "Table created\n\nValues inserted\n\nContents of the table after inserting the table\nId: 1\nName: Amit\nSalary: 30000\nLocation: Hyderabad\nId: 2\nName: Kalyan\nSalary: 40000\nLocation: Vishakhapatnam\nId: 3\nName: Renuka\nSalary: 50000\nLocation: Delhi\nId: 4\nName: Archana\nSalary: 15000\nLocation: Mumbai\nId: 5\nName: Trupti\nSalary: 45000\nLocation: Kochin\n\nContents of the table after altering the table and inserting values to it:\nId: 1\nName: Amit\nSalary: 30000\nLocation: Hyderabad\nAge: null\nPhone_No: null\nId: 2\nName: Kalyan\nSalary: 40000\nLocation: Vishakhapatnam\nAge: null\nPhone_No: null\nId: 3\nName: Renuka\nSalary: 50000\nLocation: Delhi\nAge: null\nPhone_No: null\nId: 4\nName: Archana\nSalary: 15000\nLocation: Mumbai\nAge: null\nPhone_No: null\nId: 5\nName: Trupti\nSalary: 45000\nLocation: Kochin\nAge: null\nPhone_No: null\nId: 6\nName: Amit\nSalary: 30000\nLocation: Hyderabad\nAge: 30\nPhone_No: 9848022338\n"
},
{
"code": null,
"e": 11159,
"s": 11124,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 11178,
"s": 11159,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 11213,
"s": 11178,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 11234,
"s": 11213,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 11267,
"s": 11234,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 11280,
"s": 11267,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 11315,
"s": 11280,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 11333,
"s": 11315,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 11366,
"s": 11333,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 11384,
"s": 11366,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 11417,
"s": 11384,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 11435,
"s": 11417,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 11442,
"s": 11435,
"text": " Print"
},
{
"code": null,
"e": 11453,
"s": 11442,
"text": " Add Notes"
}
]
|
How we can iterate through a Python list of tuples? | Easiest way is to employ two nested for loops. Outer loop fetches each tuple and inner loop traverses each item from the tuple. Inner print() function end=’ ‘ to print all items in a tuple in one line. Another print() introduces new line after each tuple.
L=[(1,2,3), (4,5,6), (7,8,9,10)]
for x in L:
for y in x:
print(y, end=' ')
print()
1 2 3
4 5 6
7 8 9 10 | [
{
"code": null,
"e": 1318,
"s": 1062,
"text": "Easiest way is to employ two nested for loops. Outer loop fetches each tuple and inner loop traverses each item from the tuple. Inner print() function end=’ ‘ to print all items in a tuple in one line. Another print() introduces new line after each tuple."
},
{
"code": null,
"e": 1409,
"s": 1318,
"text": "L=[(1,2,3), (4,5,6), (7,8,9,10)]\nfor x in L:\n for y in x:\n print(y, end=' ')\n print()"
},
{
"code": null,
"e": 1432,
"s": 1409,
"text": "1 2 3\n\n4 5 6\n\n7 8 9 10"
}
]
|
Combinatorial Game Theory | Set 4 (Sprague - Grundy Theorem) - GeeksforGeeks | 04 Sep, 2021
Prerequisites : Grundy Numbers/Numbers and MexWe have already seen in Set 2 (https://www.geeksforgeeks.org/combinatorial-game-theory-set-2-game-nim/), that we can find who wins in a game of Nim without actually playing the game.Suppose we change the classic Nim game a bit. This time each player can only remove 1, 2 or 3 stones only (and not any number of stones as in the classic game of Nim). Can we predict who will win?Yes, we can predict the winner using Sprague-Grundy Theorem.
What is Sprague-Grundy Theorem? Suppose there is a composite game (more than one sub-game) made up of N sub-games and two players, A and B. Then Sprague-Grundy Theorem says that if both A and B play optimally (i.e., they don’t make any mistakes), then the player starting first is guaranteed to win if the XOR of the grundy numbers of position in each sub-games at the beginning of the game is non-zero. Otherwise, if the XOR evaluates to zero, then player A will lose definitely, no matter what.
How to apply Sprague Grundy Theorem ? We can apply Sprague-Grundy Theorem in any impartial game and solve it. The basic steps are listed as follows:
Break the composite game into sub-games.Then for each sub-game, calculate the Grundy Number at that position.Then calculate the XOR of all the calculated Grundy Numbers.If the XOR value is non-zero, then the player who is going to make the turn (First Player) will win else he is destined to lose, no matter what.
Break the composite game into sub-games.
Then for each sub-game, calculate the Grundy Number at that position.
Then calculate the XOR of all the calculated Grundy Numbers.
If the XOR value is non-zero, then the player who is going to make the turn (First Player) will win else he is destined to lose, no matter what.
Example Game : The game starts with 3 piles having 3, 4 and 5 stones, and the player to move may take any positive number of stones upto 3 only from any of the piles [Provided that the pile has that much amount of stones]. The last player to move wins. Which player wins the game assuming that both players play optimally?
How to tell who will win by applying Sprague-Grundy Theorem? As, we can see that this game is itself composed of several sub-games. First Step : The sub-games can be considered as each piles. Second Step : We see from the below table that
Grundy(3) = 3
Grundy(4) = 0
Grundy(5) = 1
We have already seen how to calculate the Grundy Numbers of this game in the previous article.Third Step : The XOR of 3, 0, 1 = 2Fourth Step : Since XOR is a non-zero number, so we can say that the first player will win.
Below is the program that implements above 4 steps.
C++
Java
Python3
C#
Javascript
/* Game Description- "A game is played between two players and there are N piles of stones such that each pile has certain number of stones. On his/her turn, a player selects a pile and can take any non-zero number of stones upto 3 (i.e- 1,2,3) The player who cannot move is considered to lose the game (i.e., one who take the last stone is the winner). Can you find which player wins the game if both players play optimally (they don't make any mistake)? " A Dynamic Programming approach to calculate Grundy Number and Mex and find the Winner using Sprague - Grundy Theorem. */ #include<bits/stdc++.h>using namespace std; /* piles[] -> Array having the initial count of stones/coins in each piles before the game has started. n -> Number of piles Grundy[] -> Array having the Grundy Number corresponding to the initial position of each piles in the game The piles[] and Grundy[] are having 0-based indexing*/ #define PLAYER1 1#define PLAYER2 2 // A Function to calculate Mex of all the values in that setint calculateMex(unordered_set<int> Set){ int Mex = 0; while (Set.find(Mex) != Set.end()) Mex++; return (Mex);} // A function to Compute Grundy Number of 'n'int calculateGrundy(int n, int Grundy[]){ Grundy[0] = 0; Grundy[1] = 1; Grundy[2] = 2; Grundy[3] = 3; if (Grundy[n] != -1) return (Grundy[n]); unordered_set<int> Set; // A Hash Table for (int i=1; i<=3; i++) Set.insert (calculateGrundy (n-i, Grundy)); // Store the result Grundy[n] = calculateMex (Set); return (Grundy[n]);} // A function to declare the winner of the gamevoid declareWinner(int whoseTurn, int piles[], int Grundy[], int n){ int xorValue = Grundy[piles[0]]; for (int i=1; i<=n-1; i++) xorValue = xorValue ^ Grundy[piles[i]]; if (xorValue != 0) { if (whoseTurn == PLAYER1) printf("Player 1 will win\n"); else printf("Player 2 will win\n"); } else { if (whoseTurn == PLAYER1) printf("Player 2 will win\n"); else printf("Player 1 will win\n"); } return;} // Driver program to test above functionsint main(){ // Test Case 1 int piles[] = {3, 4, 5}; int n = sizeof(piles)/sizeof(piles[0]); // Find the maximum element int maximum = *max_element(piles, piles + n); // An array to cache the sub-problems so that // re-computation of same sub-problems is avoided int Grundy[maximum + 1]; memset(Grundy, -1, sizeof (Grundy)); // Calculate Grundy Value of piles[i] and store it for (int i=0; i<=n-1; i++) calculateGrundy(piles[i], Grundy); declareWinner(PLAYER1, piles, Grundy, n); /* Test Case 2 int piles[] = {3, 8, 2}; int n = sizeof(piles)/sizeof(piles[0]); int maximum = *max_element (piles, piles + n); // An array to cache the sub-problems so that // re-computation of same sub-problems is avoided int Grundy [maximum + 1]; memset(Grundy, -1, sizeof (Grundy)); // Calculate Grundy Value of piles[i] and store it for (int i=0; i<=n-1; i++) calculateGrundy(piles[i], Grundy); declareWinner(PLAYER2, piles, Grundy, n); */ return (0);}
import java.util.*; /* Game Description-"A game is played between two players and there are N pilesof stones such that each pile has certain number of stones.On his/her turn, a player selects a pile and can take anynon-zero number of stones upto 3 (i.e- 1,2,3)The player who cannot move is considered to lose the game(i.e., one who take the last stone is the winner).Can you find which player wins the game if both players playoptimally (they don't make any mistake)? " A Dynamic Programming approach to calculate Grundy Numberand Mex and find the Winner using Sprague - Grundy Theorem. */ class GFG { /* piles[] -> Array having the initial count of stones/coins in each piles before the game has started.n -> Number of piles Grundy[] -> Array having the Grundy Number corresponding to the initial position of each piles in the game The piles[] and Grundy[] are having 0-based indexing*/ static int PLAYER1 = 1;static int PLAYER2 = 2; // A Function to calculate Mex of all the values in that setstatic int calculateMex(HashSet<Integer> Set){ int Mex = 0; while (Set.contains(Mex)) Mex++; return (Mex);} // A function to Compute Grundy Number of 'n'static int calculateGrundy(int n, int Grundy[]){ Grundy[0] = 0; Grundy[1] = 1; Grundy[2] = 2; Grundy[3] = 3; if (Grundy[n] != -1) return (Grundy[n]); // A Hash Table HashSet<Integer> Set = new HashSet<Integer>(); for (int i = 1; i <= 3; i++) Set.add(calculateGrundy (n - i, Grundy)); // Store the result Grundy[n] = calculateMex (Set); return (Grundy[n]);} // A function to declare the winner of the gamestatic void declareWinner(int whoseTurn, int piles[], int Grundy[], int n){ int xorValue = Grundy[piles[0]]; for (int i = 1; i <= n - 1; i++) xorValue = xorValue ^ Grundy[piles[i]]; if (xorValue != 0) { if (whoseTurn == PLAYER1) System.out.printf("Player 1 will win\n"); else System.out.printf("Player 2 will win\n"); } else { if (whoseTurn == PLAYER1) System.out.printf("Player 2 will win\n"); else System.out.printf("Player 1 will win\n"); } return;} // Driver codepublic static void main(String[] args){ // Test Case 1 int piles[] = {3, 4, 5}; int n = piles.length; // Find the maximum element int maximum = Arrays.stream(piles).max().getAsInt(); // An array to cache the sub-problems so that // re-computation of same sub-problems is avoided int Grundy[] = new int[maximum + 1]; Arrays.fill(Grundy, -1); // Calculate Grundy Value of piles[i] and store it for (int i = 0; i <= n - 1; i++) calculateGrundy(piles[i], Grundy); declareWinner(PLAYER1, piles, Grundy, n); /* Test Case 2 int piles[] = {3, 8, 2}; int n = sizeof(piles)/sizeof(piles[0]); int maximum = *max_element (piles, piles + n); // An array to cache the sub-problems so that // re-computation of same sub-problems is avoided int Grundy [maximum + 1]; memset(Grundy, -1, sizeof (Grundy)); // Calculate Grundy Value of piles[i] and store it for (int i=0; i<=n-1; i++) calculateGrundy(piles[i], Grundy); declareWinner(PLAYER2, piles, Grundy, n); */ }} // This code is contributed by PrinciRaj1992
''' Game Description- "A game is played between two players and there are N piles of stones such that each pile has certain number of stones. On his/her turn, a player selects a pile and can take any non-zero number of stones upto 3 (i.e- 1,2,3) The player who cannot move is considered to lose the game (i.e., one who take the last stone is the winner). Can you find which player wins the game if both players play optimally (they don't make any mistake)? " A Dynamic Programming approach to calculate Grundy Number and Mex and find the Winner using Sprague - Grundy Theorem. piles[] -> Array having the initial count of stones/coins in each piles before the game has started. n -> Number of piles Grundy[] -> Array having the Grundy Number corresponding to the initial position of each piles in the game The piles[] and Grundy[] are having 0-based indexing''' PLAYER1 = 1PLAYER2 = 2 # A Function to calculate Mex of all# the values in that setdef calculateMex(Set): Mex = 0; while (Mex in Set): Mex += 1 return (Mex) # A function to Compute Grundy Number of 'n'def calculateGrundy(n, Grundy): Grundy[0] = 0 Grundy[1] = 1 Grundy[2] = 2 Grundy[3] = 3 if (Grundy[n] != -1): return (Grundy[n]) # A Hash Table Set = set() for i in range(1, 4): Set.add(calculateGrundy(n - i, Grundy)) # Store the result Grundy[n] = calculateMex(Set) return (Grundy[n]) # A function to declare the winner of the gamedef declareWinner(whoseTurn, piles, Grundy, n): xorValue = Grundy[piles[0]]; for i in range(1, n): xorValue = (xorValue ^ Grundy[piles[i]]) if (xorValue != 0): if (whoseTurn == PLAYER1): print("Player 1 will win\n"); else: print("Player 2 will win\n"); else: if (whoseTurn == PLAYER1): print("Player 2 will win\n"); else: print("Player 1 will win\n"); # Driver codeif __name__=="__main__": # Test Case 1 piles = [ 3, 4, 5 ] n = len(piles) # Find the maximum element maximum = max(piles) # An array to cache the sub-problems so that # re-computation of same sub-problems is avoided Grundy = [-1 for i in range(maximum + 1)]; # Calculate Grundy Value of piles[i] and store it for i in range(n): calculateGrundy(piles[i], Grundy); declareWinner(PLAYER1, piles, Grundy, n); ''' Test Case 2 int piles[] = {3, 8, 2}; int n = sizeof(piles)/sizeof(piles[0]); int maximum = *max_element (piles, piles + n); // An array to cache the sub-problems so that // re-computation of same sub-problems is avoided int Grundy [maximum + 1]; memset(Grundy, -1, sizeof (Grundy)); // Calculate Grundy Value of piles[i] and store it for (int i=0; i<=n-1; i++) calculateGrundy(piles[i], Grundy); declareWinner(PLAYER2, piles, Grundy, n); ''' # This code is contributed by rutvik_56
using System;using System.Linq;using System.Collections.Generic; /* Game Description-"A game is played between two players and there are N pilesof stones such that each pile has certain number of stones.On his/her turn, a player selects a pile and can take anynon-zero number of stones upto 3 (i.e- 1,2,3)The player who cannot move is considered to lose the game(i.e., one who take the last stone is the winner).Can you find which player wins the game if both players playoptimally (they don't make any mistake)? " A Dynamic Programming approach to calculate Grundy Numberand Mex and find the Winner using Sprague - Grundy Theorem. */ class GFG{ /* piles[] -> Array having the initial count of stones/coins in each piles before the game has started.n -> Number of piles Grundy[] -> Array having the Grundy Number corresponding to the initial position of each piles in the game The piles[] and Grundy[] are having 0-based indexing*/ static int PLAYER1 = 1;//static int PLAYER2 = 2; // A Function to calculate Mex of all the values in that setstatic int calculateMex(HashSet<int> Set){ int Mex = 0; while (Set.Contains(Mex)) Mex++; return (Mex);} // A function to Compute Grundy Number of 'n'static int calculateGrundy(int n, int []Grundy){ Grundy[0] = 0; Grundy[1] = 1; Grundy[2] = 2; Grundy[3] = 3; if (Grundy[n] != -1) return (Grundy[n]); // A Hash Table HashSet<int> Set = new HashSet<int>(); for (int i = 1; i <= 3; i++) Set.Add(calculateGrundy (n - i, Grundy)); // Store the result Grundy[n] = calculateMex (Set); return (Grundy[n]);} // A function to declare the winner of the gamestatic void declareWinner(int whoseTurn, int []piles, int []Grundy, int n){ int xorValue = Grundy[piles[0]]; for (int i = 1; i <= n - 1; i++) xorValue = xorValue ^ Grundy[piles[i]]; if (xorValue != 0) { if (whoseTurn == PLAYER1) Console.Write("Player 1 will win\n"); else Console.Write("Player 2 will win\n"); } else { if (whoseTurn == PLAYER1) Console.Write("Player 2 will win\n"); else Console.Write("Player 1 will win\n"); } return;} // Driver codestatic void Main(){ // Test Case 1 int []piles = {3, 4, 5}; int n = piles.Length; // Find the maximum element int maximum = piles.Max(); // An array to cache the sub-problems so that // re-computation of same sub-problems is avoided int []Grundy = new int[maximum + 1]; Array.Fill(Grundy, -1); // Calculate Grundy Value of piles[i] and store it for (int i = 0; i <= n - 1; i++) calculateGrundy(piles[i], Grundy); declareWinner(PLAYER1, piles, Grundy, n); /* Test Case 2 int piles[] = {3, 8, 2}; int n = sizeof(piles)/sizeof(piles[0]); int maximum = *max_element (piles, piles + n); // An array to cache the sub-problems so that // re-computation of same sub-problems is avoided int Grundy [maximum + 1]; memset(Grundy, -1, sizeof (Grundy)); // Calculate Grundy Value of piles[i] and store it for (int i=0; i<=n-1; i++) calculateGrundy(piles[i], Grundy); declareWinner(PLAYER2, piles, Grundy, n); */ }} // This code is contributed by mits
<script> /* Game Description-"A game is played between two players and there are N pilesof stones such that each pile has certain number of stones.On his/her turn, a player selects a pile and can take anynon-zero number of stones upto 3 (i.e- 1,2,3)The player who cannot move is considered to lose the game(i.e., one who take the last stone is the winner).Can you find which player wins the game if both players playoptimally (they don't make any mistake)? " A Dynamic Programming approach to calculate Grundy Numberand Mex and find the Winner using Sprague - Grundy Theorem. */ /* piles[] -> Array having the initial count of stones/coins in each piles before the game has started.n -> Number of piles Grundy[] -> Array having the Grundy Number corresponding to the initial position of each piles in the game The piles[] and Grundy[] are having 0-based indexing*/let PLAYER1 = 1;let PLAYER2 = 2; // A Function to calculate Mex of all the values in that setfunction calculateMex(Set){ let Mex = 0; while (Set.has(Mex)) Mex++; return (Mex);} // A function to Compute Grundy Number of 'n'function calculateGrundy(n,Grundy){ Grundy[0] = 0; Grundy[1] = 1; Grundy[2] = 2; Grundy[3] = 3; if (Grundy[n] != -1) return (Grundy[n]); // A Hash Table let Set = new Set(); for (let i = 1; i <= 3; i++) Set.add(calculateGrundy (n - i, Grundy)); // Store the result Grundy[n] = calculateMex (Set); return (Grundy[n]);} // A function to declare the winner of the gamefunction declareWinner(whoseTurn,piles,Grundy,n){ let xorValue = Grundy[piles[0]]; for (let i = 1; i <= n - 1; i++) xorValue = xorValue ^ Grundy[piles[i]]; if (xorValue != 0) { if (whoseTurn == PLAYER1) document.write("Player 1 will win<br>"); else document.write("Player 2 will win<br>"); } else { if (whoseTurn == PLAYER1) document.write("Player 2 will win<br>"); else document.write("Player 1 will win<br>"); } return;} // Driver code // Test Case 1 let piles = [3, 4, 5]; let n = piles.length; // Find the maximum element let maximum = Math.max(...piles) // An array to cache the sub-problems so that // re-computation of same sub-problems is avoided let Grundy = new Array(maximum + 1); for(let i=0;i<maximum+1;i++) Grundy[i]=0; // Calculate Grundy Value of piles[i] and store it for (let i = 0; i <= n - 1; i++) calculateGrundy(piles[i], Grundy); declareWinner(PLAYER1, piles, Grundy, n); /* Test Case 2 int piles[] = {3, 8, 2}; int n = sizeof(piles)/sizeof(piles[0]); int maximum = *max_element (piles, piles + n); // An array to cache the sub-problems so that // re-computation of same sub-problems is avoided int Grundy [maximum + 1]; memset(Grundy, -1, sizeof (Grundy)); // Calculate Grundy Value of piles[i] and store it for (int i=0; i<=n-1; i++) calculateGrundy(piles[i], Grundy); declareWinner(PLAYER2, piles, Grundy, n); */ // This code is contributed by avanitrachhadiya2155</script>
Output :
Player 1 will win
References : https://en.wikipedia.org/wiki/Sprague%E2%80%93Grundy_theorem
Exercise to the Readers: Consider the below game. “A game is played by two players with N integers A1, A2, .., AN. On his/her turn, a player selects an integer, divides it by 2, 3, or 6, and then takes the floor. If the integer becomes 0, it is removed. The last player to move wins. Which player wins the game if both players play optimally?”Hint : See the example 3 of previous article.
This article is contributed by Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
vinayb21
princiraj1992
Mithun Kumar
rutvik_56
avanitrachhadiya2155
adnanirshad158
Combinatorial
Game Theory
Mathematical
Mathematical
Game Theory
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Combinational Sum
Count ways to reach the nth stair using step 1, 2 or 3
Count of subsets with sum equal to X
Print all possible strings of length k that can be formed from a set of n characters
Find the Number of Permutations that satisfy the given condition in an array
Implementation of Tic-Tac-Toe game
Minimax Algorithm in Game Theory | Set 2 (Introduction to Evaluation Function)
Expectimax Algorithm in Game Theory
Game Theory (Normal-form game) | Set 3 (Game with Mixed Strategy)
Choice of Area | [
{
"code": null,
"e": 24881,
"s": 24853,
"text": "\n04 Sep, 2021"
},
{
"code": null,
"e": 25366,
"s": 24881,
"text": "Prerequisites : Grundy Numbers/Numbers and MexWe have already seen in Set 2 (https://www.geeksforgeeks.org/combinatorial-game-theory-set-2-game-nim/), that we can find who wins in a game of Nim without actually playing the game.Suppose we change the classic Nim game a bit. This time each player can only remove 1, 2 or 3 stones only (and not any number of stones as in the classic game of Nim). Can we predict who will win?Yes, we can predict the winner using Sprague-Grundy Theorem."
},
{
"code": null,
"e": 25863,
"s": 25366,
"text": "What is Sprague-Grundy Theorem? Suppose there is a composite game (more than one sub-game) made up of N sub-games and two players, A and B. Then Sprague-Grundy Theorem says that if both A and B play optimally (i.e., they don’t make any mistakes), then the player starting first is guaranteed to win if the XOR of the grundy numbers of position in each sub-games at the beginning of the game is non-zero. Otherwise, if the XOR evaluates to zero, then player A will lose definitely, no matter what."
},
{
"code": null,
"e": 26013,
"s": 25863,
"text": "How to apply Sprague Grundy Theorem ? We can apply Sprague-Grundy Theorem in any impartial game and solve it. The basic steps are listed as follows: "
},
{
"code": null,
"e": 26327,
"s": 26013,
"text": "Break the composite game into sub-games.Then for each sub-game, calculate the Grundy Number at that position.Then calculate the XOR of all the calculated Grundy Numbers.If the XOR value is non-zero, then the player who is going to make the turn (First Player) will win else he is destined to lose, no matter what."
},
{
"code": null,
"e": 26368,
"s": 26327,
"text": "Break the composite game into sub-games."
},
{
"code": null,
"e": 26438,
"s": 26368,
"text": "Then for each sub-game, calculate the Grundy Number at that position."
},
{
"code": null,
"e": 26499,
"s": 26438,
"text": "Then calculate the XOR of all the calculated Grundy Numbers."
},
{
"code": null,
"e": 26644,
"s": 26499,
"text": "If the XOR value is non-zero, then the player who is going to make the turn (First Player) will win else he is destined to lose, no matter what."
},
{
"code": null,
"e": 26967,
"s": 26644,
"text": "Example Game : The game starts with 3 piles having 3, 4 and 5 stones, and the player to move may take any positive number of stones upto 3 only from any of the piles [Provided that the pile has that much amount of stones]. The last player to move wins. Which player wins the game assuming that both players play optimally?"
},
{
"code": null,
"e": 27207,
"s": 26967,
"text": "How to tell who will win by applying Sprague-Grundy Theorem? As, we can see that this game is itself composed of several sub-games. First Step : The sub-games can be considered as each piles. Second Step : We see from the below table that "
},
{
"code": null,
"e": 27251,
"s": 27207,
"text": "Grundy(3) = 3\nGrundy(4) = 0 \nGrundy(5) = 1 "
},
{
"code": null,
"e": 27472,
"s": 27251,
"text": "We have already seen how to calculate the Grundy Numbers of this game in the previous article.Third Step : The XOR of 3, 0, 1 = 2Fourth Step : Since XOR is a non-zero number, so we can say that the first player will win."
},
{
"code": null,
"e": 27525,
"s": 27472,
"text": "Below is the program that implements above 4 steps. "
},
{
"code": null,
"e": 27529,
"s": 27525,
"text": "C++"
},
{
"code": null,
"e": 27534,
"s": 27529,
"text": "Java"
},
{
"code": null,
"e": 27542,
"s": 27534,
"text": "Python3"
},
{
"code": null,
"e": 27545,
"s": 27542,
"text": "C#"
},
{
"code": null,
"e": 27556,
"s": 27545,
"text": "Javascript"
},
{
"code": "/* Game Description- \"A game is played between two players and there are N piles of stones such that each pile has certain number of stones. On his/her turn, a player selects a pile and can take any non-zero number of stones upto 3 (i.e- 1,2,3) The player who cannot move is considered to lose the game (i.e., one who take the last stone is the winner). Can you find which player wins the game if both players play optimally (they don't make any mistake)? \" A Dynamic Programming approach to calculate Grundy Number and Mex and find the Winner using Sprague - Grundy Theorem. */ #include<bits/stdc++.h>using namespace std; /* piles[] -> Array having the initial count of stones/coins in each piles before the game has started. n -> Number of piles Grundy[] -> Array having the Grundy Number corresponding to the initial position of each piles in the game The piles[] and Grundy[] are having 0-based indexing*/ #define PLAYER1 1#define PLAYER2 2 // A Function to calculate Mex of all the values in that setint calculateMex(unordered_set<int> Set){ int Mex = 0; while (Set.find(Mex) != Set.end()) Mex++; return (Mex);} // A function to Compute Grundy Number of 'n'int calculateGrundy(int n, int Grundy[]){ Grundy[0] = 0; Grundy[1] = 1; Grundy[2] = 2; Grundy[3] = 3; if (Grundy[n] != -1) return (Grundy[n]); unordered_set<int> Set; // A Hash Table for (int i=1; i<=3; i++) Set.insert (calculateGrundy (n-i, Grundy)); // Store the result Grundy[n] = calculateMex (Set); return (Grundy[n]);} // A function to declare the winner of the gamevoid declareWinner(int whoseTurn, int piles[], int Grundy[], int n){ int xorValue = Grundy[piles[0]]; for (int i=1; i<=n-1; i++) xorValue = xorValue ^ Grundy[piles[i]]; if (xorValue != 0) { if (whoseTurn == PLAYER1) printf(\"Player 1 will win\\n\"); else printf(\"Player 2 will win\\n\"); } else { if (whoseTurn == PLAYER1) printf(\"Player 2 will win\\n\"); else printf(\"Player 1 will win\\n\"); } return;} // Driver program to test above functionsint main(){ // Test Case 1 int piles[] = {3, 4, 5}; int n = sizeof(piles)/sizeof(piles[0]); // Find the maximum element int maximum = *max_element(piles, piles + n); // An array to cache the sub-problems so that // re-computation of same sub-problems is avoided int Grundy[maximum + 1]; memset(Grundy, -1, sizeof (Grundy)); // Calculate Grundy Value of piles[i] and store it for (int i=0; i<=n-1; i++) calculateGrundy(piles[i], Grundy); declareWinner(PLAYER1, piles, Grundy, n); /* Test Case 2 int piles[] = {3, 8, 2}; int n = sizeof(piles)/sizeof(piles[0]); int maximum = *max_element (piles, piles + n); // An array to cache the sub-problems so that // re-computation of same sub-problems is avoided int Grundy [maximum + 1]; memset(Grundy, -1, sizeof (Grundy)); // Calculate Grundy Value of piles[i] and store it for (int i=0; i<=n-1; i++) calculateGrundy(piles[i], Grundy); declareWinner(PLAYER2, piles, Grundy, n); */ return (0);}",
"e": 30801,
"s": 27556,
"text": null
},
{
"code": "import java.util.*; /* Game Description-\"A game is played between two players and there are N pilesof stones such that each pile has certain number of stones.On his/her turn, a player selects a pile and can take anynon-zero number of stones upto 3 (i.e- 1,2,3)The player who cannot move is considered to lose the game(i.e., one who take the last stone is the winner).Can you find which player wins the game if both players playoptimally (they don't make any mistake)? \" A Dynamic Programming approach to calculate Grundy Numberand Mex and find the Winner using Sprague - Grundy Theorem. */ class GFG { /* piles[] -> Array having the initial count of stones/coins in each piles before the game has started.n -> Number of piles Grundy[] -> Array having the Grundy Number corresponding to the initial position of each piles in the game The piles[] and Grundy[] are having 0-based indexing*/ static int PLAYER1 = 1;static int PLAYER2 = 2; // A Function to calculate Mex of all the values in that setstatic int calculateMex(HashSet<Integer> Set){ int Mex = 0; while (Set.contains(Mex)) Mex++; return (Mex);} // A function to Compute Grundy Number of 'n'static int calculateGrundy(int n, int Grundy[]){ Grundy[0] = 0; Grundy[1] = 1; Grundy[2] = 2; Grundy[3] = 3; if (Grundy[n] != -1) return (Grundy[n]); // A Hash Table HashSet<Integer> Set = new HashSet<Integer>(); for (int i = 1; i <= 3; i++) Set.add(calculateGrundy (n - i, Grundy)); // Store the result Grundy[n] = calculateMex (Set); return (Grundy[n]);} // A function to declare the winner of the gamestatic void declareWinner(int whoseTurn, int piles[], int Grundy[], int n){ int xorValue = Grundy[piles[0]]; for (int i = 1; i <= n - 1; i++) xorValue = xorValue ^ Grundy[piles[i]]; if (xorValue != 0) { if (whoseTurn == PLAYER1) System.out.printf(\"Player 1 will win\\n\"); else System.out.printf(\"Player 2 will win\\n\"); } else { if (whoseTurn == PLAYER1) System.out.printf(\"Player 2 will win\\n\"); else System.out.printf(\"Player 1 will win\\n\"); } return;} // Driver codepublic static void main(String[] args){ // Test Case 1 int piles[] = {3, 4, 5}; int n = piles.length; // Find the maximum element int maximum = Arrays.stream(piles).max().getAsInt(); // An array to cache the sub-problems so that // re-computation of same sub-problems is avoided int Grundy[] = new int[maximum + 1]; Arrays.fill(Grundy, -1); // Calculate Grundy Value of piles[i] and store it for (int i = 0; i <= n - 1; i++) calculateGrundy(piles[i], Grundy); declareWinner(PLAYER1, piles, Grundy, n); /* Test Case 2 int piles[] = {3, 8, 2}; int n = sizeof(piles)/sizeof(piles[0]); int maximum = *max_element (piles, piles + n); // An array to cache the sub-problems so that // re-computation of same sub-problems is avoided int Grundy [maximum + 1]; memset(Grundy, -1, sizeof (Grundy)); // Calculate Grundy Value of piles[i] and store it for (int i=0; i<=n-1; i++) calculateGrundy(piles[i], Grundy); declareWinner(PLAYER2, piles, Grundy, n); */ }} // This code is contributed by PrinciRaj1992",
"e": 34150,
"s": 30801,
"text": null
},
{
"code": "''' Game Description- \"A game is played between two players and there are N piles of stones such that each pile has certain number of stones. On his/her turn, a player selects a pile and can take any non-zero number of stones upto 3 (i.e- 1,2,3) The player who cannot move is considered to lose the game (i.e., one who take the last stone is the winner). Can you find which player wins the game if both players play optimally (they don't make any mistake)? \" A Dynamic Programming approach to calculate Grundy Number and Mex and find the Winner using Sprague - Grundy Theorem. piles[] -> Array having the initial count of stones/coins in each piles before the game has started. n -> Number of piles Grundy[] -> Array having the Grundy Number corresponding to the initial position of each piles in the game The piles[] and Grundy[] are having 0-based indexing''' PLAYER1 = 1PLAYER2 = 2 # A Function to calculate Mex of all# the values in that setdef calculateMex(Set): Mex = 0; while (Mex in Set): Mex += 1 return (Mex) # A function to Compute Grundy Number of 'n'def calculateGrundy(n, Grundy): Grundy[0] = 0 Grundy[1] = 1 Grundy[2] = 2 Grundy[3] = 3 if (Grundy[n] != -1): return (Grundy[n]) # A Hash Table Set = set() for i in range(1, 4): Set.add(calculateGrundy(n - i, Grundy)) # Store the result Grundy[n] = calculateMex(Set) return (Grundy[n]) # A function to declare the winner of the gamedef declareWinner(whoseTurn, piles, Grundy, n): xorValue = Grundy[piles[0]]; for i in range(1, n): xorValue = (xorValue ^ Grundy[piles[i]]) if (xorValue != 0): if (whoseTurn == PLAYER1): print(\"Player 1 will win\\n\"); else: print(\"Player 2 will win\\n\"); else: if (whoseTurn == PLAYER1): print(\"Player 2 will win\\n\"); else: print(\"Player 1 will win\\n\"); # Driver codeif __name__==\"__main__\": # Test Case 1 piles = [ 3, 4, 5 ] n = len(piles) # Find the maximum element maximum = max(piles) # An array to cache the sub-problems so that # re-computation of same sub-problems is avoided Grundy = [-1 for i in range(maximum + 1)]; # Calculate Grundy Value of piles[i] and store it for i in range(n): calculateGrundy(piles[i], Grundy); declareWinner(PLAYER1, piles, Grundy, n); ''' Test Case 2 int piles[] = {3, 8, 2}; int n = sizeof(piles)/sizeof(piles[0]); int maximum = *max_element (piles, piles + n); // An array to cache the sub-problems so that // re-computation of same sub-problems is avoided int Grundy [maximum + 1]; memset(Grundy, -1, sizeof (Grundy)); // Calculate Grundy Value of piles[i] and store it for (int i=0; i<=n-1; i++) calculateGrundy(piles[i], Grundy); declareWinner(PLAYER2, piles, Grundy, n); ''' # This code is contributed by rutvik_56",
"e": 37225,
"s": 34150,
"text": null
},
{
"code": "using System;using System.Linq;using System.Collections.Generic; /* Game Description-\"A game is played between two players and there are N pilesof stones such that each pile has certain number of stones.On his/her turn, a player selects a pile and can take anynon-zero number of stones upto 3 (i.e- 1,2,3)The player who cannot move is considered to lose the game(i.e., one who take the last stone is the winner).Can you find which player wins the game if both players playoptimally (they don't make any mistake)? \" A Dynamic Programming approach to calculate Grundy Numberand Mex and find the Winner using Sprague - Grundy Theorem. */ class GFG{ /* piles[] -> Array having the initial count of stones/coins in each piles before the game has started.n -> Number of piles Grundy[] -> Array having the Grundy Number corresponding to the initial position of each piles in the game The piles[] and Grundy[] are having 0-based indexing*/ static int PLAYER1 = 1;//static int PLAYER2 = 2; // A Function to calculate Mex of all the values in that setstatic int calculateMex(HashSet<int> Set){ int Mex = 0; while (Set.Contains(Mex)) Mex++; return (Mex);} // A function to Compute Grundy Number of 'n'static int calculateGrundy(int n, int []Grundy){ Grundy[0] = 0; Grundy[1] = 1; Grundy[2] = 2; Grundy[3] = 3; if (Grundy[n] != -1) return (Grundy[n]); // A Hash Table HashSet<int> Set = new HashSet<int>(); for (int i = 1; i <= 3; i++) Set.Add(calculateGrundy (n - i, Grundy)); // Store the result Grundy[n] = calculateMex (Set); return (Grundy[n]);} // A function to declare the winner of the gamestatic void declareWinner(int whoseTurn, int []piles, int []Grundy, int n){ int xorValue = Grundy[piles[0]]; for (int i = 1; i <= n - 1; i++) xorValue = xorValue ^ Grundy[piles[i]]; if (xorValue != 0) { if (whoseTurn == PLAYER1) Console.Write(\"Player 1 will win\\n\"); else Console.Write(\"Player 2 will win\\n\"); } else { if (whoseTurn == PLAYER1) Console.Write(\"Player 2 will win\\n\"); else Console.Write(\"Player 1 will win\\n\"); } return;} // Driver codestatic void Main(){ // Test Case 1 int []piles = {3, 4, 5}; int n = piles.Length; // Find the maximum element int maximum = piles.Max(); // An array to cache the sub-problems so that // re-computation of same sub-problems is avoided int []Grundy = new int[maximum + 1]; Array.Fill(Grundy, -1); // Calculate Grundy Value of piles[i] and store it for (int i = 0; i <= n - 1; i++) calculateGrundy(piles[i], Grundy); declareWinner(PLAYER1, piles, Grundy, n); /* Test Case 2 int piles[] = {3, 8, 2}; int n = sizeof(piles)/sizeof(piles[0]); int maximum = *max_element (piles, piles + n); // An array to cache the sub-problems so that // re-computation of same sub-problems is avoided int Grundy [maximum + 1]; memset(Grundy, -1, sizeof (Grundy)); // Calculate Grundy Value of piles[i] and store it for (int i=0; i<=n-1; i++) calculateGrundy(piles[i], Grundy); declareWinner(PLAYER2, piles, Grundy, n); */ }} // This code is contributed by mits",
"e": 40536,
"s": 37225,
"text": null
},
{
"code": "<script> /* Game Description-\"A game is played between two players and there are N pilesof stones such that each pile has certain number of stones.On his/her turn, a player selects a pile and can take anynon-zero number of stones upto 3 (i.e- 1,2,3)The player who cannot move is considered to lose the game(i.e., one who take the last stone is the winner).Can you find which player wins the game if both players playoptimally (they don't make any mistake)? \" A Dynamic Programming approach to calculate Grundy Numberand Mex and find the Winner using Sprague - Grundy Theorem. */ /* piles[] -> Array having the initial count of stones/coins in each piles before the game has started.n -> Number of piles Grundy[] -> Array having the Grundy Number corresponding to the initial position of each piles in the game The piles[] and Grundy[] are having 0-based indexing*/let PLAYER1 = 1;let PLAYER2 = 2; // A Function to calculate Mex of all the values in that setfunction calculateMex(Set){ let Mex = 0; while (Set.has(Mex)) Mex++; return (Mex);} // A function to Compute Grundy Number of 'n'function calculateGrundy(n,Grundy){ Grundy[0] = 0; Grundy[1] = 1; Grundy[2] = 2; Grundy[3] = 3; if (Grundy[n] != -1) return (Grundy[n]); // A Hash Table let Set = new Set(); for (let i = 1; i <= 3; i++) Set.add(calculateGrundy (n - i, Grundy)); // Store the result Grundy[n] = calculateMex (Set); return (Grundy[n]);} // A function to declare the winner of the gamefunction declareWinner(whoseTurn,piles,Grundy,n){ let xorValue = Grundy[piles[0]]; for (let i = 1; i <= n - 1; i++) xorValue = xorValue ^ Grundy[piles[i]]; if (xorValue != 0) { if (whoseTurn == PLAYER1) document.write(\"Player 1 will win<br>\"); else document.write(\"Player 2 will win<br>\"); } else { if (whoseTurn == PLAYER1) document.write(\"Player 2 will win<br>\"); else document.write(\"Player 1 will win<br>\"); } return;} // Driver code // Test Case 1 let piles = [3, 4, 5]; let n = piles.length; // Find the maximum element let maximum = Math.max(...piles) // An array to cache the sub-problems so that // re-computation of same sub-problems is avoided let Grundy = new Array(maximum + 1); for(let i=0;i<maximum+1;i++) Grundy[i]=0; // Calculate Grundy Value of piles[i] and store it for (let i = 0; i <= n - 1; i++) calculateGrundy(piles[i], Grundy); declareWinner(PLAYER1, piles, Grundy, n); /* Test Case 2 int piles[] = {3, 8, 2}; int n = sizeof(piles)/sizeof(piles[0]); int maximum = *max_element (piles, piles + n); // An array to cache the sub-problems so that // re-computation of same sub-problems is avoided int Grundy [maximum + 1]; memset(Grundy, -1, sizeof (Grundy)); // Calculate Grundy Value of piles[i] and store it for (int i=0; i<=n-1; i++) calculateGrundy(piles[i], Grundy); declareWinner(PLAYER2, piles, Grundy, n); */ // This code is contributed by avanitrachhadiya2155</script>",
"e": 43726,
"s": 40536,
"text": null
},
{
"code": null,
"e": 43736,
"s": 43726,
"text": "Output : "
},
{
"code": null,
"e": 43754,
"s": 43736,
"text": "Player 1 will win"
},
{
"code": null,
"e": 43828,
"s": 43754,
"text": "References : https://en.wikipedia.org/wiki/Sprague%E2%80%93Grundy_theorem"
},
{
"code": null,
"e": 44217,
"s": 43828,
"text": "Exercise to the Readers: Consider the below game. “A game is played by two players with N integers A1, A2, .., AN. On his/her turn, a player selects an integer, divides it by 2, 3, or 6, and then takes the floor. If the integer becomes 0, it is removed. The last player to move wins. Which player wins the game if both players play optimally?”Hint : See the example 3 of previous article."
},
{
"code": null,
"e": 44612,
"s": 44217,
"text": "This article is contributed by Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 44621,
"s": 44612,
"text": "vinayb21"
},
{
"code": null,
"e": 44635,
"s": 44621,
"text": "princiraj1992"
},
{
"code": null,
"e": 44648,
"s": 44635,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 44658,
"s": 44648,
"text": "rutvik_56"
},
{
"code": null,
"e": 44679,
"s": 44658,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 44694,
"s": 44679,
"text": "adnanirshad158"
},
{
"code": null,
"e": 44708,
"s": 44694,
"text": "Combinatorial"
},
{
"code": null,
"e": 44720,
"s": 44708,
"text": "Game Theory"
},
{
"code": null,
"e": 44733,
"s": 44720,
"text": "Mathematical"
},
{
"code": null,
"e": 44746,
"s": 44733,
"text": "Mathematical"
},
{
"code": null,
"e": 44758,
"s": 44746,
"text": "Game Theory"
},
{
"code": null,
"e": 44772,
"s": 44758,
"text": "Combinatorial"
},
{
"code": null,
"e": 44870,
"s": 44772,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 44879,
"s": 44870,
"text": "Comments"
},
{
"code": null,
"e": 44892,
"s": 44879,
"text": "Old Comments"
},
{
"code": null,
"e": 44910,
"s": 44892,
"text": "Combinational Sum"
},
{
"code": null,
"e": 44965,
"s": 44910,
"text": "Count ways to reach the nth stair using step 1, 2 or 3"
},
{
"code": null,
"e": 45002,
"s": 44965,
"text": "Count of subsets with sum equal to X"
},
{
"code": null,
"e": 45087,
"s": 45002,
"text": "Print all possible strings of length k that can be formed from a set of n characters"
},
{
"code": null,
"e": 45164,
"s": 45087,
"text": "Find the Number of Permutations that satisfy the given condition in an array"
},
{
"code": null,
"e": 45199,
"s": 45164,
"text": "Implementation of Tic-Tac-Toe game"
},
{
"code": null,
"e": 45278,
"s": 45199,
"text": "Minimax Algorithm in Game Theory | Set 2 (Introduction to Evaluation Function)"
},
{
"code": null,
"e": 45314,
"s": 45278,
"text": "Expectimax Algorithm in Game Theory"
},
{
"code": null,
"e": 45380,
"s": 45314,
"text": "Game Theory (Normal-form game) | Set 3 (Game with Mixed Strategy)"
}
]
|
Arithmetic Encoding and Decoding Using MATLAB - GeeksforGeeks | 17 Aug, 2020
Arithmetic coding is a type of entropy encoding utilized in lossless data compression. Ordinarily, a string of characters, for example, the words “hey” is represented for utilizing a fixed number of bits per character.
In the most straightforward case, the probability of every symbol occurring is equivalent. For instance, think about a set of three symbols, A, B, and C, each similarly prone to happen. Straightforward block encoding would require 2 bits for every symbol, which is inefficient as one of the bit varieties is rarely utilized.In other words, A = 00, B = 01, and C = 10, however, 11 is unused. An increasingly productive arrangement is to speak to a succession of these three symbols as a rational number in base 3 where every digit speaks to a symbol. For instance, the arrangement “ABBCAB” could become 0.011201. In arithmetic coding as an incentive in the stretch [0, 1). The subsequent stage is to encode this ternary number utilizing a fixed-guide paired number of adequate exactness toward recuperating it, for example, 0.00101100102 — this is just 10 bits. This is achievable for long arrangements in light of the fact that there are productive, set up calculations for changing over the base of subjectively exact numbers.
When all is said and done, arithmetic coders can deliver close ideal output for some random arrangement of symbols and probabilities (the ideal value is – log2P bits for every symbol of likelihood P). Compression algorithms that utilize arithmetic coding go by deciding a structure of the data – fundamentally an expectation of what examples will be found in the symbols of the message. The more precise this prediction is, the closer to ideal the output will be.
When all is said and done, each progression of the encoding procedure, aside from the absolute last, is the equivalent; the encoder has fundamentally only three bits of information to consider: The following symbol that should be encoded. The current span (at the very beginning of the encoding procedure, the stretch is set to [0,1], yet that will change) The probabilities the model allows to every one of the different symbols that are conceivable at this stage (as referenced prior, higher-request or versatile models imply that these probabilities are not really the equivalent in each progression.) The encoder isolates the current span into sub-spans, each speaking to a small amount of the current span relative to the likelihood of that symbol in the current setting. Whichever stretch relates to the real symbol that is close to being encoded turns into the span utilized in the subsequent stage. At the point when the sum total of what symbols have been encoded, the subsequent span unambiguously recognizes the arrangement of symbols that delivered it. Any individual who has a similar last span and model that is being utilized can remake the symbol succession that more likely than not entered the encoder to bring about that last stretch. It isn’t important to transmit the last stretch, in any case; it is just important to transmit one division that exists in that span. Specifically, it is just important to transmit enough digits (in whatever base) of the part so all divisions that start with those digits fall into the last stretch; this will ensure that the subsequent code is a prefix code.
Encoding
% input stringstr = 'GeeksforGeeks';fprintf('The entered string is : %s\n', str); % length of the stringlen = length(str);fprintf('The length of the string is : %d\n', len); % get unique characters from the stringu = unique(str);fprintf('The unique characters are : %s\n', u); % length of the unique characters stringlen_unique = length(u);fprintf('The length of unique character string is : %d\n', len_unique); % General lookup table % get zeros of length of unique charactersz = zeros(1, len_unique);p = zeros(1, len_unique); for i = 1 : len_unique % in 'z' variable we will find the % occurrence of each characters from 'str' z(i) = length(findstr(str, u(i))); % in 'p' variable we will get % probability of those occurrences p(i) = z(i) / len;enddisplay(z);display(p); % in 'cpr' variable we will get the cumulative % summation of 'p' from '1' till last value of 'p'cpr = cumsum(p); % in 'newcpr' variable we are taking % 'cpr' from '0' till last value of 'p' newcpr = [0 cpr]; display(cpr);display(newcpr); % make table till 'len_unique' sizefor i = 1 : len_unique % in first column we are then % placing 'newcpr' values interval(i, 1) = newcpr(i); % in second column we are % placing 'cpr' values interval(i, 2) = cpr(i);end % Displaying the lookup tabledisplay('The lookip table is : ')display(interval); % Encoder Table low = 0;high = 1;for i = 1 : len for j = 1 : len_unique % if the value from 'str' % matches with 'u' then if str(i) == u(j); pos = j; j = j + 1; % displaying the matched length % of unique characters display(pos); % getting the tag value % of the matched character range = high - low; high = low + (range .* interval(pos, 2)); low = low + (range .* interval(pos, 1)); i = i + 1; break end endend % displaying tag valuetag = low;display(tag);
Output :
The entered string is : GeeksforGeeks
The length of the string is : 13
The unique characters are : Gefkors
The length of unique character string is : 7
z =
2 4 1 2 1 1 2
p =
0.1538 0.3077 0.0769 0.1538 0.0769 0.0769 0.1538
cpr =
0.1538 0.4615 0.5385 0.6923 0.7692 0.8462 1.0000
newcpr =
0 0.1538 0.4615 0.5385 0.6923 0.7692 0.8462 1.0000
The lookip table is :
interval =
0 0.1538
0.1538 0.4615
0.4615 0.5385
0.5385 0.6923
0.6923 0.7692
0.7692 0.8462
0.8462 1.0000
pos =
1
pos =
2
pos =
2
pos =
4
pos =
7
pos =
3
pos =
5
pos =
6
pos =
1
pos =
2
pos =
2
pos =
4
pos =
7
tag =
0.0409
Decoding
str = ''; for i = 1 : len for j = 1 : len_unique % If tag value falls between a certain % range in lookup table then if tag > interval(j, 1) && tag < interval(j, 2) pos = j; tag = (tag - interval(pos, 1)) / p(j); % Geeting the matched tag % value character decoded_str = u(pos); % String concatenating % 'decoded_str' into 'str' str = strcat(str, decoded_str); break end endend % Displaying final decoded stringdisp(str)
Output :
GeeksforGeeks
MATLAB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
ML | Linear Regression
Decision Tree
Copying Files to and from Docker Containers
System Design Tutorial
Python | Decision tree implementation
Decision Tree Introduction with example
Reinforcement learning
ML | Underfitting and Overfitting
ML | Label Encoding of datasets in Python
Docker - COPY Instruction | [
{
"code": null,
"e": 24211,
"s": 24183,
"text": "\n17 Aug, 2020"
},
{
"code": null,
"e": 24430,
"s": 24211,
"text": "Arithmetic coding is a type of entropy encoding utilized in lossless data compression. Ordinarily, a string of characters, for example, the words “hey” is represented for utilizing a fixed number of bits per character."
},
{
"code": null,
"e": 25458,
"s": 24430,
"text": "In the most straightforward case, the probability of every symbol occurring is equivalent. For instance, think about a set of three symbols, A, B, and C, each similarly prone to happen. Straightforward block encoding would require 2 bits for every symbol, which is inefficient as one of the bit varieties is rarely utilized.In other words, A = 00, B = 01, and C = 10, however, 11 is unused. An increasingly productive arrangement is to speak to a succession of these three symbols as a rational number in base 3 where every digit speaks to a symbol. For instance, the arrangement “ABBCAB” could become 0.011201. In arithmetic coding as an incentive in the stretch [0, 1). The subsequent stage is to encode this ternary number utilizing a fixed-guide paired number of adequate exactness toward recuperating it, for example, 0.00101100102 — this is just 10 bits. This is achievable for long arrangements in light of the fact that there are productive, set up calculations for changing over the base of subjectively exact numbers."
},
{
"code": null,
"e": 25922,
"s": 25458,
"text": "When all is said and done, arithmetic coders can deliver close ideal output for some random arrangement of symbols and probabilities (the ideal value is – log2P bits for every symbol of likelihood P). Compression algorithms that utilize arithmetic coding go by deciding a structure of the data – fundamentally an expectation of what examples will be found in the symbols of the message. The more precise this prediction is, the closer to ideal the output will be."
},
{
"code": null,
"e": 27536,
"s": 25922,
"text": "When all is said and done, each progression of the encoding procedure, aside from the absolute last, is the equivalent; the encoder has fundamentally only three bits of information to consider: The following symbol that should be encoded. The current span (at the very beginning of the encoding procedure, the stretch is set to [0,1], yet that will change) The probabilities the model allows to every one of the different symbols that are conceivable at this stage (as referenced prior, higher-request or versatile models imply that these probabilities are not really the equivalent in each progression.) The encoder isolates the current span into sub-spans, each speaking to a small amount of the current span relative to the likelihood of that symbol in the current setting. Whichever stretch relates to the real symbol that is close to being encoded turns into the span utilized in the subsequent stage. At the point when the sum total of what symbols have been encoded, the subsequent span unambiguously recognizes the arrangement of symbols that delivered it. Any individual who has a similar last span and model that is being utilized can remake the symbol succession that more likely than not entered the encoder to bring about that last stretch. It isn’t important to transmit the last stretch, in any case; it is just important to transmit one division that exists in that span. Specifically, it is just important to transmit enough digits (in whatever base) of the part so all divisions that start with those digits fall into the last stretch; this will ensure that the subsequent code is a prefix code."
},
{
"code": null,
"e": 27545,
"s": 27536,
"text": "Encoding"
},
{
"code": "% input stringstr = 'GeeksforGeeks';fprintf('The entered string is : %s\\n', str); % length of the stringlen = length(str);fprintf('The length of the string is : %d\\n', len); % get unique characters from the stringu = unique(str);fprintf('The unique characters are : %s\\n', u); % length of the unique characters stringlen_unique = length(u);fprintf('The length of unique character string is : %d\\n', len_unique); % General lookup table % get zeros of length of unique charactersz = zeros(1, len_unique);p = zeros(1, len_unique); for i = 1 : len_unique % in 'z' variable we will find the % occurrence of each characters from 'str' z(i) = length(findstr(str, u(i))); % in 'p' variable we will get % probability of those occurrences p(i) = z(i) / len;enddisplay(z);display(p); % in 'cpr' variable we will get the cumulative % summation of 'p' from '1' till last value of 'p'cpr = cumsum(p); % in 'newcpr' variable we are taking % 'cpr' from '0' till last value of 'p' newcpr = [0 cpr]; display(cpr);display(newcpr); % make table till 'len_unique' sizefor i = 1 : len_unique % in first column we are then % placing 'newcpr' values interval(i, 1) = newcpr(i); % in second column we are % placing 'cpr' values interval(i, 2) = cpr(i);end % Displaying the lookup tabledisplay('The lookip table is : ')display(interval); % Encoder Table low = 0;high = 1;for i = 1 : len for j = 1 : len_unique % if the value from 'str' % matches with 'u' then if str(i) == u(j); pos = j; j = j + 1; % displaying the matched length % of unique characters display(pos); % getting the tag value % of the matched character range = high - low; high = low + (range .* interval(pos, 2)); low = low + (range .* interval(pos, 1)); i = i + 1; break end endend % displaying tag valuetag = low;display(tag);",
"e": 29525,
"s": 27545,
"text": null
},
{
"code": null,
"e": 29534,
"s": 29525,
"text": "Output :"
},
{
"code": null,
"e": 30399,
"s": 29534,
"text": "The entered string is : GeeksforGeeks\nThe length of the string is : 13\nThe unique characters are : Gefkors\nThe length of unique character string is : 7\n\nz =\n\n 2 4 1 2 1 1 2\n\n\np =\n\n 0.1538 0.3077 0.0769 0.1538 0.0769 0.0769 0.1538\n\n\ncpr =\n\n 0.1538 0.4615 0.5385 0.6923 0.7692 0.8462 1.0000\n\n\nnewcpr =\n\n 0 0.1538 0.4615 0.5385 0.6923 0.7692 0.8462 1.0000\n\nThe lookip table is : \n\ninterval =\n\n 0 0.1538\n 0.1538 0.4615\n 0.4615 0.5385\n 0.5385 0.6923\n 0.6923 0.7692\n 0.7692 0.8462\n 0.8462 1.0000\n\n\npos =\n\n 1\n\n\npos =\n\n 2\n\n\npos =\n\n 2\n\n\npos =\n\n 4\n\n\npos =\n\n 7\n\n\npos =\n\n 3\n\n\npos =\n\n 5\n\n\npos =\n\n 6\n\n\npos =\n\n 1\n\n\npos =\n\n 2\n\n\npos =\n\n 2\n\n\npos =\n\n 4\n\n\npos =\n\n 7\n\n\ntag =\n\n 0.0409\n"
},
{
"code": null,
"e": 30408,
"s": 30399,
"text": "Decoding"
},
{
"code": "str = ''; for i = 1 : len for j = 1 : len_unique % If tag value falls between a certain % range in lookup table then if tag > interval(j, 1) && tag < interval(j, 2) pos = j; tag = (tag - interval(pos, 1)) / p(j); % Geeting the matched tag % value character decoded_str = u(pos); % String concatenating % 'decoded_str' into 'str' str = strcat(str, decoded_str); break end endend % Displaying final decoded stringdisp(str)",
"e": 30963,
"s": 30408,
"text": null
},
{
"code": null,
"e": 30972,
"s": 30963,
"text": "Output :"
},
{
"code": null,
"e": 30986,
"s": 30972,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 30993,
"s": 30986,
"text": "MATLAB"
},
{
"code": null,
"e": 31019,
"s": 30993,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 31117,
"s": 31019,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31126,
"s": 31117,
"text": "Comments"
},
{
"code": null,
"e": 31139,
"s": 31126,
"text": "Old Comments"
},
{
"code": null,
"e": 31162,
"s": 31139,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 31176,
"s": 31162,
"text": "Decision Tree"
},
{
"code": null,
"e": 31220,
"s": 31176,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 31243,
"s": 31220,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 31281,
"s": 31243,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 31321,
"s": 31281,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 31344,
"s": 31321,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 31378,
"s": 31344,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 31420,
"s": 31378,
"text": "ML | Label Encoding of datasets in Python"
}
]
|
Count Fibonacci numbers in given range in O(Log n) time and O(1) space - GeeksforGeeks | 28 Jun, 2021
Given a range, count Fibonacci numbers in given range. First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 141, .. Example :
Input: low = 10, high = 100
Output: 5
There are five Fibonacci numbers in given
range, the numbers are 13, 21, 34, 55 and 89.
Input: low = 10, high = 20
Output: 1
There is only one Fibonacci Number, 13.
Input: low = 0, high = 1
Output: 3
Fibonacci numbers are 0, 1 and 1
We strongly recommend you to minimize your browser and try this yourself first. A Brute Force Solution is to one by one find all Fibonacci Numbers and count all Fibonacci numbers in given rangeAn Efficient Solution is to use previous Fibonacci Number to generate next using simple Fibonacci formula that fn = fn-1 + fn-2.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to count Fibonacci numbers in given range#include <bits/stdc++.h>using namespace std; // Returns count of fibonacci numbers in [low, high]int countFibs(int low, int high){ // Initialize first three Fibonacci Numbers int f1 = 0, f2 = 1, f3 = 1; // Count fibonacci numbers in given range int result = 0; while (f1 <= high) { if (f1 >= low) result++; f1 = f2; f2 = f3; f3 = f1 + f2; } return result;} // Driver programint main(){int low = 10, high = 100;cout << "Count of Fibonacci Numbers is " << countFibs(low, high);return 0;}
// Java program to count Fibonacci numbers in given rangeimport java.io.*; class GFG { // Returns count of fibonacci numbers in [low, high] public static int countFibs(int low, int high) { // Initialize first three Fibonacci Numbers int f1 = 0, f2 = 1, f3 = 1; // Count fibonacci numbers in given range int result = 0; while (f1 <= high) { if (f1 >= low) result++; f1 = f2; f2 = f3; f3 = f1 + f2; } return result; } // Driver program public static void main(String[] args) { int low = 10, high = 100; System.out.println("Count of Fibonacci Numbers is " + countFibs(low, high)); }} // This code is contributed by RohitOberoi.
# Python3 program to count Fibonacci# numbers in given range # Returns count of fibonacci# numbers in [low, high]def countFibs(low, high): # Initialize first three # Fibonacci Numbers f1, f2, f3 = 0, 1, 1 # Count fibonacci numbers in # given range result = 0 while (f1 <= high): if (f1 >= low): result += 1 f1 = f2 f2 = f3 f3 = f1 + f2 return result # Driver Codelow, high = 10, 100print("Count of Fibonacci Numbers is", countFibs(low, high)) # This code is contributed# by mohit kumar
// C# program to count Fibonacci// numbers in given rangeusing System; public class GFG{ // Returns count of fibonacci // numbers in [low, high] static int countFibs(int low, int high) { // Initialize first three // Fibonacci Numbers int f1 = 0, f2 = 1, f3 = 1; // Count fibonacci numbers // in given range int result = 0; while (f1 <= high) { if (f1 >= low) result++; f1 = f2; f2 = f3; f3 = f1 + f2; } return result; } // Driver Code public static void Main(String []args) { int low = 10, high = 100; Console.WriteLine("Count of Fibonacci Numbers is " + countFibs(low, high)); }} // This code is contributed by Sam007.
<?php// PHP program to count// Fibonacci numbers in// given range // Returns count of fibonacci// numbers in [low, high]function countFibs($low, $high){ // Initialize first // three Fibonacci Numbers $f1 = 0; $f2 = 1; $f3 = 1; // Count fibonacci // numbers in given range $result = 0; while ($f1 <= $high) { if ($f1 >= $low) $result++; $f1 = $f2; $f2 = $f3; $f3 = $f1 + $f2; } return $result;} // Driver Code$low = 10; $high = 100;echo "Count of Fibonacci Numbers is ", countFibs($low, $high); // This code is contributed by nitin mittal.?>
<script> // JavaScript program to count Fibonacci// numbers in given range // Returns count of fibonacci // numbers in [low, high] function countFibs(low, high) { // Initialize first three // Fibonacci Numbers let f1 = 0, f2 = 1, f3 = 1; // Count fibonacci numbers // in given range let result = 0; while (f1 <= high) { if (f1 >= low) result++; f1 = f2; f2 = f3; f3 = f1 + f2; } return result; } // Driver program let low = 10, high = 100; document.write("Count of Fibonacci Numbers is " + countFibs(low, high)); // This code is contributed by susmitakundugoaldanga.</script>
Output :
Count of Fibonacci Numbers is 5
Time Complexity Analysis: Consider the that Fibonacci Numbers can be written as below So the value of Fibonacci numbers grow exponentially. It means that the while loop grows exponentially till it reaches ‘high’. So the loop runs O(Log (high)) times. One solution could be directly use above formula to find count of Fibonacci Numbers, but that is not practically feasible (See this for details).Auxiliary Space: O(1)This article is contributed by Sudhanshu Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Sam007
nitin mittal
mohit kumar 29
susmitakundugoaldanga
RohitOberoi
Fibonacci
Algorithms
Fibonacci
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Introduction to Algorithms
Converting Roman Numerals to Decimal lying between 1 to 3999
Quick Sort vs Merge Sort
Program for SSTF disk scheduling algorithm
Quadratic Probing in Hashing
Cyclomatic Complexity
Difference Between Symmetric and Asymmetric Key Encryption
Rail Fence Cipher - Encryption and Decryption | [
{
"code": null,
"e": 24754,
"s": 24726,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24901,
"s": 24754,
"text": "Given a range, count Fibonacci numbers in given range. First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 141, .. Example : "
},
{
"code": null,
"e": 25174,
"s": 24901,
"text": "Input: low = 10, high = 100\nOutput: 5\nThere are five Fibonacci numbers in given\nrange, the numbers are 13, 21, 34, 55 and 89.\n\nInput: low = 10, high = 20\nOutput: 1\nThere is only one Fibonacci Number, 13.\n\nInput: low = 0, high = 1\nOutput: 3\nFibonacci numbers are 0, 1 and 1"
},
{
"code": null,
"e": 25497,
"s": 25174,
"text": "We strongly recommend you to minimize your browser and try this yourself first. A Brute Force Solution is to one by one find all Fibonacci Numbers and count all Fibonacci numbers in given rangeAn Efficient Solution is to use previous Fibonacci Number to generate next using simple Fibonacci formula that fn = fn-1 + fn-2. "
},
{
"code": null,
"e": 25503,
"s": 25499,
"text": "C++"
},
{
"code": null,
"e": 25508,
"s": 25503,
"text": "Java"
},
{
"code": null,
"e": 25516,
"s": 25508,
"text": "Python3"
},
{
"code": null,
"e": 25519,
"s": 25516,
"text": "C#"
},
{
"code": null,
"e": 25523,
"s": 25519,
"text": "PHP"
},
{
"code": null,
"e": 25534,
"s": 25523,
"text": "Javascript"
},
{
"code": "// C++ program to count Fibonacci numbers in given range#include <bits/stdc++.h>using namespace std; // Returns count of fibonacci numbers in [low, high]int countFibs(int low, int high){ // Initialize first three Fibonacci Numbers int f1 = 0, f2 = 1, f3 = 1; // Count fibonacci numbers in given range int result = 0; while (f1 <= high) { if (f1 >= low) result++; f1 = f2; f2 = f3; f3 = f1 + f2; } return result;} // Driver programint main(){int low = 10, high = 100;cout << \"Count of Fibonacci Numbers is \" << countFibs(low, high);return 0;}",
"e": 26145,
"s": 25534,
"text": null
},
{
"code": "// Java program to count Fibonacci numbers in given rangeimport java.io.*; class GFG { // Returns count of fibonacci numbers in [low, high] public static int countFibs(int low, int high) { // Initialize first three Fibonacci Numbers int f1 = 0, f2 = 1, f3 = 1; // Count fibonacci numbers in given range int result = 0; while (f1 <= high) { if (f1 >= low) result++; f1 = f2; f2 = f3; f3 = f1 + f2; } return result; } // Driver program public static void main(String[] args) { int low = 10, high = 100; System.out.println(\"Count of Fibonacci Numbers is \" + countFibs(low, high)); }} // This code is contributed by RohitOberoi.",
"e": 26947,
"s": 26145,
"text": null
},
{
"code": "# Python3 program to count Fibonacci# numbers in given range # Returns count of fibonacci# numbers in [low, high]def countFibs(low, high): # Initialize first three # Fibonacci Numbers f1, f2, f3 = 0, 1, 1 # Count fibonacci numbers in # given range result = 0 while (f1 <= high): if (f1 >= low): result += 1 f1 = f2 f2 = f3 f3 = f1 + f2 return result # Driver Codelow, high = 10, 100print(\"Count of Fibonacci Numbers is\", countFibs(low, high)) # This code is contributed# by mohit kumar",
"e": 27520,
"s": 26947,
"text": null
},
{
"code": "// C# program to count Fibonacci// numbers in given rangeusing System; public class GFG{ // Returns count of fibonacci // numbers in [low, high] static int countFibs(int low, int high) { // Initialize first three // Fibonacci Numbers int f1 = 0, f2 = 1, f3 = 1; // Count fibonacci numbers // in given range int result = 0; while (f1 <= high) { if (f1 >= low) result++; f1 = f2; f2 = f3; f3 = f1 + f2; } return result; } // Driver Code public static void Main(String []args) { int low = 10, high = 100; Console.WriteLine(\"Count of Fibonacci Numbers is \" + countFibs(low, high)); }} // This code is contributed by Sam007.",
"e": 28390,
"s": 27520,
"text": null
},
{
"code": "<?php// PHP program to count// Fibonacci numbers in// given range // Returns count of fibonacci// numbers in [low, high]function countFibs($low, $high){ // Initialize first // three Fibonacci Numbers $f1 = 0; $f2 = 1; $f3 = 1; // Count fibonacci // numbers in given range $result = 0; while ($f1 <= $high) { if ($f1 >= $low) $result++; $f1 = $f2; $f2 = $f3; $f3 = $f1 + $f2; } return $result;} // Driver Code$low = 10; $high = 100;echo \"Count of Fibonacci Numbers is \", countFibs($low, $high); // This code is contributed by nitin mittal.?>",
"e": 29013,
"s": 28390,
"text": null
},
{
"code": "<script> // JavaScript program to count Fibonacci// numbers in given range // Returns count of fibonacci // numbers in [low, high] function countFibs(low, high) { // Initialize first three // Fibonacci Numbers let f1 = 0, f2 = 1, f3 = 1; // Count fibonacci numbers // in given range let result = 0; while (f1 <= high) { if (f1 >= low) result++; f1 = f2; f2 = f3; f3 = f1 + f2; } return result; } // Driver program let low = 10, high = 100; document.write(\"Count of Fibonacci Numbers is \" + countFibs(low, high)); // This code is contributed by susmitakundugoaldanga.</script>",
"e": 29803,
"s": 29013,
"text": null
},
{
"code": null,
"e": 29813,
"s": 29803,
"text": "Output : "
},
{
"code": null,
"e": 29845,
"s": 29813,
"text": "Count of Fibonacci Numbers is 5"
},
{
"code": null,
"e": 30435,
"s": 29845,
"text": "Time Complexity Analysis: Consider the that Fibonacci Numbers can be written as below So the value of Fibonacci numbers grow exponentially. It means that the while loop grows exponentially till it reaches ‘high’. So the loop runs O(Log (high)) times. One solution could be directly use above formula to find count of Fibonacci Numbers, but that is not practically feasible (See this for details).Auxiliary Space: O(1)This article is contributed by Sudhanshu Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 30442,
"s": 30435,
"text": "Sam007"
},
{
"code": null,
"e": 30455,
"s": 30442,
"text": "nitin mittal"
},
{
"code": null,
"e": 30470,
"s": 30455,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 30492,
"s": 30470,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 30504,
"s": 30492,
"text": "RohitOberoi"
},
{
"code": null,
"e": 30514,
"s": 30504,
"text": "Fibonacci"
},
{
"code": null,
"e": 30525,
"s": 30514,
"text": "Algorithms"
},
{
"code": null,
"e": 30535,
"s": 30525,
"text": "Fibonacci"
},
{
"code": null,
"e": 30546,
"s": 30535,
"text": "Algorithms"
},
{
"code": null,
"e": 30644,
"s": 30546,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30693,
"s": 30644,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 30718,
"s": 30693,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 30745,
"s": 30718,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 30806,
"s": 30745,
"text": "Converting Roman Numerals to Decimal lying between 1 to 3999"
},
{
"code": null,
"e": 30831,
"s": 30806,
"text": "Quick Sort vs Merge Sort"
},
{
"code": null,
"e": 30874,
"s": 30831,
"text": "Program for SSTF disk scheduling algorithm"
},
{
"code": null,
"e": 30903,
"s": 30874,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 30925,
"s": 30903,
"text": "Cyclomatic Complexity"
},
{
"code": null,
"e": 30984,
"s": 30925,
"text": "Difference Between Symmetric and Asymmetric Key Encryption"
}
]
|
Top 10 new features of HTML5 | 15 Mar, 2021
HTML stands for Hypertext Markup Language, and it is the standard markup language for creating web pages and web applications. HTML5 is the 5th version of HTML. With invent of features in HTML5, it’s not only possible to create better websites, but we can also create dynamic websites.
Now let’s have a look at all the new features that were added in HTML5 that make it better than HTML :
Intro of audio and video: Audio and Video tags are the two major addition to HTML5. It allows developers to embed a video or audio on their website. HTML5 video can use CSS and CSS3 to style the video tag. You can change the border, opacity, reflections, gradients, transitions, transformations, and even animations. HTML5 makes adding video super-fast and without having to build a video player. This saves time for the developer and offers the client a superior and more affordable solution.Example:HTMLHTML<!DOCTYPE html><html><body><h2>Example of video and audio tag</h2> <video width = "300" height = "200" controls autoplay> <source src = "/html5/foo.ogg" type ="video/ogg" /> <source src = "/html5/foo.mp4" type = "video/mp4" /> Your browser does not support the video element. </video> <audio controls autoplay> <source src = "/html5/audio.ogg" type = "audio/ogg" /> <source src = "/html5/audio.wav" type = "audio/wav" /> Your browser does not support the audio element. </audio></body></html>Output: The resulting UI looks something like this:video outputVector Graphics: This is a new addition to the revised version which has hugely impacted the use of Adobe Flash in websites. It can be used to draw graphics with various shapes and colors via scripting usually JS. Vector graphics are scalable, easy to create and edit. It also supports interactivity and animation. Having a smaller file size makes transferring and loading graphics much faster on the web. That’s the reason why many people prefer to use vector graphics.Example:HTMLHTML<svg id = "svgelem" height = "200" xmlns = "http://www.abc.org/2000/svg"> <circle id = "redcircle" cx = "50" cy = "50" r = "50" fill = "red" /> </svg>Output:vector outputHeader and Footer: With these new tags, there is no longer a need to identify the two elements with a <div> tag. Footer is placed at the end of the web page while Header is placed at the start of the web page. By using <header> and <footer> HTML5 elements, the browser will know what to load first and what to load later. The header can contain-One or more heading elements (<h1> – <h6>)Logo or iconAuthorship informationFooter can contain-Authorship informationCopyright informationContact informationBack to top linksThey both have the same default CSS property as a display block.Layout of HTML vs HTML5Example: Below examples illustrate the <header> element in HTML:HTMLHTML<!DOCTYPE html> <html> <head> <title>Header Tag</title> </head> <body> <article> <header> <h1>This is the heading.</h1> <h4>This is the sub-heading.</h4> <p>This is the metadata.</p> </header> </article> </body> </html> Output:Example: Below examples illustrate the <footer> Tag in HTML elements:HTMLHTML<!DOCTYPE html> <html> <head> <title>HTML footer Tag</title> <style> a { font-size:25px; text-decoration:none; } p { font-size:25px; } </style> </head> <body> <footer> <nav> <p> <a href= "https://www.geeksforgeeks.org/about/">About Us</a>| <a href= "https://www.geeksforgeeks.org/privacy-policy/">Privacy Policy</a>| <a href= "https://www.geeksforgeeks.org/careers/">Careers</a> </p> </nav> <p>@geeksforgeeks, Some rights reserved</p> </footer> </body> </html> Output:Figure and Figcaption: HTML5 allows to use a <figure> element to mark up a photo in a document, and a <figcaption> element to define a caption for the photo. The <figcaption> tag defines a caption for a <figure> element. This tag provides a container for content that is equivalent to a figure. It can be used to group a caption with one or more images, a block of code, or other content.Example:HTMLHTML<figure> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/ download3.png" alt="GFG" style="width:50%"> <figcaption>Fig.1 - Geeksforgeeks.</figcaption></figure>Output:figure and figcaption outputNav tag: The <nav> tag defines a set of navigation links. It is used for the part of an internet site that links to different pages at the website. The hyperlinks can be organized through a number of approaches. Common examples of the nav elements are menus, tables, contents, and indexes. This element makes it much easier to create a navigation menu, creates a neat horizontal menu of text links, and helps screen reading software to correctly identify primary navigation areas in the document.Example:HTMLHTML<h1> HTML Nav tag</h1><nav> <a href="/html/">HTML</a> <a href="/css/">CSS</a> <a href="/js/">JavaScript</a> <a href="/jquery/">jQuery</a></nav>Output:Nav OutputProgress tag: The progress tag is used to check the progress of a task during the execution. Progress tag can be used with the conjunction of JavaScript.Example:HTMLHTML<h1>The progress element</h1> <label for="file">Downloading progress:</label><progress id="file" value="32" max="100"> 32% </progress>Output:Placeholder Attribute:The placeholder attribute specifies a short hint that describes the expected value of an input field/text area. The short hint is displayed in the field before the user enters a value.Example:HTMLHTML<!DOCTYPE html> <html> <body> <center> <h1 style="font-size:25px;font-style:italic;"> GeeksforGeeks </h1> <h2 style="font-size:25px;font-style:italic;"> Placeholder Attribute in Input Element </h2> <form action=" "> <input type="text" name="fname" placeholder="First name"> <br> <input type="text" name="lname" placeholder="Last name"> <br> <input type="submit" value="Submit"> </form> </center> </body> </html> Output:Email attribute:When the input type in the form set as email, then the browser gets the instruction from the code to write a valid format email. The input email id is automatically validated to check the format of the email id is correct or not.Example:HTMLHTML<!DOCTYPE html> <html> <head> <title> HTML input type email </title> </head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h2>HTML <input type ="email"></h2> <form> Email: <input type ="email" value="[email protected]"> </form> </body> </html>Output:Storage: In the case of HTML, we can use the browser as the temporary storage whereas, in the case of HTML5, application cache, web SQL database, and web storage is used.Ease of use: While HTML5 does have risks like constant updates, it is generally easy to keep up with the changes & updates because of simpler syntax as compared to other versions of HTML.
Intro of audio and video: Audio and Video tags are the two major addition to HTML5. It allows developers to embed a video or audio on their website. HTML5 video can use CSS and CSS3 to style the video tag. You can change the border, opacity, reflections, gradients, transitions, transformations, and even animations. HTML5 makes adding video super-fast and without having to build a video player. This saves time for the developer and offers the client a superior and more affordable solution.Example:HTMLHTML<!DOCTYPE html><html><body><h2>Example of video and audio tag</h2> <video width = "300" height = "200" controls autoplay> <source src = "/html5/foo.ogg" type ="video/ogg" /> <source src = "/html5/foo.mp4" type = "video/mp4" /> Your browser does not support the video element. </video> <audio controls autoplay> <source src = "/html5/audio.ogg" type = "audio/ogg" /> <source src = "/html5/audio.wav" type = "audio/wav" /> Your browser does not support the audio element. </audio></body></html>Output: The resulting UI looks something like this:video output
Audio and Video tags are the two major addition to HTML5. It allows developers to embed a video or audio on their website. HTML5 video can use CSS and CSS3 to style the video tag. You can change the border, opacity, reflections, gradients, transitions, transformations, and even animations. HTML5 makes adding video super-fast and without having to build a video player. This saves time for the developer and offers the client a superior and more affordable solution.
Example:
HTML
<!DOCTYPE html><html><body><h2>Example of video and audio tag</h2> <video width = "300" height = "200" controls autoplay> <source src = "/html5/foo.ogg" type ="video/ogg" /> <source src = "/html5/foo.mp4" type = "video/mp4" /> Your browser does not support the video element. </video> <audio controls autoplay> <source src = "/html5/audio.ogg" type = "audio/ogg" /> <source src = "/html5/audio.wav" type = "audio/wav" /> Your browser does not support the audio element. </audio></body></html>
Output: The resulting UI looks something like this:
video output
Vector Graphics: This is a new addition to the revised version which has hugely impacted the use of Adobe Flash in websites. It can be used to draw graphics with various shapes and colors via scripting usually JS. Vector graphics are scalable, easy to create and edit. It also supports interactivity and animation. Having a smaller file size makes transferring and loading graphics much faster on the web. That’s the reason why many people prefer to use vector graphics.Example:HTMLHTML<svg id = "svgelem" height = "200" xmlns = "http://www.abc.org/2000/svg"> <circle id = "redcircle" cx = "50" cy = "50" r = "50" fill = "red" /> </svg>Output:vector output
This is a new addition to the revised version which has hugely impacted the use of Adobe Flash in websites. It can be used to draw graphics with various shapes and colors via scripting usually JS. Vector graphics are scalable, easy to create and edit. It also supports interactivity and animation. Having a smaller file size makes transferring and loading graphics much faster on the web. That’s the reason why many people prefer to use vector graphics.
Example:
HTML
<svg id = "svgelem" height = "200" xmlns = "http://www.abc.org/2000/svg"> <circle id = "redcircle" cx = "50" cy = "50" r = "50" fill = "red" /> </svg>
vector output
Header and Footer: With these new tags, there is no longer a need to identify the two elements with a <div> tag. Footer is placed at the end of the web page while Header is placed at the start of the web page. By using <header> and <footer> HTML5 elements, the browser will know what to load first and what to load later. The header can contain-One or more heading elements (<h1> – <h6>)Logo or iconAuthorship informationFooter can contain-Authorship informationCopyright informationContact informationBack to top linksThey both have the same default CSS property as a display block.Layout of HTML vs HTML5Example: Below examples illustrate the <header> element in HTML:HTMLHTML<!DOCTYPE html> <html> <head> <title>Header Tag</title> </head> <body> <article> <header> <h1>This is the heading.</h1> <h4>This is the sub-heading.</h4> <p>This is the metadata.</p> </header> </article> </body> </html> Output:Example: Below examples illustrate the <footer> Tag in HTML elements:HTMLHTML<!DOCTYPE html> <html> <head> <title>HTML footer Tag</title> <style> a { font-size:25px; text-decoration:none; } p { font-size:25px; } </style> </head> <body> <footer> <nav> <p> <a href= "https://www.geeksforgeeks.org/about/">About Us</a>| <a href= "https://www.geeksforgeeks.org/privacy-policy/">Privacy Policy</a>| <a href= "https://www.geeksforgeeks.org/careers/">Careers</a> </p> </nav> <p>@geeksforgeeks, Some rights reserved</p> </footer> </body> </html> Output:
With these new tags, there is no longer a need to identify the two elements with a <div> tag. Footer is placed at the end of the web page while Header is placed at the start of the web page. By using <header> and <footer> HTML5 elements, the browser will know what to load first and what to load later.
The header can contain-
One or more heading elements (<h1> – <h6>)
Logo or icon
Authorship information
Footer can contain-
Authorship information
Copyright information
Contact information
Back to top links
They both have the same default CSS property as a display block.
Layout of HTML vs HTML5
Example: Below examples illustrate the <header> element in HTML:
HTML
<!DOCTYPE html> <html> <head> <title>Header Tag</title> </head> <body> <article> <header> <h1>This is the heading.</h1> <h4>This is the sub-heading.</h4> <p>This is the metadata.</p> </header> </article> </body> </html>
Output:
Example: Below examples illustrate the <footer> Tag in HTML elements:
HTML
<!DOCTYPE html> <html> <head> <title>HTML footer Tag</title> <style> a { font-size:25px; text-decoration:none; } p { font-size:25px; } </style> </head> <body> <footer> <nav> <p> <a href= "https://www.geeksforgeeks.org/about/">About Us</a>| <a href= "https://www.geeksforgeeks.org/privacy-policy/">Privacy Policy</a>| <a href= "https://www.geeksforgeeks.org/careers/">Careers</a> </p> </nav> <p>@geeksforgeeks, Some rights reserved</p> </footer> </body> </html>
Output:
Figure and Figcaption: HTML5 allows to use a <figure> element to mark up a photo in a document, and a <figcaption> element to define a caption for the photo. The <figcaption> tag defines a caption for a <figure> element. This tag provides a container for content that is equivalent to a figure. It can be used to group a caption with one or more images, a block of code, or other content.Example:HTMLHTML<figure> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/ download3.png" alt="GFG" style="width:50%"> <figcaption>Fig.1 - Geeksforgeeks.</figcaption></figure>Output:figure and figcaption output
HTML5 allows to use a <figure> element to mark up a photo in a document, and a <figcaption> element to define a caption for the photo. The <figcaption> tag defines a caption for a <figure> element. This tag provides a container for content that is equivalent to a figure. It can be used to group a caption with one or more images, a block of code, or other content.
Example:
HTML
<figure> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/ download3.png" alt="GFG" style="width:50%"> <figcaption>Fig.1 - Geeksforgeeks.</figcaption></figure>
figure and figcaption output
Nav tag: The <nav> tag defines a set of navigation links. It is used for the part of an internet site that links to different pages at the website. The hyperlinks can be organized through a number of approaches. Common examples of the nav elements are menus, tables, contents, and indexes. This element makes it much easier to create a navigation menu, creates a neat horizontal menu of text links, and helps screen reading software to correctly identify primary navigation areas in the document.Example:HTMLHTML<h1> HTML Nav tag</h1><nav> <a href="/html/">HTML</a> <a href="/css/">CSS</a> <a href="/js/">JavaScript</a> <a href="/jquery/">jQuery</a></nav>Output:Nav Output
The <nav> tag defines a set of navigation links. It is used for the part of an internet site that links to different pages at the website. The hyperlinks can be organized through a number of approaches. Common examples of the nav elements are menus, tables, contents, and indexes. This element makes it much easier to create a navigation menu, creates a neat horizontal menu of text links, and helps screen reading software to correctly identify primary navigation areas in the document.
Example:
HTML
<h1> HTML Nav tag</h1><nav> <a href="/html/">HTML</a> <a href="/css/">CSS</a> <a href="/js/">JavaScript</a> <a href="/jquery/">jQuery</a></nav>
Nav Output
Progress tag: The progress tag is used to check the progress of a task during the execution. Progress tag can be used with the conjunction of JavaScript.Example:HTMLHTML<h1>The progress element</h1> <label for="file">Downloading progress:</label><progress id="file" value="32" max="100"> 32% </progress>Output:
The progress tag is used to check the progress of a task during the execution. Progress tag can be used with the conjunction of JavaScript.
HTML
<h1>The progress element</h1> <label for="file">Downloading progress:</label><progress id="file" value="32" max="100"> 32% </progress>
Placeholder Attribute:The placeholder attribute specifies a short hint that describes the expected value of an input field/text area. The short hint is displayed in the field before the user enters a value.Example:HTMLHTML<!DOCTYPE html> <html> <body> <center> <h1 style="font-size:25px;font-style:italic;"> GeeksforGeeks </h1> <h2 style="font-size:25px;font-style:italic;"> Placeholder Attribute in Input Element </h2> <form action=" "> <input type="text" name="fname" placeholder="First name"> <br> <input type="text" name="lname" placeholder="Last name"> <br> <input type="submit" value="Submit"> </form> </center> </body> </html> Output:
Example:
HTML
<!DOCTYPE html> <html> <body> <center> <h1 style="font-size:25px;font-style:italic;"> GeeksforGeeks </h1> <h2 style="font-size:25px;font-style:italic;"> Placeholder Attribute in Input Element </h2> <form action=" "> <input type="text" name="fname" placeholder="First name"> <br> <input type="text" name="lname" placeholder="Last name"> <br> <input type="submit" value="Submit"> </form> </center> </body> </html>
Output:
Email attribute:When the input type in the form set as email, then the browser gets the instruction from the code to write a valid format email. The input email id is automatically validated to check the format of the email id is correct or not.Example:HTMLHTML<!DOCTYPE html> <html> <head> <title> HTML input type email </title> </head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h2>HTML <input type ="email"></h2> <form> Email: <input type ="email" value="[email protected]"> </form> </body> </html>Output:
HTML
<!DOCTYPE html> <html> <head> <title> HTML input type email </title> </head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h2>HTML <input type ="email"></h2> <form> Email: <input type ="email" value="[email protected]"> </form> </body> </html>
Storage: In the case of HTML, we can use the browser as the temporary storage whereas, in the case of HTML5, application cache, web SQL database, and web storage is used.
In the case of HTML, we can use the browser as the temporary storage whereas, in the case of HTML5, application cache, web SQL database, and web storage is used.
Ease of use: While HTML5 does have risks like constant updates, it is generally easy to keep up with the changes & updates because of simpler syntax as compared to other versions of HTML.
While HTML5 does have risks like constant updates, it is generally easy to keep up with the changes & updates because of simpler syntax as compared to other versions of HTML.
There are a lot more tags and functionalities added in HTML5. Some common tags are nav, aside, section, summary, article, meter, and many more.
HTML5
Technical Scripter 2020
HTML
Technical Scripter
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Angular File Upload
Make a div horizontally scrollable using CSS
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Remove elements from a JavaScript Array
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n15 Mar, 2021"
},
{
"code": null,
"e": 338,
"s": 52,
"text": "HTML stands for Hypertext Markup Language, and it is the standard markup language for creating web pages and web applications. HTML5 is the 5th version of HTML. With invent of features in HTML5, it’s not only possible to create better websites, but we can also create dynamic websites."
},
{
"code": null,
"e": 441,
"s": 338,
"text": "Now let’s have a look at all the new features that were added in HTML5 that make it better than HTML :"
},
{
"code": null,
"e": 7685,
"s": 441,
"text": "Intro of audio and video: Audio and Video tags are the two major addition to HTML5. It allows developers to embed a video or audio on their website. HTML5 video can use CSS and CSS3 to style the video tag. You can change the border, opacity, reflections, gradients, transitions, transformations, and even animations. HTML5 makes adding video super-fast and without having to build a video player. This saves time for the developer and offers the client a superior and more affordable solution.Example:HTMLHTML<!DOCTYPE html><html><body><h2>Example of video and audio tag</h2> <video width = \"300\" height = \"200\" controls autoplay> <source src = \"/html5/foo.ogg\" type =\"video/ogg\" /> <source src = \"/html5/foo.mp4\" type = \"video/mp4\" /> Your browser does not support the video element. </video> <audio controls autoplay> <source src = \"/html5/audio.ogg\" type = \"audio/ogg\" /> <source src = \"/html5/audio.wav\" type = \"audio/wav\" /> Your browser does not support the audio element. </audio></body></html>Output: The resulting UI looks something like this:video outputVector Graphics: This is a new addition to the revised version which has hugely impacted the use of Adobe Flash in websites. It can be used to draw graphics with various shapes and colors via scripting usually JS. Vector graphics are scalable, easy to create and edit. It also supports interactivity and animation. Having a smaller file size makes transferring and loading graphics much faster on the web. That’s the reason why many people prefer to use vector graphics.Example:HTMLHTML<svg id = \"svgelem\" height = \"200\" xmlns = \"http://www.abc.org/2000/svg\"> <circle id = \"redcircle\" cx = \"50\" cy = \"50\" r = \"50\" fill = \"red\" /> </svg>Output:vector outputHeader and Footer: With these new tags, there is no longer a need to identify the two elements with a <div> tag. Footer is placed at the end of the web page while Header is placed at the start of the web page. By using <header> and <footer> HTML5 elements, the browser will know what to load first and what to load later. The header can contain-One or more heading elements (<h1> – <h6>)Logo or iconAuthorship informationFooter can contain-Authorship informationCopyright informationContact informationBack to top linksThey both have the same default CSS property as a display block.Layout of HTML vs HTML5Example: Below examples illustrate the <header> element in HTML:HTMLHTML<!DOCTYPE html> <html> <head> <title>Header Tag</title> </head> <body> <article> <header> <h1>This is the heading.</h1> <h4>This is the sub-heading.</h4> <p>This is the metadata.</p> </header> </article> </body> </html> Output:Example: Below examples illustrate the <footer> Tag in HTML elements:HTMLHTML<!DOCTYPE html> <html> <head> <title>HTML footer Tag</title> <style> a { font-size:25px; text-decoration:none; } p { font-size:25px; } </style> </head> <body> <footer> <nav> <p> <a href= \"https://www.geeksforgeeks.org/about/\">About Us</a>| <a href= \"https://www.geeksforgeeks.org/privacy-policy/\">Privacy Policy</a>| <a href= \"https://www.geeksforgeeks.org/careers/\">Careers</a> </p> </nav> <p>@geeksforgeeks, Some rights reserved</p> </footer> </body> </html> Output:Figure and Figcaption: HTML5 allows to use a <figure> element to mark up a photo in a document, and a <figcaption> element to define a caption for the photo. The <figcaption> tag defines a caption for a <figure> element. This tag provides a container for content that is equivalent to a figure. It can be used to group a caption with one or more images, a block of code, or other content.Example:HTMLHTML<figure> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/ download3.png\" alt=\"GFG\" style=\"width:50%\"> <figcaption>Fig.1 - Geeksforgeeks.</figcaption></figure>Output:figure and figcaption outputNav tag: The <nav> tag defines a set of navigation links. It is used for the part of an internet site that links to different pages at the website. The hyperlinks can be organized through a number of approaches. Common examples of the nav elements are menus, tables, contents, and indexes. This element makes it much easier to create a navigation menu, creates a neat horizontal menu of text links, and helps screen reading software to correctly identify primary navigation areas in the document.Example:HTMLHTML<h1> HTML Nav tag</h1><nav> <a href=\"/html/\">HTML</a> <a href=\"/css/\">CSS</a> <a href=\"/js/\">JavaScript</a> <a href=\"/jquery/\">jQuery</a></nav>Output:Nav OutputProgress tag: The progress tag is used to check the progress of a task during the execution. Progress tag can be used with the conjunction of JavaScript.Example:HTMLHTML<h1>The progress element</h1> <label for=\"file\">Downloading progress:</label><progress id=\"file\" value=\"32\" max=\"100\"> 32% </progress>Output:Placeholder Attribute:The placeholder attribute specifies a short hint that describes the expected value of an input field/text area. The short hint is displayed in the field before the user enters a value.Example:HTMLHTML<!DOCTYPE html> <html> <body> <center> <h1 style=\"font-size:25px;font-style:italic;\"> GeeksforGeeks </h1> <h2 style=\"font-size:25px;font-style:italic;\"> Placeholder Attribute in Input Element </h2> <form action=\" \"> <input type=\"text\" name=\"fname\" placeholder=\"First name\"> <br> <input type=\"text\" name=\"lname\" placeholder=\"Last name\"> <br> <input type=\"submit\" value=\"Submit\"> </form> </center> </body> </html> Output:Email attribute:When the input type in the form set as email, then the browser gets the instruction from the code to write a valid format email. The input email id is automatically validated to check the format of the email id is correct or not.Example:HTMLHTML<!DOCTYPE html> <html> <head> <title> HTML input type email </title> </head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h2>HTML <input type =\"email\"></h2> <form> Email: <input type =\"email\" value=\"[email protected]\"> </form> </body> </html>Output:Storage: In the case of HTML, we can use the browser as the temporary storage whereas, in the case of HTML5, application cache, web SQL database, and web storage is used.Ease of use: While HTML5 does have risks like constant updates, it is generally easy to keep up with the changes & updates because of simpler syntax as compared to other versions of HTML."
},
{
"code": null,
"e": 8809,
"s": 7685,
"text": "Intro of audio and video: Audio and Video tags are the two major addition to HTML5. It allows developers to embed a video or audio on their website. HTML5 video can use CSS and CSS3 to style the video tag. You can change the border, opacity, reflections, gradients, transitions, transformations, and even animations. HTML5 makes adding video super-fast and without having to build a video player. This saves time for the developer and offers the client a superior and more affordable solution.Example:HTMLHTML<!DOCTYPE html><html><body><h2>Example of video and audio tag</h2> <video width = \"300\" height = \"200\" controls autoplay> <source src = \"/html5/foo.ogg\" type =\"video/ogg\" /> <source src = \"/html5/foo.mp4\" type = \"video/mp4\" /> Your browser does not support the video element. </video> <audio controls autoplay> <source src = \"/html5/audio.ogg\" type = \"audio/ogg\" /> <source src = \"/html5/audio.wav\" type = \"audio/wav\" /> Your browser does not support the audio element. </audio></body></html>Output: The resulting UI looks something like this:video output"
},
{
"code": null,
"e": 9282,
"s": 8809,
"text": " Audio and Video tags are the two major addition to HTML5. It allows developers to embed a video or audio on their website. HTML5 video can use CSS and CSS3 to style the video tag. You can change the border, opacity, reflections, gradients, transitions, transformations, and even animations. HTML5 makes adding video super-fast and without having to build a video player. This saves time for the developer and offers the client a superior and more affordable solution."
},
{
"code": null,
"e": 9291,
"s": 9282,
"text": "Example:"
},
{
"code": null,
"e": 9296,
"s": 9291,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><body><h2>Example of video and audio tag</h2> <video width = \"300\" height = \"200\" controls autoplay> <source src = \"/html5/foo.ogg\" type =\"video/ogg\" /> <source src = \"/html5/foo.mp4\" type = \"video/mp4\" /> Your browser does not support the video element. </video> <audio controls autoplay> <source src = \"/html5/audio.ogg\" type = \"audio/ogg\" /> <source src = \"/html5/audio.wav\" type = \"audio/wav\" /> Your browser does not support the audio element. </audio></body></html>",
"e": 9843,
"s": 9296,
"text": null
},
{
"code": null,
"e": 9895,
"s": 9843,
"text": "Output: The resulting UI looks something like this:"
},
{
"code": null,
"e": 9908,
"s": 9895,
"text": "video output"
},
{
"code": null,
"e": 10574,
"s": 9908,
"text": "Vector Graphics: This is a new addition to the revised version which has hugely impacted the use of Adobe Flash in websites. It can be used to draw graphics with various shapes and colors via scripting usually JS. Vector graphics are scalable, easy to create and edit. It also supports interactivity and animation. Having a smaller file size makes transferring and loading graphics much faster on the web. That’s the reason why many people prefer to use vector graphics.Example:HTMLHTML<svg id = \"svgelem\" height = \"200\" xmlns = \"http://www.abc.org/2000/svg\"> <circle id = \"redcircle\" cx = \"50\" cy = \"50\" r = \"50\" fill = \"red\" /> </svg>Output:vector output"
},
{
"code": null,
"e": 11033,
"s": 10574,
"text": " This is a new addition to the revised version which has hugely impacted the use of Adobe Flash in websites. It can be used to draw graphics with various shapes and colors via scripting usually JS. Vector graphics are scalable, easy to create and edit. It also supports interactivity and animation. Having a smaller file size makes transferring and loading graphics much faster on the web. That’s the reason why many people prefer to use vector graphics."
},
{
"code": null,
"e": 11042,
"s": 11033,
"text": "Example:"
},
{
"code": null,
"e": 11047,
"s": 11042,
"text": "HTML"
},
{
"code": "<svg id = \"svgelem\" height = \"200\" xmlns = \"http://www.abc.org/2000/svg\"> <circle id = \"redcircle\" cx = \"50\" cy = \"50\" r = \"50\" fill = \"red\" /> </svg>",
"e": 11203,
"s": 11047,
"text": null
},
{
"code": null,
"e": 11217,
"s": 11203,
"text": "vector output"
},
{
"code": null,
"e": 13116,
"s": 11217,
"text": "Header and Footer: With these new tags, there is no longer a need to identify the two elements with a <div> tag. Footer is placed at the end of the web page while Header is placed at the start of the web page. By using <header> and <footer> HTML5 elements, the browser will know what to load first and what to load later. The header can contain-One or more heading elements (<h1> – <h6>)Logo or iconAuthorship informationFooter can contain-Authorship informationCopyright informationContact informationBack to top linksThey both have the same default CSS property as a display block.Layout of HTML vs HTML5Example: Below examples illustrate the <header> element in HTML:HTMLHTML<!DOCTYPE html> <html> <head> <title>Header Tag</title> </head> <body> <article> <header> <h1>This is the heading.</h1> <h4>This is the sub-heading.</h4> <p>This is the metadata.</p> </header> </article> </body> </html> Output:Example: Below examples illustrate the <footer> Tag in HTML elements:HTMLHTML<!DOCTYPE html> <html> <head> <title>HTML footer Tag</title> <style> a { font-size:25px; text-decoration:none; } p { font-size:25px; } </style> </head> <body> <footer> <nav> <p> <a href= \"https://www.geeksforgeeks.org/about/\">About Us</a>| <a href= \"https://www.geeksforgeeks.org/privacy-policy/\">Privacy Policy</a>| <a href= \"https://www.geeksforgeeks.org/careers/\">Careers</a> </p> </nav> <p>@geeksforgeeks, Some rights reserved</p> </footer> </body> </html> Output:"
},
{
"code": null,
"e": 13425,
"s": 13116,
"text": " With these new tags, there is no longer a need to identify the two elements with a <div> tag. Footer is placed at the end of the web page while Header is placed at the start of the web page. By using <header> and <footer> HTML5 elements, the browser will know what to load first and what to load later. "
},
{
"code": null,
"e": 13449,
"s": 13425,
"text": "The header can contain-"
},
{
"code": null,
"e": 13492,
"s": 13449,
"text": "One or more heading elements (<h1> – <h6>)"
},
{
"code": null,
"e": 13505,
"s": 13492,
"text": "Logo or icon"
},
{
"code": null,
"e": 13528,
"s": 13505,
"text": "Authorship information"
},
{
"code": null,
"e": 13548,
"s": 13528,
"text": "Footer can contain-"
},
{
"code": null,
"e": 13571,
"s": 13548,
"text": "Authorship information"
},
{
"code": null,
"e": 13593,
"s": 13571,
"text": "Copyright information"
},
{
"code": null,
"e": 13613,
"s": 13593,
"text": "Contact information"
},
{
"code": null,
"e": 13631,
"s": 13613,
"text": "Back to top links"
},
{
"code": null,
"e": 13696,
"s": 13631,
"text": "They both have the same default CSS property as a display block."
},
{
"code": null,
"e": 13720,
"s": 13696,
"text": "Layout of HTML vs HTML5"
},
{
"code": null,
"e": 13785,
"s": 13720,
"text": "Example: Below examples illustrate the <header> element in HTML:"
},
{
"code": null,
"e": 13790,
"s": 13785,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <html> <head> <title>Header Tag</title> </head> <body> <article> <header> <h1>This is the heading.</h1> <h4>This is the sub-heading.</h4> <p>This is the metadata.</p> </header> </article> </body> </html> ",
"e": 14147,
"s": 13790,
"text": null
},
{
"code": null,
"e": 14155,
"s": 14147,
"text": "Output:"
},
{
"code": null,
"e": 14225,
"s": 14155,
"text": "Example: Below examples illustrate the <footer> Tag in HTML elements:"
},
{
"code": null,
"e": 14230,
"s": 14225,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <html> <head> <title>HTML footer Tag</title> <style> a { font-size:25px; text-decoration:none; } p { font-size:25px; } </style> </head> <body> <footer> <nav> <p> <a href= \"https://www.geeksforgeeks.org/about/\">About Us</a>| <a href= \"https://www.geeksforgeeks.org/privacy-policy/\">Privacy Policy</a>| <a href= \"https://www.geeksforgeeks.org/careers/\">Careers</a> </p> </nav> <p>@geeksforgeeks, Some rights reserved</p> </footer> </body> </html> ",
"e": 15000,
"s": 14230,
"text": null
},
{
"code": null,
"e": 15008,
"s": 15000,
"text": "Output:"
},
{
"code": null,
"e": 15662,
"s": 15008,
"text": "Figure and Figcaption: HTML5 allows to use a <figure> element to mark up a photo in a document, and a <figcaption> element to define a caption for the photo. The <figcaption> tag defines a caption for a <figure> element. This tag provides a container for content that is equivalent to a figure. It can be used to group a caption with one or more images, a block of code, or other content.Example:HTMLHTML<figure> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/ download3.png\" alt=\"GFG\" style=\"width:50%\"> <figcaption>Fig.1 - Geeksforgeeks.</figcaption></figure>Output:figure and figcaption output"
},
{
"code": null,
"e": 16033,
"s": 15662,
"text": " HTML5 allows to use a <figure> element to mark up a photo in a document, and a <figcaption> element to define a caption for the photo. The <figcaption> tag defines a caption for a <figure> element. This tag provides a container for content that is equivalent to a figure. It can be used to group a caption with one or more images, a block of code, or other content."
},
{
"code": null,
"e": 16042,
"s": 16033,
"text": "Example:"
},
{
"code": null,
"e": 16047,
"s": 16042,
"text": "HTML"
},
{
"code": "<figure> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/ download3.png\" alt=\"GFG\" style=\"width:50%\"> <figcaption>Fig.1 - Geeksforgeeks.</figcaption></figure>",
"e": 16258,
"s": 16047,
"text": null
},
{
"code": null,
"e": 16287,
"s": 16258,
"text": "figure and figcaption output"
},
{
"code": null,
"e": 16968,
"s": 16287,
"text": "Nav tag: The <nav> tag defines a set of navigation links. It is used for the part of an internet site that links to different pages at the website. The hyperlinks can be organized through a number of approaches. Common examples of the nav elements are menus, tables, contents, and indexes. This element makes it much easier to create a navigation menu, creates a neat horizontal menu of text links, and helps screen reading software to correctly identify primary navigation areas in the document.Example:HTMLHTML<h1> HTML Nav tag</h1><nav> <a href=\"/html/\">HTML</a> <a href=\"/css/\">CSS</a> <a href=\"/js/\">JavaScript</a> <a href=\"/jquery/\">jQuery</a></nav>Output:Nav Output"
},
{
"code": null,
"e": 17461,
"s": 16968,
"text": " The <nav> tag defines a set of navigation links. It is used for the part of an internet site that links to different pages at the website. The hyperlinks can be organized through a number of approaches. Common examples of the nav elements are menus, tables, contents, and indexes. This element makes it much easier to create a navigation menu, creates a neat horizontal menu of text links, and helps screen reading software to correctly identify primary navigation areas in the document."
},
{
"code": null,
"e": 17470,
"s": 17461,
"text": "Example:"
},
{
"code": null,
"e": 17475,
"s": 17470,
"text": "HTML"
},
{
"code": "<h1> HTML Nav tag</h1><nav> <a href=\"/html/\">HTML</a> <a href=\"/css/\">CSS</a> <a href=\"/js/\">JavaScript</a> <a href=\"/jquery/\">jQuery</a></nav>",
"e": 17623,
"s": 17475,
"text": null
},
{
"code": null,
"e": 17634,
"s": 17623,
"text": "Nav Output"
},
{
"code": null,
"e": 17950,
"s": 17634,
"text": "Progress tag: The progress tag is used to check the progress of a task during the execution. Progress tag can be used with the conjunction of JavaScript.Example:HTMLHTML<h1>The progress element</h1> <label for=\"file\">Downloading progress:</label><progress id=\"file\" value=\"32\" max=\"100\"> 32% </progress>Output:"
},
{
"code": null,
"e": 18095,
"s": 17950,
"text": " The progress tag is used to check the progress of a task during the execution. Progress tag can be used with the conjunction of JavaScript."
},
{
"code": null,
"e": 18100,
"s": 18095,
"text": "HTML"
},
{
"code": "<h1>The progress element</h1> <label for=\"file\">Downloading progress:</label><progress id=\"file\" value=\"32\" max=\"100\"> 32% </progress>",
"e": 18236,
"s": 18100,
"text": null
},
{
"code": null,
"e": 19068,
"s": 18236,
"text": "Placeholder Attribute:The placeholder attribute specifies a short hint that describes the expected value of an input field/text area. The short hint is displayed in the field before the user enters a value.Example:HTMLHTML<!DOCTYPE html> <html> <body> <center> <h1 style=\"font-size:25px;font-style:italic;\"> GeeksforGeeks </h1> <h2 style=\"font-size:25px;font-style:italic;\"> Placeholder Attribute in Input Element </h2> <form action=\" \"> <input type=\"text\" name=\"fname\" placeholder=\"First name\"> <br> <input type=\"text\" name=\"lname\" placeholder=\"Last name\"> <br> <input type=\"submit\" value=\"Submit\"> </form> </center> </body> </html> Output:"
},
{
"code": null,
"e": 19077,
"s": 19068,
"text": "Example:"
},
{
"code": null,
"e": 19082,
"s": 19077,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <html> <body> <center> <h1 style=\"font-size:25px;font-style:italic;\"> GeeksforGeeks </h1> <h2 style=\"font-size:25px;font-style:italic;\"> Placeholder Attribute in Input Element </h2> <form action=\" \"> <input type=\"text\" name=\"fname\" placeholder=\"First name\"> <br> <input type=\"text\" name=\"lname\" placeholder=\"Last name\"> <br> <input type=\"submit\" value=\"Submit\"> </form> </center> </body> </html> ",
"e": 19685,
"s": 19082,
"text": null
},
{
"code": null,
"e": 19693,
"s": 19685,
"text": "Output:"
},
{
"code": null,
"e": 20408,
"s": 19693,
"text": "Email attribute:When the input type in the form set as email, then the browser gets the instruction from the code to write a valid format email. The input email id is automatically validated to check the format of the email id is correct or not.Example:HTMLHTML<!DOCTYPE html> <html> <head> <title> HTML input type email </title> </head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h2>HTML <input type =\"email\"></h2> <form> Email: <input type =\"email\" value=\"[email protected]\"> </form> </body> </html>Output:"
},
{
"code": null,
"e": 20413,
"s": 20408,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <html> <head> <title> HTML input type email </title> </head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h2>HTML <input type =\"email\"></h2> <form> Email: <input type =\"email\" value=\"[email protected]\"> </form> </body> </html>",
"e": 20860,
"s": 20413,
"text": null
},
{
"code": null,
"e": 21034,
"s": 20860,
"text": "Storage: In the case of HTML, we can use the browser as the temporary storage whereas, in the case of HTML5, application cache, web SQL database, and web storage is used."
},
{
"code": null,
"e": 21200,
"s": 21034,
"text": " In the case of HTML, we can use the browser as the temporary storage whereas, in the case of HTML5, application cache, web SQL database, and web storage is used."
},
{
"code": null,
"e": 21392,
"s": 21200,
"text": "Ease of use: While HTML5 does have risks like constant updates, it is generally easy to keep up with the changes & updates because of simpler syntax as compared to other versions of HTML."
},
{
"code": null,
"e": 21572,
"s": 21392,
"text": " While HTML5 does have risks like constant updates, it is generally easy to keep up with the changes & updates because of simpler syntax as compared to other versions of HTML."
},
{
"code": null,
"e": 21716,
"s": 21572,
"text": "There are a lot more tags and functionalities added in HTML5. Some common tags are nav, aside, section, summary, article, meter, and many more."
},
{
"code": null,
"e": 21722,
"s": 21716,
"text": "HTML5"
},
{
"code": null,
"e": 21746,
"s": 21722,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 21751,
"s": 21746,
"text": "HTML"
},
{
"code": null,
"e": 21770,
"s": 21751,
"text": "Technical Scripter"
},
{
"code": null,
"e": 21787,
"s": 21770,
"text": "Web Technologies"
},
{
"code": null,
"e": 21814,
"s": 21787,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 21819,
"s": 21814,
"text": "HTML"
},
{
"code": null,
"e": 21917,
"s": 21819,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 21941,
"s": 21917,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 21980,
"s": 21941,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 22019,
"s": 21980,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 22039,
"s": 22019,
"text": "Angular File Upload"
},
{
"code": null,
"e": 22084,
"s": 22039,
"text": "Make a div horizontally scrollable using CSS"
},
{
"code": null,
"e": 22117,
"s": 22084,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 22178,
"s": 22117,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 22221,
"s": 22178,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 22261,
"s": 22221,
"text": "Remove elements from a JavaScript Array"
}
]
|
vector emplace() function in C++ STL | 06 Oct, 2021
The vector::emplace() is an STL in C++ which extends the container by inserting a new element at the position. Reallocation happens only if there is a need for more space. Here the container size increases by one.Syntax:
template
iterator vector_name.emplace (const_iterator position, element);
Parameter: The function accepts two mandatory parameters which are specified as below:
position – It specifies the iterator pointing to the position in the container where the new element is to be inserted.
element- It specifies the element to be inserted in the vector container.
Return value: The function returns an iterator that points to the newly inserted element.
Complexity: Linear Below programs illustrates the above function:Program 1:
CPP
// C++ program to illustrate the// vector::emplace() function// insertion at thefront#include <bits/stdc++.h>using namespace std; int main(){ vector<int> vec = { 10, 20, 30 }; // insert element by emplace function // at front auto it = vec.emplace(vec.begin(), 15); // print the elements of the vectorcout << "The vector elements are: "; for (auto it = vec.begin(); it != vec.end(); ++it) cout << *it << " "; return 0;}
The vector elements are: 15 10 20 30
Program 2:
CPP
// C++ program to illustrate the// vector::emplace() function// insertion at the end#include <bits/stdc++.h>using namespace std; int main(){ vector<int> vec = { 10, 20, 30 }; // insert element by emplace function // at the end auto it = vec.emplace(vec.end(), 16); // print the elements of the vectorcout << "The vector elements are: "; for (auto it = vec.begin(); it != vec.end(); ++it) cout << *it << " "; return 0;}
The vector elements are: 10 20 30 16
Program 3:
CPP
// C++ program to illustrate the// vector::emplace() function// insertion at the middle#include <bits/stdc++.h>using namespace std; int main(){ vector<int> vec = { 10, 20, 30 }; // insert element by emplace function // in the middle auto it = vec.emplace(vec.begin() + 2, 16); // print the elements of the vectorcout << "The vector elements are: "; for (auto it = vec.begin(); it != vec.end(); ++it) cout << *it << " "; return 0;}
The vector elements are: 10 20 16 30
Additional Related Links: emplace_front( ) and emplace_back( )
Regular insertion using shift operation in arrays V/s emplace( ) function :
a) If want to insert an element at some specific position between the first and last index, we have to shift all the elements next to that specific index. So, if want to keep our code precise so emplace( ) would be a good choice. In terms of Time Complexity both take the same linear time which is directly dependent on the number of shift operations.
Ex:
C++
#include <iostream>#include <vector>#include <array>using namespace std; int main() { array<int,6> a={1,2,4,5}; vector<int> v={1,2,4,5}; // Insert 3 in the arr at index 2 for(int i=3;i>=0;i--) { if(i!=1) a[i+1]=a[i]; else { a[i+1]=3; break; } } // Time complexity is high cout<<"Content of a: "; for(int i=0;i<5;i++) cout<<a[i]<<" "; v.emplace( v.begin() + 2 , 3); cout<<"\nContent of v: "; for(int i=0;i<v.size();i++) cout<<v[i]<<" "; return 0;}
Content of a: 1 2 3 4 5
Content of v: 1 2 3 4 5
madhav_mohan
duttabhishek0
CPP-Functions
cpp-vector
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 276,
"s": 53,
"text": "The vector::emplace() is an STL in C++ which extends the container by inserting a new element at the position. Reallocation happens only if there is a need for more space. Here the container size increases by one.Syntax: "
},
{
"code": null,
"e": 351,
"s": 276,
"text": "template \niterator vector_name.emplace (const_iterator position, element);"
},
{
"code": null,
"e": 439,
"s": 351,
"text": "Parameter: The function accepts two mandatory parameters which are specified as below: "
},
{
"code": null,
"e": 561,
"s": 439,
"text": "position – It specifies the iterator pointing to the position in the container where the new element is to be inserted. "
},
{
"code": null,
"e": 637,
"s": 561,
"text": "element- It specifies the element to be inserted in the vector container. "
},
{
"code": null,
"e": 727,
"s": 637,
"text": "Return value: The function returns an iterator that points to the newly inserted element."
},
{
"code": null,
"e": 805,
"s": 727,
"text": "Complexity: Linear Below programs illustrates the above function:Program 1: "
},
{
"code": null,
"e": 809,
"s": 805,
"text": "CPP"
},
{
"code": "// C++ program to illustrate the// vector::emplace() function// insertion at thefront#include <bits/stdc++.h>using namespace std; int main(){ vector<int> vec = { 10, 20, 30 }; // insert element by emplace function // at front auto it = vec.emplace(vec.begin(), 15); // print the elements of the vectorcout << \"The vector elements are: \"; for (auto it = vec.begin(); it != vec.end(); ++it) cout << *it << \" \"; return 0;}",
"e": 1260,
"s": 809,
"text": null
},
{
"code": null,
"e": 1297,
"s": 1260,
"text": "The vector elements are: 15 10 20 30"
},
{
"code": null,
"e": 1312,
"s": 1299,
"text": "Program 2: "
},
{
"code": null,
"e": 1316,
"s": 1312,
"text": "CPP"
},
{
"code": "// C++ program to illustrate the// vector::emplace() function// insertion at the end#include <bits/stdc++.h>using namespace std; int main(){ vector<int> vec = { 10, 20, 30 }; // insert element by emplace function // at the end auto it = vec.emplace(vec.end(), 16); // print the elements of the vectorcout << \"The vector elements are: \"; for (auto it = vec.begin(); it != vec.end(); ++it) cout << *it << \" \"; return 0;}",
"e": 1766,
"s": 1316,
"text": null
},
{
"code": null,
"e": 1803,
"s": 1766,
"text": "The vector elements are: 10 20 30 16"
},
{
"code": null,
"e": 1818,
"s": 1805,
"text": "Program 3: "
},
{
"code": null,
"e": 1822,
"s": 1818,
"text": "CPP"
},
{
"code": "// C++ program to illustrate the// vector::emplace() function// insertion at the middle#include <bits/stdc++.h>using namespace std; int main(){ vector<int> vec = { 10, 20, 30 }; // insert element by emplace function // in the middle auto it = vec.emplace(vec.begin() + 2, 16); // print the elements of the vectorcout << \"The vector elements are: \"; for (auto it = vec.begin(); it != vec.end(); ++it) cout << *it << \" \"; return 0;}",
"e": 2284,
"s": 1822,
"text": null
},
{
"code": null,
"e": 2321,
"s": 2284,
"text": "The vector elements are: 10 20 16 30"
},
{
"code": null,
"e": 2386,
"s": 2323,
"text": "Additional Related Links: emplace_front( ) and emplace_back( )"
},
{
"code": null,
"e": 2462,
"s": 2386,
"text": "Regular insertion using shift operation in arrays V/s emplace( ) function :"
},
{
"code": null,
"e": 2814,
"s": 2462,
"text": "a) If want to insert an element at some specific position between the first and last index, we have to shift all the elements next to that specific index. So, if want to keep our code precise so emplace( ) would be a good choice. In terms of Time Complexity both take the same linear time which is directly dependent on the number of shift operations."
},
{
"code": null,
"e": 2819,
"s": 2814,
"text": "Ex: "
},
{
"code": null,
"e": 2823,
"s": 2819,
"text": "C++"
},
{
"code": "#include <iostream>#include <vector>#include <array>using namespace std; int main() { array<int,6> a={1,2,4,5}; vector<int> v={1,2,4,5}; // Insert 3 in the arr at index 2 for(int i=3;i>=0;i--) { if(i!=1) a[i+1]=a[i]; else { a[i+1]=3; break; } } // Time complexity is high cout<<\"Content of a: \"; for(int i=0;i<5;i++) cout<<a[i]<<\" \"; v.emplace( v.begin() + 2 , 3); cout<<\"\\nContent of v: \"; for(int i=0;i<v.size();i++) cout<<v[i]<<\" \"; return 0;}",
"e": 3388,
"s": 2823,
"text": null
},
{
"code": null,
"e": 3438,
"s": 3388,
"text": "Content of a: 1 2 3 4 5 \nContent of v: 1 2 3 4 5 "
},
{
"code": null,
"e": 3451,
"s": 3438,
"text": "madhav_mohan"
},
{
"code": null,
"e": 3465,
"s": 3451,
"text": "duttabhishek0"
},
{
"code": null,
"e": 3479,
"s": 3465,
"text": "CPP-Functions"
},
{
"code": null,
"e": 3490,
"s": 3479,
"text": "cpp-vector"
},
{
"code": null,
"e": 3494,
"s": 3490,
"text": "STL"
},
{
"code": null,
"e": 3498,
"s": 3494,
"text": "C++"
},
{
"code": null,
"e": 3502,
"s": 3498,
"text": "STL"
},
{
"code": null,
"e": 3506,
"s": 3502,
"text": "CPP"
}
]
|
SQL Query to Display Last 50% Records from Employee Table | 13 Apr, 2021
Here, we are going to see how to display the last 50% of records from an Employee Table in MySQL and MS SQL server’s databases.
For the purpose of demonstration, we will be creating an Employee table in a database called “geeks“.
Use the below SQL statement to create a database called geeks:
CREATE DATABASE geeks;
USE geeks;
We have the following Employee table in our geeks database :
CREATE TABLE Employee(
ID INT IDENTITY(1,1) KEY, --IDENTITY(1,1) tells start ID from 1 and increment
-- it by 1 with each row inserted.
NAME VARCHAR(30) NOT NULL,
PHONE INT NOT NULL UNIQUE,
EMAIL VARCHAR(30) NOT NULL UNIQUE,
DATE_OF_JOINING DATE);
NOTE: We should use VARCHAR or BIGINT as the data type for the PHONE column to avoid integer overflow.
You can use the below statement to query the description of the created table:
EXEC SP_COLUMNS Employee;
Use the below statement to add data to the Employee table:
INSERT INTO Employee (NAME, PHONE, EMAIL, DATE_OF_JOINING)
VALUES
('Yogesh Vaishnav', 0000000001, '[email protected]', '2019-10-03'),
('Vishal Vishwakarma', 0000000002, '[email protected]', '2019-11-07'),
('Ajit Yadav', 0000000003, '[email protected]', '2019-12-12'),
('Ashish Yadav', 0000000004, '[email protected]', '2019-12-25'),
('Tanvi Thakur', 0000000005, '[email protected]', '2020-01-20'),
('Sam', 0000000006, '[email protected]', '2020-03-03'),
('Ron', 0000000007, '[email protected]', '2020-05-16'),
('Sara', 0000000008, '[email protected]', '2020-07-01'),
('Zara', 0000000009, '[email protected]', '2020-08-20'),
('Yoji', 0000000010, '[email protected]', '2020-03-10'),
('Rekha Vaishnav', 12, '[email protected]', '2021-03-25');
To verify the contents of the table use the below statement:
SELECT * FROM Employee;
Now let’s retrieve the last 50% of the records from the Employee Table.
In MS SQL we can directly retrieve the last 50% of the records with the help of top and percent and order by clauses. A simple syntax for the same is given below:
Syntax :
select * from
/*Gives the top N percent records from bottom of a database table*/
(select top N percent * from <table_name> order by <column_name> desc)<identifier>
order by <column_name>;
Example :
SELECT * FROM
(SELECT top 50 percent * FROM Employee ORDER BY ID DESC)
ORDER BY ID;
Output :
Picked
SQL-Query
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Apr, 2021"
},
{
"code": null,
"e": 156,
"s": 28,
"text": "Here, we are going to see how to display the last 50% of records from an Employee Table in MySQL and MS SQL server’s databases."
},
{
"code": null,
"e": 258,
"s": 156,
"text": "For the purpose of demonstration, we will be creating an Employee table in a database called “geeks“."
},
{
"code": null,
"e": 321,
"s": 258,
"text": "Use the below SQL statement to create a database called geeks:"
},
{
"code": null,
"e": 344,
"s": 321,
"text": "CREATE DATABASE geeks;"
},
{
"code": null,
"e": 355,
"s": 344,
"text": "USE geeks;"
},
{
"code": null,
"e": 416,
"s": 355,
"text": "We have the following Employee table in our geeks database :"
},
{
"code": null,
"e": 696,
"s": 416,
"text": "CREATE TABLE Employee(\nID INT IDENTITY(1,1) KEY, --IDENTITY(1,1) tells start ID from 1 and increment\n -- it by 1 with each row inserted.\nNAME VARCHAR(30) NOT NULL,\nPHONE INT NOT NULL UNIQUE,\nEMAIL VARCHAR(30) NOT NULL UNIQUE,\nDATE_OF_JOINING DATE);"
},
{
"code": null,
"e": 799,
"s": 696,
"text": "NOTE: We should use VARCHAR or BIGINT as the data type for the PHONE column to avoid integer overflow."
},
{
"code": null,
"e": 878,
"s": 799,
"text": "You can use the below statement to query the description of the created table:"
},
{
"code": null,
"e": 904,
"s": 878,
"text": "EXEC SP_COLUMNS Employee;"
},
{
"code": null,
"e": 963,
"s": 904,
"text": "Use the below statement to add data to the Employee table:"
},
{
"code": null,
"e": 1662,
"s": 963,
"text": "INSERT INTO Employee (NAME, PHONE, EMAIL, DATE_OF_JOINING)\nVALUES\n('Yogesh Vaishnav', 0000000001, '[email protected]', '2019-10-03'),\n('Vishal Vishwakarma', 0000000002, '[email protected]', '2019-11-07'),\n('Ajit Yadav', 0000000003, '[email protected]', '2019-12-12'),\n('Ashish Yadav', 0000000004, '[email protected]', '2019-12-25'),\n('Tanvi Thakur', 0000000005, '[email protected]', '2020-01-20'),\n('Sam', 0000000006, '[email protected]', '2020-03-03'),\n('Ron', 0000000007, '[email protected]', '2020-05-16'),\n('Sara', 0000000008, '[email protected]', '2020-07-01'),\n('Zara', 0000000009, '[email protected]', '2020-08-20'),\n('Yoji', 0000000010, '[email protected]', '2020-03-10'),\n('Rekha Vaishnav', 12, '[email protected]', '2021-03-25');"
},
{
"code": null,
"e": 1723,
"s": 1662,
"text": "To verify the contents of the table use the below statement:"
},
{
"code": null,
"e": 1747,
"s": 1723,
"text": "SELECT * FROM Employee;"
},
{
"code": null,
"e": 1819,
"s": 1747,
"text": "Now let’s retrieve the last 50% of the records from the Employee Table."
},
{
"code": null,
"e": 1982,
"s": 1819,
"text": "In MS SQL we can directly retrieve the last 50% of the records with the help of top and percent and order by clauses. A simple syntax for the same is given below:"
},
{
"code": null,
"e": 1991,
"s": 1982,
"text": "Syntax :"
},
{
"code": null,
"e": 2006,
"s": 1991,
"text": "select * from "
},
{
"code": null,
"e": 2076,
"s": 2006,
"text": " /*Gives the top N percent records from bottom of a database table*/"
},
{
"code": null,
"e": 2159,
"s": 2076,
"text": "(select top N percent * from <table_name> order by <column_name> desc)<identifier>"
},
{
"code": null,
"e": 2183,
"s": 2159,
"text": "order by <column_name>;"
},
{
"code": null,
"e": 2193,
"s": 2183,
"text": "Example :"
},
{
"code": null,
"e": 2277,
"s": 2193,
"text": "SELECT * FROM\n(SELECT top 50 percent * FROM Employee ORDER BY ID DESC)\nORDER BY ID;"
},
{
"code": null,
"e": 2286,
"s": 2277,
"text": "Output :"
},
{
"code": null,
"e": 2293,
"s": 2286,
"text": "Picked"
},
{
"code": null,
"e": 2303,
"s": 2293,
"text": "SQL-Query"
},
{
"code": null,
"e": 2307,
"s": 2303,
"text": "SQL"
},
{
"code": null,
"e": 2311,
"s": 2307,
"text": "SQL"
}
]
|
CSS | matrix3d() Function | 21 Aug, 2019
The matrix3d() function is an inbuilt function which is used to apply a transformation to create a 3D transformation as a 4×4 homogeneous matrix.
Syntax:
matrix3d( a1, b1, c1, d1, a2, b2, c2, d2, a3, b3, c3, d3, a4, b4, c4, d4 )
Parameters: This function accepts 16 parameters as mentioned above and described below:
a1, b1, c1, d1, a2, b2, c2, d2, a3, b3, c3, d3, d4: These parameters are used to hold the value for linear transformation.
a4, b4, c4: These parameters are used to hold the value of translation.
Below example illustrates the matrix3d() function in CSS:Example:
<!DOCTYPE html> <html> <head> <title> CSS matrix3d() function </title> <style> .GFG { transform: matrix3d( 0.6, 0.1, 0.7, 0, -0.5, 0.8, 0.1, 0, -0.6, -0.5, 0.5, 0, 0, 0, 0, 1 ); font-size:26px; font-weight:bold; width:250px; padding:20px; background: green; color: white; font-family: sans-serif; } </style> </head> <body> <center> <h1 style="color:green">GeeksforGeeks</h1> <h2>CSS matrix3d() function</h2> <br><br> <div class="GFG"> Welcome to GeeksforGeeks </div> </center></body> </html>
Output:
Supported Browsers: The browsers supported by matrix3d() function are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
CSS-Functions
CSS
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": "\n21 Aug, 2019"
},
{
"code": null,
"e": 174,
"s": 28,
"text": "The matrix3d() function is an inbuilt function which is used to apply a transformation to create a 3D transformation as a 4×4 homogeneous matrix."
},
{
"code": null,
"e": 182,
"s": 174,
"text": "Syntax:"
},
{
"code": null,
"e": 257,
"s": 182,
"text": "matrix3d( a1, b1, c1, d1, a2, b2, c2, d2, a3, b3, c3, d3, a4, b4, c4, d4 )"
},
{
"code": null,
"e": 345,
"s": 257,
"text": "Parameters: This function accepts 16 parameters as mentioned above and described below:"
},
{
"code": null,
"e": 468,
"s": 345,
"text": "a1, b1, c1, d1, a2, b2, c2, d2, a3, b3, c3, d3, d4: These parameters are used to hold the value for linear transformation."
},
{
"code": null,
"e": 540,
"s": 468,
"text": "a4, b4, c4: These parameters are used to hold the value of translation."
},
{
"code": null,
"e": 606,
"s": 540,
"text": "Below example illustrates the matrix3d() function in CSS:Example:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title> CSS matrix3d() function </title> <style> .GFG { transform: matrix3d( 0.6, 0.1, 0.7, 0, -0.5, 0.8, 0.1, 0, -0.6, -0.5, 0.5, 0, 0, 0, 0, 1 ); font-size:26px; font-weight:bold; width:250px; padding:20px; background: green; color: white; font-family: sans-serif; } </style> </head> <body> <center> <h1 style=\"color:green\">GeeksforGeeks</h1> <h2>CSS matrix3d() function</h2> <br><br> <div class=\"GFG\"> Welcome to GeeksforGeeks </div> </center></body> </html> ",
"e": 1416,
"s": 606,
"text": null
},
{
"code": null,
"e": 1424,
"s": 1416,
"text": "Output:"
},
{
"code": null,
"e": 1508,
"s": 1424,
"text": "Supported Browsers: The browsers supported by matrix3d() function are listed below:"
},
{
"code": null,
"e": 1522,
"s": 1508,
"text": "Google Chrome"
},
{
"code": null,
"e": 1540,
"s": 1522,
"text": "Internet Explorer"
},
{
"code": null,
"e": 1548,
"s": 1540,
"text": "Firefox"
},
{
"code": null,
"e": 1555,
"s": 1548,
"text": "Safari"
},
{
"code": null,
"e": 1561,
"s": 1555,
"text": "Opera"
},
{
"code": null,
"e": 1575,
"s": 1561,
"text": "CSS-Functions"
},
{
"code": null,
"e": 1579,
"s": 1575,
"text": "CSS"
},
{
"code": null,
"e": 1596,
"s": 1579,
"text": "Web Technologies"
}
]
|
C/C++ if statement with Examples | 22 Nov, 2019
Decision Making in C/C++ helps to write decision driven statements and execute a particular set of code based on certain conditions.
The C/C++ if statement is the most simple decision making statement. It is used to decide whether a certain statement or block of statements will be executed or not based on a certain type of condition.
Syntax:
if(condition)
{
// Statements to execute if
// condition is true
}
Working of if statement
Control falls into the if block.The flow jumps to Condition.Condition is tested.If Condition yields true, goto Step 4.If Condition yields false, goto Step 5.The if-block or the body inside the if is executed.Flow steps out of the if block.
Control falls into the if block.
The flow jumps to Condition.
Condition is tested.If Condition yields true, goto Step 4.If Condition yields false, goto Step 5.
If Condition yields true, goto Step 4.If Condition yields false, goto Step 5.
If Condition yields true, goto Step 4.
If Condition yields false, goto Step 5.
The if-block or the body inside the if is executed.
Flow steps out of the if block.
Flowchart
Note: If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if statement will consider the immediate one statement to be inside its block. For example,
if(condition)
statement1;
statement2;
// Here if the condition is true,
// if block will consider only statement1
// to be inside its block.
Example 1:
C
C++
// C program to illustrate If statement #include <stdio.h> int main(){ int i = 10; if (i < 15) { printf("10 is less than 15 \n"); } printf("I am Not in if");}
// C++ program to illustrate If statement #include <iostream>using namespace std; int main(){ int i = 10; if (i < 15) { cout << "10 is less than 15 \n"; } cout << "I am Not in if";}
10 is less than 15
I am Not in if
Dry-Running Example 1:
1. Program starts.
2. i is initialized to 10.
3. if-condition is checked. 10 < 15, yields true.
3.a) "10 is less than 15" gets printed.
4. "I am Not in if" is printed.
Example 2:
C
C++
// C program to illustrate If statement #include <stdio.h> int main(){ int i = 10; if (i > 15) { printf("10 is greater than 15 \n"); } printf("I am Not in if");}
// C++ program to illustrate If statement #include <iostream>using namespace std; int main(){ int i = 10; if (i > 15) { cout << "10 is greater than 15 \n"; } cout << "I am Not in if";}
I am Not in if
Related Articles:
Decision Making in C / C++C/C++ if else statement with ExamplesC/C++ if else if ladder with ExamplesSwitch Statement in C/C++Break Statement in C/C++Continue Statement in C/C++goto statement in C/C++return statement in C/C++ with Examples
Decision Making in C / C++
C/C++ if else statement with Examples
C/C++ if else if ladder with Examples
Switch Statement in C/C++
Break Statement in C/C++
Continue Statement in C/C++
goto statement in C/C++
return statement in C/C++ with Examples
C Basics
CPP-Basics
C Language
C++
School Programming
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
What is the purpose of a function prototype?
Operators in C / C++
Exception Handling in C++
TCP Server-Client implementation in C
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++ | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n22 Nov, 2019"
},
{
"code": null,
"e": 186,
"s": 53,
"text": "Decision Making in C/C++ helps to write decision driven statements and execute a particular set of code based on certain conditions."
},
{
"code": null,
"e": 389,
"s": 186,
"text": "The C/C++ if statement is the most simple decision making statement. It is used to decide whether a certain statement or block of statements will be executed or not based on a certain type of condition."
},
{
"code": null,
"e": 397,
"s": 389,
"text": "Syntax:"
},
{
"code": null,
"e": 471,
"s": 397,
"text": "if(condition) \n{\n // Statements to execute if\n // condition is true\n}"
},
{
"code": null,
"e": 495,
"s": 471,
"text": "Working of if statement"
},
{
"code": null,
"e": 735,
"s": 495,
"text": "Control falls into the if block.The flow jumps to Condition.Condition is tested.If Condition yields true, goto Step 4.If Condition yields false, goto Step 5.The if-block or the body inside the if is executed.Flow steps out of the if block."
},
{
"code": null,
"e": 768,
"s": 735,
"text": "Control falls into the if block."
},
{
"code": null,
"e": 797,
"s": 768,
"text": "The flow jumps to Condition."
},
{
"code": null,
"e": 895,
"s": 797,
"text": "Condition is tested.If Condition yields true, goto Step 4.If Condition yields false, goto Step 5."
},
{
"code": null,
"e": 973,
"s": 895,
"text": "If Condition yields true, goto Step 4.If Condition yields false, goto Step 5."
},
{
"code": null,
"e": 1012,
"s": 973,
"text": "If Condition yields true, goto Step 4."
},
{
"code": null,
"e": 1052,
"s": 1012,
"text": "If Condition yields false, goto Step 5."
},
{
"code": null,
"e": 1104,
"s": 1052,
"text": "The if-block or the body inside the if is executed."
},
{
"code": null,
"e": 1136,
"s": 1104,
"text": "Flow steps out of the if block."
},
{
"code": null,
"e": 1146,
"s": 1136,
"text": "Flowchart"
},
{
"code": null,
"e": 1332,
"s": 1146,
"text": "Note: If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if statement will consider the immediate one statement to be inside its block. For example,"
},
{
"code": null,
"e": 1481,
"s": 1332,
"text": "if(condition)\n statement1;\n statement2;\n\n// Here if the condition is true,\n// if block will consider only statement1\n// to be inside its block."
},
{
"code": null,
"e": 1492,
"s": 1481,
"text": "Example 1:"
},
{
"code": null,
"e": 1494,
"s": 1492,
"text": "C"
},
{
"code": null,
"e": 1498,
"s": 1494,
"text": "C++"
},
{
"code": "// C program to illustrate If statement #include <stdio.h> int main(){ int i = 10; if (i < 15) { printf(\"10 is less than 15 \\n\"); } printf(\"I am Not in if\");}",
"e": 1682,
"s": 1498,
"text": null
},
{
"code": "// C++ program to illustrate If statement #include <iostream>using namespace std; int main(){ int i = 10; if (i < 15) { cout << \"10 is less than 15 \\n\"; } cout << \"I am Not in if\";}",
"e": 1889,
"s": 1682,
"text": null
},
{
"code": null,
"e": 1925,
"s": 1889,
"text": "10 is less than 15 \nI am Not in if\n"
},
{
"code": null,
"e": 1948,
"s": 1925,
"text": "Dry-Running Example 1:"
},
{
"code": null,
"e": 2119,
"s": 1948,
"text": "1. Program starts.\n2. i is initialized to 10.\n3. if-condition is checked. 10 < 15, yields true.\n 3.a) \"10 is less than 15\" gets printed.\n4. \"I am Not in if\" is printed.\n"
},
{
"code": null,
"e": 2130,
"s": 2119,
"text": "Example 2:"
},
{
"code": null,
"e": 2132,
"s": 2130,
"text": "C"
},
{
"code": null,
"e": 2136,
"s": 2132,
"text": "C++"
},
{
"code": "// C program to illustrate If statement #include <stdio.h> int main(){ int i = 10; if (i > 15) { printf(\"10 is greater than 15 \\n\"); } printf(\"I am Not in if\");}",
"e": 2323,
"s": 2136,
"text": null
},
{
"code": "// C++ program to illustrate If statement #include <iostream>using namespace std; int main(){ int i = 10; if (i > 15) { cout << \"10 is greater than 15 \\n\"; } cout << \"I am Not in if\";}",
"e": 2533,
"s": 2323,
"text": null
},
{
"code": null,
"e": 2549,
"s": 2533,
"text": "I am Not in if\n"
},
{
"code": null,
"e": 2567,
"s": 2549,
"text": "Related Articles:"
},
{
"code": null,
"e": 2806,
"s": 2567,
"text": "Decision Making in C / C++C/C++ if else statement with ExamplesC/C++ if else if ladder with ExamplesSwitch Statement in C/C++Break Statement in C/C++Continue Statement in C/C++goto statement in C/C++return statement in C/C++ with Examples"
},
{
"code": null,
"e": 2833,
"s": 2806,
"text": "Decision Making in C / C++"
},
{
"code": null,
"e": 2871,
"s": 2833,
"text": "C/C++ if else statement with Examples"
},
{
"code": null,
"e": 2909,
"s": 2871,
"text": "C/C++ if else if ladder with Examples"
},
{
"code": null,
"e": 2935,
"s": 2909,
"text": "Switch Statement in C/C++"
},
{
"code": null,
"e": 2960,
"s": 2935,
"text": "Break Statement in C/C++"
},
{
"code": null,
"e": 2988,
"s": 2960,
"text": "Continue Statement in C/C++"
},
{
"code": null,
"e": 3012,
"s": 2988,
"text": "goto statement in C/C++"
},
{
"code": null,
"e": 3052,
"s": 3012,
"text": "return statement in C/C++ with Examples"
},
{
"code": null,
"e": 3061,
"s": 3052,
"text": "C Basics"
},
{
"code": null,
"e": 3072,
"s": 3061,
"text": "CPP-Basics"
},
{
"code": null,
"e": 3083,
"s": 3072,
"text": "C Language"
},
{
"code": null,
"e": 3087,
"s": 3083,
"text": "C++"
},
{
"code": null,
"e": 3106,
"s": 3087,
"text": "School Programming"
},
{
"code": null,
"e": 3110,
"s": 3106,
"text": "CPP"
},
{
"code": null,
"e": 3208,
"s": 3110,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3256,
"s": 3208,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 3301,
"s": 3256,
"text": "What is the purpose of a function prototype?"
},
{
"code": null,
"e": 3322,
"s": 3301,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 3348,
"s": 3322,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 3386,
"s": 3348,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 3404,
"s": 3386,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 3447,
"s": 3404,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3493,
"s": 3447,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 3536,
"s": 3493,
"text": "Set in C++ Standard Template Library (STL)"
}
]
|
How to Implement Circular ProgressBar in Android? | 06 Apr, 2021
ProgressBar is used when we are fetching some data from another source and it takes time, so for user’s satisfaction, we generally display them the progress of the task. In this article, we are going to learn how to implement the circular progress bar in an android application using Java. So, this article will give you a complete idea of implementing a circular progress bar in an application built in Android Studio. So, without wasting further time let’s go to the article and read how we can achieve this task.
We will be building a simple application in which we will be implementing a circular progress bar with a text display. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Create circular_progress_bar.xml
Navigate to the app > res > drawable > right-click and select new > drawable resource file and name the new XML file as circular_progress_bar.xml and refer to the following code. Comments are added inside the code to understand the code in more detail.
XML
<?xml version="1.0" encoding="utf-8"?><rotate xmlns:android="http://schemas.android.com/apk/res/android" android:fromDegrees="270" android:toDegrees="270"> <!--styling the progress bar--> <shape android:innerRadiusRatio="2.5" android:shape="ring" android:thickness="8dp" android:useLevel="true"> <gradient android:angle="0" android:endColor="@color/colorPrimary" android:startColor="#000000" android:type="sweep" android:useLevel="false" /> </shape> </rotate>
Step 3: Create circular_shape.xml
Similarly, create a new drawable resource file and name the file as circular_shape.xml and refer to the following code.
XML
<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" android:innerRadiusRatio="2.5" android:shape="ring" android:thickness="3dp" android:useLevel="false"> <solid android:color="@color/colorPrimary" /></shape>
Step 4: Working with the activity_main.xml file
Now it’s time to design the layout of the application. So for that, navigate to the app > res > layout > activity_main.xml and refer to the code written below.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_horizontal" android:orientation="vertical" tools:context=".MainActivity"> <RelativeLayout android:id="@+id/progress_layout" android:layout_width="200dp" android:layout_height="200dp" android:layout_margin="100dp"> <!--progress bar implementation--> <ProgressBar android:id="@+id/progress_bar" style="?android:attr/progressBarStyleHorizontal" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/circular_shape" android:indeterminate="false" android:progressDrawable="@drawable/circular_progress_bar" android:textAlignment="center" /> <!--Text implementation in center of the progress bar--> <TextView android:id="@+id/progress_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:gravity="center" android:text="---" android:textColor="@color/colorPrimary" android:textSize="28sp" android:textStyle="bold" /> </RelativeLayout> </LinearLayout>
Step 5: Working with the MainActivity.java file
Go to the app > java > package name > MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle;import android.os.Handler;import android.widget.ProgressBar;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private ProgressBar progressBar; private TextView progressText; int i = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // set the id for the progressbar and progress text progressBar = findViewById(R.id.progress_bar); progressText = findViewById(R.id.progress_text); final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { // set the limitations for the numeric // text under the progress bar if (i <= 100) { progressText.setText("" + i); progressBar.setProgress(i); i++; handler.postDelayed(this, 200); } else { handler.removeCallbacks(this); } } }, 200); }}
That’s all, now the application is ready to install on the device. Here is what the output of the application looks like.
Output:
GitHub Link:
The project is available on GitHub, you can access it by following the link below: Circular Progress Bar in Android Application
Android-Bars
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Android SDK and it's Components
Flutter - Custom Bottom Navigation Bar
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Flutter - Stack Widget
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Object Oriented Programming (OOPs) Concept in Java
Reverse a string in Java | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 Apr, 2021"
},
{
"code": null,
"e": 570,
"s": 54,
"text": "ProgressBar is used when we are fetching some data from another source and it takes time, so for user’s satisfaction, we generally display them the progress of the task. In this article, we are going to learn how to implement the circular progress bar in an android application using Java. So, this article will give you a complete idea of implementing a circular progress bar in an application built in Android Studio. So, without wasting further time let’s go to the article and read how we can achieve this task."
},
{
"code": null,
"e": 857,
"s": 570,
"text": "We will be building a simple application in which we will be implementing a circular progress bar with a text display. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 886,
"s": 857,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 1048,
"s": 886,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 1089,
"s": 1048,
"text": "Step 2: Create circular_progress_bar.xml"
},
{
"code": null,
"e": 1342,
"s": 1089,
"text": "Navigate to the app > res > drawable > right-click and select new > drawable resource file and name the new XML file as circular_progress_bar.xml and refer to the following code. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 1346,
"s": 1342,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><rotate xmlns:android=\"http://schemas.android.com/apk/res/android\" android:fromDegrees=\"270\" android:toDegrees=\"270\"> <!--styling the progress bar--> <shape android:innerRadiusRatio=\"2.5\" android:shape=\"ring\" android:thickness=\"8dp\" android:useLevel=\"true\"> <gradient android:angle=\"0\" android:endColor=\"@color/colorPrimary\" android:startColor=\"#000000\" android:type=\"sweep\" android:useLevel=\"false\" /> </shape> </rotate>",
"e": 1922,
"s": 1346,
"text": null
},
{
"code": null,
"e": 1956,
"s": 1922,
"text": "Step 3: Create circular_shape.xml"
},
{
"code": null,
"e": 2076,
"s": 1956,
"text": "Similarly, create a new drawable resource file and name the file as circular_shape.xml and refer to the following code."
},
{
"code": null,
"e": 2080,
"s": 2076,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><shape xmlns:android=\"http://schemas.android.com/apk/res/android\" android:innerRadiusRatio=\"2.5\" android:shape=\"ring\" android:thickness=\"3dp\" android:useLevel=\"false\"> <solid android:color=\"@color/colorPrimary\" /></shape>",
"e": 2359,
"s": 2080,
"text": null
},
{
"code": null,
"e": 2407,
"s": 2359,
"text": "Step 4: Working with the activity_main.xml file"
},
{
"code": null,
"e": 2568,
"s": 2407,
"text": "Now it’s time to design the layout of the application. So for that, navigate to the app > res > layout > activity_main.xml and refer to the code written below. "
},
{
"code": null,
"e": 2572,
"s": 2568,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center_horizontal\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <RelativeLayout android:id=\"@+id/progress_layout\" android:layout_width=\"200dp\" android:layout_height=\"200dp\" android:layout_margin=\"100dp\"> <!--progress bar implementation--> <ProgressBar android:id=\"@+id/progress_bar\" style=\"?android:attr/progressBarStyleHorizontal\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"@drawable/circular_shape\" android:indeterminate=\"false\" android:progressDrawable=\"@drawable/circular_progress_bar\" android:textAlignment=\"center\" /> <!--Text implementation in center of the progress bar--> <TextView android:id=\"@+id/progress_text\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentLeft=\"true\" android:layout_alignParentRight=\"true\" android:layout_centerVertical=\"true\" android:gravity=\"center\" android:text=\"---\" android:textColor=\"@color/colorPrimary\" android:textSize=\"28sp\" android:textStyle=\"bold\" /> </RelativeLayout> </LinearLayout>",
"e": 4187,
"s": 2572,
"text": null
},
{
"code": null,
"e": 4235,
"s": 4187,
"text": "Step 5: Working with the MainActivity.java file"
},
{
"code": null,
"e": 4453,
"s": 4235,
"text": "Go to the app > java > package name > MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 4458,
"s": 4453,
"text": "Java"
},
{
"code": "import android.os.Bundle;import android.os.Handler;import android.widget.ProgressBar;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private ProgressBar progressBar; private TextView progressText; int i = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // set the id for the progressbar and progress text progressBar = findViewById(R.id.progress_bar); progressText = findViewById(R.id.progress_text); final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { // set the limitations for the numeric // text under the progress bar if (i <= 100) { progressText.setText(\"\" + i); progressBar.setProgress(i); i++; handler.postDelayed(this, 200); } else { handler.removeCallbacks(this); } } }, 200); }}",
"e": 5678,
"s": 4458,
"text": null
},
{
"code": null,
"e": 5800,
"s": 5678,
"text": "That’s all, now the application is ready to install on the device. Here is what the output of the application looks like."
},
{
"code": null,
"e": 5808,
"s": 5800,
"text": "Output:"
},
{
"code": null,
"e": 5821,
"s": 5808,
"text": "GitHub Link:"
},
{
"code": null,
"e": 5949,
"s": 5821,
"text": "The project is available on GitHub, you can access it by following the link below: Circular Progress Bar in Android Application"
},
{
"code": null,
"e": 5962,
"s": 5949,
"text": "Android-Bars"
},
{
"code": null,
"e": 5970,
"s": 5962,
"text": "Android"
},
{
"code": null,
"e": 5975,
"s": 5970,
"text": "Java"
},
{
"code": null,
"e": 5980,
"s": 5975,
"text": "Java"
},
{
"code": null,
"e": 5988,
"s": 5980,
"text": "Android"
},
{
"code": null,
"e": 6086,
"s": 5988,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6118,
"s": 6086,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 6157,
"s": 6118,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 6199,
"s": 6157,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 6250,
"s": 6199,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 6273,
"s": 6250,
"text": "Flutter - Stack Widget"
},
{
"code": null,
"e": 6288,
"s": 6273,
"text": "Arrays in Java"
},
{
"code": null,
"e": 6332,
"s": 6288,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 6368,
"s": 6332,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 6419,
"s": 6368,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
]
|
JavaScript Date getTime() Method | 22 Nov, 2021
In this article, we will learn the getTime() method in Javascript, along with understanding their implementation through the examples.
The date.getTime() method is used to return the number of milliseconds since 1 January 1970. when a new Date object is created it stores the date and time data when it is created. When the getTime() method is called on this date object it returns the number of milliseconds since 1 January 1970 (Unix Epoch). The getTime() always uses UTC for time representation.
Syntax:
Date.getTime()
Parameters: This method does not accept any parameter.
Return type: A numeric value equal to no of milliseconds since Unix Epoch.
Please refer to the JavaScript Get Date Methods article for further details.
Example: Below is the example of the Date getTime() method.
Javascript
<script> // Here a date has been assigned // While creating Date object var A = new Date('October 15, 1996 05:35:32'); // Hour from above is being // extracted using getTime() var B = A.getTime(); // Printing time in milliseconds. document.write(B); </script>
Output:
845337932000
More examples for the above method are as follows:
Example 1: Here, the date of the month must lie in between 1 to 31 because no date can have a month greater than 31. That is why it returns NaN i.e, Not a Number if the month in the Date object is greater than 31. Hours will not have existed when the date of the month is given as 33 i.e, greater than 31.
Javascript
<script> // Creating a Date object var A = new Date('October 35, 1996 12:35:32'); var B = A.getTime(); // Printing hour. document.write(B); </script>
Output:
NaN
Example 2: Here, we will calculate the user’s age by providing the birth date of the user.
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title></head> <body> <h1>GeeksforGeeks</h1> <h3>Date.getTime() Method</h3> <div> <h4>Birth Date: <span class="date"></span> </h4> </div> <div> <h4>getTime(): <span class="time"></span> </h4> </div> <div> <h4>I am <span class="years"></span> years old. </h4></div> <script> var BD = new Date("July 29, 1997 23:15:20"); var date = document.querySelector(".date"); var time = document.querySelector(".time"); var Today = new Date(); var today = Today.getTime(); var bd = BD.getTime(); var year = 1000 * 60 * 60 * 24 * 365; var years = (today - bd) / year; date.innerHTML = BD; time.innerHTML = BD.getTime(); var y = document.querySelector(".years"); y.innerHTML = Math.round(years); </script></body> </html>
Output:
date.getTime() Method
Supported Browsers: The browsers supported by JavaScript Date getTime() method are listed below:
Google Chrome 1.0
Microsoft Edge 12.0
Firefox 1.0
Internet Explorer 4.0
Opera 3.0
Safari 1.0
ysachin2314
bhaskargeeksforgeeks
javascript-date
JavaScript-Methods
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Differences between Functional Components and Class Components in React
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Nov, 2021"
},
{
"code": null,
"e": 163,
"s": 28,
"text": "In this article, we will learn the getTime() method in Javascript, along with understanding their implementation through the examples."
},
{
"code": null,
"e": 527,
"s": 163,
"text": "The date.getTime() method is used to return the number of milliseconds since 1 January 1970. when a new Date object is created it stores the date and time data when it is created. When the getTime() method is called on this date object it returns the number of milliseconds since 1 January 1970 (Unix Epoch). The getTime() always uses UTC for time representation."
},
{
"code": null,
"e": 535,
"s": 527,
"text": "Syntax:"
},
{
"code": null,
"e": 550,
"s": 535,
"text": "Date.getTime()"
},
{
"code": null,
"e": 606,
"s": 550,
"text": "Parameters: This method does not accept any parameter. "
},
{
"code": null,
"e": 681,
"s": 606,
"text": "Return type: A numeric value equal to no of milliseconds since Unix Epoch."
},
{
"code": null,
"e": 758,
"s": 681,
"text": "Please refer to the JavaScript Get Date Methods article for further details."
},
{
"code": null,
"e": 818,
"s": 758,
"text": "Example: Below is the example of the Date getTime() method."
},
{
"code": null,
"e": 829,
"s": 818,
"text": "Javascript"
},
{
"code": "<script> // Here a date has been assigned // While creating Date object var A = new Date('October 15, 1996 05:35:32'); // Hour from above is being // extracted using getTime() var B = A.getTime(); // Printing time in milliseconds. document.write(B); </script>",
"e": 1112,
"s": 829,
"text": null
},
{
"code": null,
"e": 1120,
"s": 1112,
"text": "Output:"
},
{
"code": null,
"e": 1133,
"s": 1120,
"text": "845337932000"
},
{
"code": null,
"e": 1184,
"s": 1133,
"text": "More examples for the above method are as follows:"
},
{
"code": null,
"e": 1490,
"s": 1184,
"text": "Example 1: Here, the date of the month must lie in between 1 to 31 because no date can have a month greater than 31. That is why it returns NaN i.e, Not a Number if the month in the Date object is greater than 31. Hours will not have existed when the date of the month is given as 33 i.e, greater than 31."
},
{
"code": null,
"e": 1501,
"s": 1490,
"text": "Javascript"
},
{
"code": "<script> // Creating a Date object var A = new Date('October 35, 1996 12:35:32'); var B = A.getTime(); // Printing hour. document.write(B); </script>",
"e": 1671,
"s": 1501,
"text": null
},
{
"code": null,
"e": 1679,
"s": 1671,
"text": "Output:"
},
{
"code": null,
"e": 1683,
"s": 1679,
"text": "NaN"
},
{
"code": null,
"e": 1774,
"s": 1683,
"text": "Example 2: Here, we will calculate the user’s age by providing the birth date of the user."
},
{
"code": null,
"e": 1779,
"s": 1774,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"> <title>Document</title></head> <body> <h1>GeeksforGeeks</h1> <h3>Date.getTime() Method</h3> <div> <h4>Birth Date: <span class=\"date\"></span> </h4> </div> <div> <h4>getTime(): <span class=\"time\"></span> </h4> </div> <div> <h4>I am <span class=\"years\"></span> years old. </h4></div> <script> var BD = new Date(\"July 29, 1997 23:15:20\"); var date = document.querySelector(\".date\"); var time = document.querySelector(\".time\"); var Today = new Date(); var today = Today.getTime(); var bd = BD.getTime(); var year = 1000 * 60 * 60 * 24 * 365; var years = (today - bd) / year; date.innerHTML = BD; time.innerHTML = BD.getTime(); var y = document.querySelector(\".years\"); y.innerHTML = Math.round(years); </script></body> </html>",
"e": 2912,
"s": 1779,
"text": null
},
{
"code": null,
"e": 2920,
"s": 2912,
"text": "Output:"
},
{
"code": null,
"e": 2943,
"s": 2920,
"text": " date.getTime() Method"
},
{
"code": null,
"e": 3040,
"s": 2943,
"text": "Supported Browsers: The browsers supported by JavaScript Date getTime() method are listed below:"
},
{
"code": null,
"e": 3058,
"s": 3040,
"text": "Google Chrome 1.0"
},
{
"code": null,
"e": 3078,
"s": 3058,
"text": "Microsoft Edge 12.0"
},
{
"code": null,
"e": 3090,
"s": 3078,
"text": "Firefox 1.0"
},
{
"code": null,
"e": 3112,
"s": 3090,
"text": "Internet Explorer 4.0"
},
{
"code": null,
"e": 3122,
"s": 3112,
"text": "Opera 3.0"
},
{
"code": null,
"e": 3133,
"s": 3122,
"text": "Safari 1.0"
},
{
"code": null,
"e": 3145,
"s": 3133,
"text": "ysachin2314"
},
{
"code": null,
"e": 3166,
"s": 3145,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 3182,
"s": 3166,
"text": "javascript-date"
},
{
"code": null,
"e": 3201,
"s": 3182,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 3208,
"s": 3201,
"text": "Picked"
},
{
"code": null,
"e": 3219,
"s": 3208,
"text": "JavaScript"
},
{
"code": null,
"e": 3236,
"s": 3219,
"text": "Web Technologies"
},
{
"code": null,
"e": 3334,
"s": 3236,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3395,
"s": 3334,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3435,
"s": 3395,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3477,
"s": 3435,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 3549,
"s": 3477,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3590,
"s": 3549,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 3623,
"s": 3590,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3685,
"s": 3623,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3746,
"s": 3685,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3789,
"s": 3746,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
How to output in Octave GNU | 21 Jun, 2021
Octave is open-source, free available for many of the platforms. It is a high-level language. It comes up with a text interface along with an experimental graphical interface. It is also used for various Machine Learning algorithms for solving various numeric problems. You can say that it is similar to MATLAB but slower than MATLAB.There are multiple library functions to display an output in Octave.
The printf() function prints the characters and returns the number of character printed, the format is a string starting with % and ends with conversion character (like c, i, f, d, etc.).
Syntax : printf(template, variables) Parameters :
template : string to be written on the console, it also contains format specifiers like %d, %s etc
variables : values that will replace the format specifiers
Types of Format Specifiers :
%d : used for integers
%f : used for floating point values
%s : used for strings
Returns : number of characters printed
Example :
MATLAB
% using printf() without format specifiersprintf("Hello World!!\n"); x = 5; % using printf() with format specifiersprintf("Welcome, value of x is %d\n", x);
Output :
Hello World!!
Welcome, value of x is 5
The fprintf() function is equivalent to the printf() function, except that the output is written to the file descriptor fid instead of stdout.
Syntax : fprintf(fid, template, variables) Parameters :
fid : file descriptor
template : string to be written on the console, it also contains format specifiers like %d, %s etc
variables : values that will replace the format specifiers
Types of Format Specifiers :
%d : used for integers
%f : used for floating point values
%s : used for strings
Returns : number of characters printed
Example :
MATLAB
% using fprintf() without format specifiersfprintf("Hello World!!\n"); x = 5; % using fprintf() with format specifiersprintf("Welcome, value of x is %d\n", x);
Output :
Hello World!!
Welcome, value of x is 5
The sprintf() function is like the printf() function, except that the output is returned as a string.
Syntax : sprintf(template, variables) Parameters :
template : string to be written on the console, it also contains format specifiers like %d, %s etc
variables : values that will replace the format specifiers
Types of Format Specifiers :
%d : used for integers
%f : used for floating point values
%s : used for strings
Returns : number of characters printed
MATLAB
% using sprintf() without format specifiersfprintf("Hello World!!\n"); x = 5; % using sprintf() with format specifiersprintf("Welcome, value of x is %d\n", x);
Output :
Hello World!!
Welcome, value of x is 5
The disp() function is used to either display the value on the console or assign the value to a variable.
Syntax : disp(argument) Parameters :
argument : can either be a string or a variable
Returns : the string/value printed
Example:
MATLAB
% displaying the value of the consoledisp("Hello World!!"); % assigning the value to a variableoutput = disp("Welcome"); % displaying the assigned variable valuedisp(output);
Output :
Hello World!!
Welcome
saurabh1990aror
Octave-GNU
Programming Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Jun, 2021"
},
{
"code": null,
"e": 432,
"s": 28,
"text": "Octave is open-source, free available for many of the platforms. It is a high-level language. It comes up with a text interface along with an experimental graphical interface. It is also used for various Machine Learning algorithms for solving various numeric problems. You can say that it is similar to MATLAB but slower than MATLAB.There are multiple library functions to display an output in Octave. "
},
{
"code": null,
"e": 621,
"s": 432,
"text": "The printf() function prints the characters and returns the number of character printed, the format is a string starting with % and ends with conversion character (like c, i, f, d, etc.). "
},
{
"code": null,
"e": 673,
"s": 621,
"text": "Syntax : printf(template, variables) Parameters : "
},
{
"code": null,
"e": 772,
"s": 673,
"text": "template : string to be written on the console, it also contains format specifiers like %d, %s etc"
},
{
"code": null,
"e": 831,
"s": 772,
"text": "variables : values that will replace the format specifiers"
},
{
"code": null,
"e": 862,
"s": 831,
"text": "Types of Format Specifiers : "
},
{
"code": null,
"e": 885,
"s": 862,
"text": "%d : used for integers"
},
{
"code": null,
"e": 921,
"s": 885,
"text": "%f : used for floating point values"
},
{
"code": null,
"e": 943,
"s": 921,
"text": "%s : used for strings"
},
{
"code": null,
"e": 984,
"s": 943,
"text": "Returns : number of characters printed "
},
{
"code": null,
"e": 996,
"s": 984,
"text": "Example : "
},
{
"code": null,
"e": 1003,
"s": 996,
"text": "MATLAB"
},
{
"code": "% using printf() without format specifiersprintf(\"Hello World!!\\n\"); x = 5; % using printf() with format specifiersprintf(\"Welcome, value of x is %d\\n\", x);",
"e": 1160,
"s": 1003,
"text": null
},
{
"code": null,
"e": 1171,
"s": 1160,
"text": "Output : "
},
{
"code": null,
"e": 1210,
"s": 1171,
"text": "Hello World!!\nWelcome, value of x is 5"
},
{
"code": null,
"e": 1356,
"s": 1212,
"text": "The fprintf() function is equivalent to the printf() function, except that the output is written to the file descriptor fid instead of stdout. "
},
{
"code": null,
"e": 1414,
"s": 1356,
"text": "Syntax : fprintf(fid, template, variables) Parameters : "
},
{
"code": null,
"e": 1436,
"s": 1414,
"text": "fid : file descriptor"
},
{
"code": null,
"e": 1535,
"s": 1436,
"text": "template : string to be written on the console, it also contains format specifiers like %d, %s etc"
},
{
"code": null,
"e": 1594,
"s": 1535,
"text": "variables : values that will replace the format specifiers"
},
{
"code": null,
"e": 1625,
"s": 1594,
"text": "Types of Format Specifiers : "
},
{
"code": null,
"e": 1648,
"s": 1625,
"text": "%d : used for integers"
},
{
"code": null,
"e": 1684,
"s": 1648,
"text": "%f : used for floating point values"
},
{
"code": null,
"e": 1706,
"s": 1684,
"text": "%s : used for strings"
},
{
"code": null,
"e": 1747,
"s": 1706,
"text": "Returns : number of characters printed "
},
{
"code": null,
"e": 1759,
"s": 1747,
"text": "Example : "
},
{
"code": null,
"e": 1766,
"s": 1759,
"text": "MATLAB"
},
{
"code": "% using fprintf() without format specifiersfprintf(\"Hello World!!\\n\"); x = 5; % using fprintf() with format specifiersprintf(\"Welcome, value of x is %d\\n\", x);",
"e": 1926,
"s": 1766,
"text": null
},
{
"code": null,
"e": 1937,
"s": 1926,
"text": "Output : "
},
{
"code": null,
"e": 1976,
"s": 1937,
"text": "Hello World!!\nWelcome, value of x is 5"
},
{
"code": null,
"e": 2081,
"s": 1978,
"text": "The sprintf() function is like the printf() function, except that the output is returned as a string. "
},
{
"code": null,
"e": 2134,
"s": 2081,
"text": "Syntax : sprintf(template, variables) Parameters : "
},
{
"code": null,
"e": 2233,
"s": 2134,
"text": "template : string to be written on the console, it also contains format specifiers like %d, %s etc"
},
{
"code": null,
"e": 2292,
"s": 2233,
"text": "variables : values that will replace the format specifiers"
},
{
"code": null,
"e": 2323,
"s": 2292,
"text": "Types of Format Specifiers : "
},
{
"code": null,
"e": 2346,
"s": 2323,
"text": "%d : used for integers"
},
{
"code": null,
"e": 2382,
"s": 2346,
"text": "%f : used for floating point values"
},
{
"code": null,
"e": 2404,
"s": 2382,
"text": "%s : used for strings"
},
{
"code": null,
"e": 2445,
"s": 2404,
"text": "Returns : number of characters printed "
},
{
"code": null,
"e": 2454,
"s": 2447,
"text": "MATLAB"
},
{
"code": "% using sprintf() without format specifiersfprintf(\"Hello World!!\\n\"); x = 5; % using sprintf() with format specifiersprintf(\"Welcome, value of x is %d\\n\", x);",
"e": 2614,
"s": 2454,
"text": null
},
{
"code": null,
"e": 2625,
"s": 2614,
"text": "Output : "
},
{
"code": null,
"e": 2664,
"s": 2625,
"text": "Hello World!!\nWelcome, value of x is 5"
},
{
"code": null,
"e": 2774,
"s": 2666,
"text": "The disp() function is used to either display the value on the console or assign the value to a variable. "
},
{
"code": null,
"e": 2813,
"s": 2774,
"text": "Syntax : disp(argument) Parameters : "
},
{
"code": null,
"e": 2861,
"s": 2813,
"text": "argument : can either be a string or a variable"
},
{
"code": null,
"e": 2898,
"s": 2861,
"text": "Returns : the string/value printed "
},
{
"code": null,
"e": 2908,
"s": 2898,
"text": "Example: "
},
{
"code": null,
"e": 2915,
"s": 2908,
"text": "MATLAB"
},
{
"code": "% displaying the value of the consoledisp(\"Hello World!!\"); % assigning the value to a variableoutput = disp(\"Welcome\"); % displaying the assigned variable valuedisp(output);",
"e": 3090,
"s": 2915,
"text": null
},
{
"code": null,
"e": 3101,
"s": 3090,
"text": "Output : "
},
{
"code": null,
"e": 3123,
"s": 3101,
"text": "Hello World!!\nWelcome"
},
{
"code": null,
"e": 3141,
"s": 3125,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 3152,
"s": 3141,
"text": "Octave-GNU"
},
{
"code": null,
"e": 3173,
"s": 3152,
"text": "Programming Language"
}
]
|
How to set the visibility of the CheckBox in C#? | 30 Sep, 2021
The CheckBox control is the part of the windows form that is used to take input from the user. Or in other words, CheckBox control allows us to select single or multiple elements from the given list. In CheckBox, you are allowed to set a value that represents the CheckBox and its CheckBox controls are displayed by using the Visible Property of the CheckBox.
If you want to display the given CheckBox and its child controls, then set the value of Visible property to true, otherwise set false. The default value of this property is true. In Windows form, you can set this property in two different ways:
1. Design-Time: It is the simplest way to set the Visible property of a CheckBox using the following steps:
Step 1: Create a windows form as shown in the below image: Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Drag the CheckBox control from the ToolBox and drop it on the windows form. You can place CheckBox anywhere on the windows form according to your need.
Step 3: After drag and drop you will go to the properties of the CheckBox control to set the visibility of the CheckBox by using Visible property.
Output:
Note: If the value of Visible property is true, sometimes the control may not be visible because they are hidden behind other controls.
2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the Visible property of a CheckBox using the following syntax:
public bool Visible { get; set; }
Here, the value type of this property is System.Boolean. Following steps are used to set the Visible property of the CheckBox:
Step 1: Create a checkbox using the CheckBox() constructor provided by the CheckBox class.
// Creating checkbox
CheckBox Mycheckbox = new CheckBox();
Step 2: After creating CheckBox, set the Visible property of the CheckBox provided by the CheckBox class.
// Set the Visible property of the CheckBox
Mycheckbox.Visible = true;
Step 3: And last add this checkbox control to form using Add() method.
// Add this checkbox to form
this.Controls.Add(Mycheckbox);
Example:
C#
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp5 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Text = "Select Gender:"; l.Location = new Point(233, 111); // Adding label to form this.Controls.Add(l); // Creating and setting the properties of CheckBox CheckBox Mycheckbox = new CheckBox(); Mycheckbox.Height = 50; Mycheckbox.Width = 100; Mycheckbox.Location = new Point(229, 136); Mycheckbox.Text = "Male"; Mycheckbox.Visible = true; // Adding checkbox to form this.Controls.Add(Mycheckbox); // Creating and setting the properties of CheckBox // This CheckBox is not displayed in the output because // the visibility of this CheckBox is set to be false CheckBox Mycheckbox1 = new CheckBox(); Mycheckbox1.Height = 50; Mycheckbox1.Width = 100; Mycheckbox1.Location = new Point(230, 174); Mycheckbox1.Text = "Female"; Mycheckbox1.Visible = false; // Adding checkbox to form this.Controls.Add(Mycheckbox1); }}}
Output:
sagartomar9927
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Sep, 2021"
},
{
"code": null,
"e": 389,
"s": 28,
"text": "The CheckBox control is the part of the windows form that is used to take input from the user. Or in other words, CheckBox control allows us to select single or multiple elements from the given list. In CheckBox, you are allowed to set a value that represents the CheckBox and its CheckBox controls are displayed by using the Visible Property of the CheckBox. "
},
{
"code": null,
"e": 634,
"s": 389,
"text": "If you want to display the given CheckBox and its child controls, then set the value of Visible property to true, otherwise set false. The default value of this property is true. In Windows form, you can set this property in two different ways:"
},
{
"code": null,
"e": 743,
"s": 634,
"text": "1. Design-Time: It is the simplest way to set the Visible property of a CheckBox using the following steps: "
},
{
"code": null,
"e": 861,
"s": 743,
"text": "Step 1: Create a windows form as shown in the below image: Visual Studio -> File -> New -> Project -> WindowsFormApp "
},
{
"code": null,
"e": 1022,
"s": 861,
"text": "Step 2: Drag the CheckBox control from the ToolBox and drop it on the windows form. You can place CheckBox anywhere on the windows form according to your need. "
},
{
"code": null,
"e": 1170,
"s": 1022,
"text": "Step 3: After drag and drop you will go to the properties of the CheckBox control to set the visibility of the CheckBox by using Visible property. "
},
{
"code": null,
"e": 1179,
"s": 1170,
"text": "Output: "
},
{
"code": null,
"e": 1315,
"s": 1179,
"text": "Note: If the value of Visible property is true, sometimes the control may not be visible because they are hidden behind other controls."
},
{
"code": null,
"e": 1471,
"s": 1315,
"text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the Visible property of a CheckBox using the following syntax: "
},
{
"code": null,
"e": 1505,
"s": 1471,
"text": "public bool Visible { get; set; }"
},
{
"code": null,
"e": 1633,
"s": 1505,
"text": "Here, the value type of this property is System.Boolean. Following steps are used to set the Visible property of the CheckBox: "
},
{
"code": null,
"e": 1724,
"s": 1633,
"text": "Step 1: Create a checkbox using the CheckBox() constructor provided by the CheckBox class."
},
{
"code": null,
"e": 1783,
"s": 1724,
"text": "// Creating checkbox\nCheckBox Mycheckbox = new CheckBox();"
},
{
"code": null,
"e": 1889,
"s": 1783,
"text": "Step 2: After creating CheckBox, set the Visible property of the CheckBox provided by the CheckBox class."
},
{
"code": null,
"e": 1960,
"s": 1889,
"text": "// Set the Visible property of the CheckBox\nMycheckbox.Visible = true;"
},
{
"code": null,
"e": 2032,
"s": 1960,
"text": "Step 3: And last add this checkbox control to form using Add() method. "
},
{
"code": null,
"e": 2092,
"s": 2032,
"text": "// Add this checkbox to form\nthis.Controls.Add(Mycheckbox);"
},
{
"code": null,
"e": 2101,
"s": 2092,
"text": "Example:"
},
{
"code": null,
"e": 2104,
"s": 2101,
"text": "C#"
},
{
"code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp5 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Text = \"Select Gender:\"; l.Location = new Point(233, 111); // Adding label to form this.Controls.Add(l); // Creating and setting the properties of CheckBox CheckBox Mycheckbox = new CheckBox(); Mycheckbox.Height = 50; Mycheckbox.Width = 100; Mycheckbox.Location = new Point(229, 136); Mycheckbox.Text = \"Male\"; Mycheckbox.Visible = true; // Adding checkbox to form this.Controls.Add(Mycheckbox); // Creating and setting the properties of CheckBox // This CheckBox is not displayed in the output because // the visibility of this CheckBox is set to be false CheckBox Mycheckbox1 = new CheckBox(); Mycheckbox1.Height = 50; Mycheckbox1.Width = 100; Mycheckbox1.Location = new Point(230, 174); Mycheckbox1.Text = \"Female\"; Mycheckbox1.Visible = false; // Adding checkbox to form this.Controls.Add(Mycheckbox1); }}}",
"e": 3571,
"s": 2104,
"text": null
},
{
"code": null,
"e": 3580,
"s": 3571,
"text": "Output: "
},
{
"code": null,
"e": 3597,
"s": 3582,
"text": "sagartomar9927"
},
{
"code": null,
"e": 3600,
"s": 3597,
"text": "C#"
}
]
|
Program for replacing one digit with other | 26 May, 2022
Given a number x and two digits d1 and d2, replace d1 with d2 in x.Examples:
Input : x = 645, d1 = 6, d2 = 5
Output : 545
We replace digit 6 with 5 in number 645.
Input : x = 746, d1 = 7, d2 = 8
Output : 846
We traverse through all digits of x. For every digit, we check if it is d1, we update result accordingly.
C++
C
Java
Python3
C#
PHP
Javascript
// CPP program to replace a digit with other// in a given number.#include <bits/stdc++.h>using namespace std; int replaceDigit(int x, int d1, int d2){ int result = 0, multiply = 1; while (x / 10 > 0) { // Take remainder of number starting from the unit // place digit int remainder = x % 10; // check whether it is equal to the digit to be // replaced.if yes then replace if (remainder == d1) result = result + d2 * multiply; else // else remain as such result = result + remainder * multiply; // Update and move forward from unit place to // hundred place and so on. multiply *= 10; x = x / 10; // update the value } // check whether it is equal to the digit to be // replaced.if yes then replace if (x == d1) result = result + d2 * multiply; else // else remain as such result = result + x * multiply; return result;} // Driver codeint main(){ int x = 645, d1 = 6, d2 = 5; cout << replaceDigit(x, d1, d2) << endl; return 0;} // This code is contributed by Sania Kumari Gupta
// C program to replace a digit with other// in a given number.#include <stdio.h> int replaceDigit(int x, int d1, int d2){ int result = 0, multiply = 1; while (x / 10 > 0) { // Take remainder of number starting from the unit // place digit int remainder = x % 10; // check whether it is equal to the digit to be // replaced.if yes then replace if (remainder == d1) result = result + d2 * multiply; else // else remain as such result = result + remainder * multiply; // Update and move forward from unit place to // hundred place and so on. multiply *= 10; x = x / 10; // update the value } // check whether it is equal to the digit to be // replaced.if yes then replace if (x == d1) result = result + d2 * multiply; else // else remain as such result = result + x * multiply; return result;} // Driver codeint main(){ int x = 645, d1 = 6, d2 = 5; printf("%d\n", replaceDigit(x, d1, d2)); return 0;} // This code is contributed by Sania Kumari Gupta
// Java program to replace a digit// with other in a given number.class GFG { static int replaceDigit(int x, int d1, int d2) { int result = 0, multiply = 1; while (x / 10 > 0) { // Take remainder of number starting from the // unit place digit int remainder = x % 10; // check whether it is equal to the digit to be // replaced. if yes then replace if (remainder == d1) result = result + d2 * multiply; else // else remain as such result = result + remainder * multiply; // Update and move forward from unit place to // hundred place and so on. multiply *= 10; x = x / 10; // update the value } // check whether it is equal to the digit to be // replaced.if yes then replace if (x == d1) result = result + d2 * multiply; else // else remain as such result = result + x * multiply; return result; } // Driver code public static void main(String[] args) { int x = 645, d1 = 6, d2 = 5; System.out.println(replaceDigit(x, d1, d2)); }} // This code is contributed by Sania Kumari Gupta
# Python3 program to replace# a digit with other# in a given number. def replaceDigit(x, d1, d2): result = 0 multiply = 1 while (x // 10 > 0): # Take remainder of number # starting from the unit # place digit remainder = x % 10 # check whether it is # equal to the digit # to be replaced.if yes # then replace if (remainder == d1): result = (result + d2 * multiply) else: # else remain as such result = (result + remainder * multiply) # Update and move forward # from unit place to hundred # place and so on. multiply *= 10 x = int(x / 10) # update the value # check whether it is equal to the digit # to be replaced.if yes then replace if (x == d1): result = result + d2 * multiply else: # else remain as such result = result + x * multiply return result # Driver codex = 645d1 = 6d2 = 5print(replaceDigit(x, d1, d2)) # This Code is contributed# by mits
// C# program to replace a digit// with other in a given numberusing System;class GFG{ static int replaceDigit(int x, int d1, int d2) { int result = 0, multiply = 1; while (x / 10 > 0) { // Take remainder of number // starting from the unit // place digit int remainder = x % 10; // check whether it is equal // to the digit to be replaced. // if yes then replace if (remainder == d1) result = result + d2 * multiply; else // else remain as such result = result + remainder * multiply; // Update and move forward // from unit place to // hundred place and so on. multiply *= 10; x = x / 10; // update the value } // check whether it is equal to the digit // to be replaced.if yes then replace if (x == d1) result = result + d2 * multiply; else // else remain as such result = result + x * multiply; return result; } // Driver code public static void Main() { int x = 645, d1 = 6, d2 = 5; Console.WriteLine(replaceDigit(x, d1, d2)); }} // This Code is contributed// by inder_verma
<?php// PHP program to replace// a digit with other// in a given number. function replaceDigit($x, $d1, $d2){ $result = 0; $multiply = 1; while ($x / 10 > 0) { // Take remainder of number // starting from the unit // place digit $remainder = $x % 10; // check whether it is // equal to the digit // to be replaced.if yes // then replace if ($remainder == $d1) $result = $result + $d2 * $multiply; else // else remain as such $result = $result + $remainder * $multiply; // Update and move forward // from unit place to hundred // place and so on. $multiply *= 10; $x = $x / 10; // update the value } // check whether it is equal to the digit // to be replaced.if yes then replace if ($x == $d1) $result = $result + $d2 * $multiply; else // else remain as such $result = $result + $x * $multiply; return $result;} // Driver code$x = 645; $d1 = 6; $d2 = 5;echo replaceDigit($x, $d1, $d2); // This Code is contributed// by inder_verma?>
<script> // Javascript program to replace a digit // with other in a given number function replaceDigit(x, d1, d2) { let result = 0, multiply = 1; while (parseInt(x / 10, 10) > 0) { // Take remainder of number // starting from the unit // place digit let remainder = x % 10; // check whether it is equal // to the digit to be replaced. // if yes then replace if (remainder == d1) result = result + d2 * multiply; else // else remain as such result = result + remainder * multiply; // Update and move forward // from unit place to // hundred place and so on. multiply *= 10; x = parseInt(x / 10, 10); // update the value } // check whether it is equal to the digit // to be replaced.if yes then replace if (x == d1) result = result + d2 * multiply; else // else remain as such result = result + x * multiply; return result; } let x = 645, d1 = 6, d2 = 5; document.write(replaceDigit(x, d1, d2)); // This code is contributed by rameshtravel07.</script>
545
Time Complexity: O(logn), where n is the given number.
Auxiliary Space: O(1)
Mithun Kumar
inderDuMCA
Akanksha_Rai
kirankadam633
rameshtravel07
krisania804
rohitmishra051000
Accenture
number-digits
Mathematical
Accenture
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Sum of the series (1*2) + (2*3) + (3*4) + ...... upto n terms
Merge two sorted arrays with O(1) extra space
Program to print prime numbers from 1 to N.
Count ways to reach the n'th stair
Segment Tree | Set 1 (Sum of given range)
Check if a number is Palindrome
Median of two sorted arrays of same size
Count all possible paths from top left to bottom right of a mXn matrix
Maximize difference between the Sum of the two halves of the Array after removal of N elements | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n26 May, 2022"
},
{
"code": null,
"e": 130,
"s": 52,
"text": "Given a number x and two digits d1 and d2, replace d1 with d2 in x.Examples: "
},
{
"code": null,
"e": 263,
"s": 130,
"text": "Input : x = 645, d1 = 6, d2 = 5\nOutput : 545\nWe replace digit 6 with 5 in number 645.\n\nInput : x = 746, d1 = 7, d2 = 8\nOutput : 846"
},
{
"code": null,
"e": 371,
"s": 263,
"text": "We traverse through all digits of x. For every digit, we check if it is d1, we update result accordingly. "
},
{
"code": null,
"e": 375,
"s": 371,
"text": "C++"
},
{
"code": null,
"e": 377,
"s": 375,
"text": "C"
},
{
"code": null,
"e": 382,
"s": 377,
"text": "Java"
},
{
"code": null,
"e": 390,
"s": 382,
"text": "Python3"
},
{
"code": null,
"e": 393,
"s": 390,
"text": "C#"
},
{
"code": null,
"e": 397,
"s": 393,
"text": "PHP"
},
{
"code": null,
"e": 408,
"s": 397,
"text": "Javascript"
},
{
"code": "// CPP program to replace a digit with other// in a given number.#include <bits/stdc++.h>using namespace std; int replaceDigit(int x, int d1, int d2){ int result = 0, multiply = 1; while (x / 10 > 0) { // Take remainder of number starting from the unit // place digit int remainder = x % 10; // check whether it is equal to the digit to be // replaced.if yes then replace if (remainder == d1) result = result + d2 * multiply; else // else remain as such result = result + remainder * multiply; // Update and move forward from unit place to // hundred place and so on. multiply *= 10; x = x / 10; // update the value } // check whether it is equal to the digit to be // replaced.if yes then replace if (x == d1) result = result + d2 * multiply; else // else remain as such result = result + x * multiply; return result;} // Driver codeint main(){ int x = 645, d1 = 6, d2 = 5; cout << replaceDigit(x, d1, d2) << endl; return 0;} // This code is contributed by Sania Kumari Gupta",
"e": 1531,
"s": 408,
"text": null
},
{
"code": "// C program to replace a digit with other// in a given number.#include <stdio.h> int replaceDigit(int x, int d1, int d2){ int result = 0, multiply = 1; while (x / 10 > 0) { // Take remainder of number starting from the unit // place digit int remainder = x % 10; // check whether it is equal to the digit to be // replaced.if yes then replace if (remainder == d1) result = result + d2 * multiply; else // else remain as such result = result + remainder * multiply; // Update and move forward from unit place to // hundred place and so on. multiply *= 10; x = x / 10; // update the value } // check whether it is equal to the digit to be // replaced.if yes then replace if (x == d1) result = result + d2 * multiply; else // else remain as such result = result + x * multiply; return result;} // Driver codeint main(){ int x = 645, d1 = 6, d2 = 5; printf(\"%d\\n\", replaceDigit(x, d1, d2)); return 0;} // This code is contributed by Sania Kumari Gupta",
"e": 2653,
"s": 1531,
"text": null
},
{
"code": "// Java program to replace a digit// with other in a given number.class GFG { static int replaceDigit(int x, int d1, int d2) { int result = 0, multiply = 1; while (x / 10 > 0) { // Take remainder of number starting from the // unit place digit int remainder = x % 10; // check whether it is equal to the digit to be // replaced. if yes then replace if (remainder == d1) result = result + d2 * multiply; else // else remain as such result = result + remainder * multiply; // Update and move forward from unit place to // hundred place and so on. multiply *= 10; x = x / 10; // update the value } // check whether it is equal to the digit to be // replaced.if yes then replace if (x == d1) result = result + d2 * multiply; else // else remain as such result = result + x * multiply; return result; } // Driver code public static void main(String[] args) { int x = 645, d1 = 6, d2 = 5; System.out.println(replaceDigit(x, d1, d2)); }} // This code is contributed by Sania Kumari Gupta",
"e": 3899,
"s": 2653,
"text": null
},
{
"code": "# Python3 program to replace# a digit with other# in a given number. def replaceDigit(x, d1, d2): result = 0 multiply = 1 while (x // 10 > 0): # Take remainder of number # starting from the unit # place digit remainder = x % 10 # check whether it is # equal to the digit # to be replaced.if yes # then replace if (remainder == d1): result = (result + d2 * multiply) else: # else remain as such result = (result + remainder * multiply) # Update and move forward # from unit place to hundred # place and so on. multiply *= 10 x = int(x / 10) # update the value # check whether it is equal to the digit # to be replaced.if yes then replace if (x == d1): result = result + d2 * multiply else: # else remain as such result = result + x * multiply return result # Driver codex = 645d1 = 6d2 = 5print(replaceDigit(x, d1, d2)) # This Code is contributed# by mits",
"e": 4973,
"s": 3899,
"text": null
},
{
"code": "// C# program to replace a digit// with other in a given numberusing System;class GFG{ static int replaceDigit(int x, int d1, int d2) { int result = 0, multiply = 1; while (x / 10 > 0) { // Take remainder of number // starting from the unit // place digit int remainder = x % 10; // check whether it is equal // to the digit to be replaced. // if yes then replace if (remainder == d1) result = result + d2 * multiply; else // else remain as such result = result + remainder * multiply; // Update and move forward // from unit place to // hundred place and so on. multiply *= 10; x = x / 10; // update the value } // check whether it is equal to the digit // to be replaced.if yes then replace if (x == d1) result = result + d2 * multiply; else // else remain as such result = result + x * multiply; return result; } // Driver code public static void Main() { int x = 645, d1 = 6, d2 = 5; Console.WriteLine(replaceDigit(x, d1, d2)); }} // This Code is contributed// by inder_verma",
"e": 6265,
"s": 4973,
"text": null
},
{
"code": "<?php// PHP program to replace// a digit with other// in a given number. function replaceDigit($x, $d1, $d2){ $result = 0; $multiply = 1; while ($x / 10 > 0) { // Take remainder of number // starting from the unit // place digit $remainder = $x % 10; // check whether it is // equal to the digit // to be replaced.if yes // then replace if ($remainder == $d1) $result = $result + $d2 * $multiply; else // else remain as such $result = $result + $remainder * $multiply; // Update and move forward // from unit place to hundred // place and so on. $multiply *= 10; $x = $x / 10; // update the value } // check whether it is equal to the digit // to be replaced.if yes then replace if ($x == $d1) $result = $result + $d2 * $multiply; else // else remain as such $result = $result + $x * $multiply; return $result;} // Driver code$x = 645; $d1 = 6; $d2 = 5;echo replaceDigit($x, $d1, $d2); // This Code is contributed// by inder_verma?>",
"e": 7452,
"s": 6265,
"text": null
},
{
"code": "<script> // Javascript program to replace a digit // with other in a given number function replaceDigit(x, d1, d2) { let result = 0, multiply = 1; while (parseInt(x / 10, 10) > 0) { // Take remainder of number // starting from the unit // place digit let remainder = x % 10; // check whether it is equal // to the digit to be replaced. // if yes then replace if (remainder == d1) result = result + d2 * multiply; else // else remain as such result = result + remainder * multiply; // Update and move forward // from unit place to // hundred place and so on. multiply *= 10; x = parseInt(x / 10, 10); // update the value } // check whether it is equal to the digit // to be replaced.if yes then replace if (x == d1) result = result + d2 * multiply; else // else remain as such result = result + x * multiply; return result; } let x = 645, d1 = 6, d2 = 5; document.write(replaceDigit(x, d1, d2)); // This code is contributed by rameshtravel07.</script>",
"e": 8719,
"s": 7452,
"text": null
},
{
"code": null,
"e": 8723,
"s": 8719,
"text": "545"
},
{
"code": null,
"e": 8780,
"s": 8725,
"text": "Time Complexity: O(logn), where n is the given number."
},
{
"code": null,
"e": 8802,
"s": 8780,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 8815,
"s": 8802,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 8826,
"s": 8815,
"text": "inderDuMCA"
},
{
"code": null,
"e": 8839,
"s": 8826,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 8853,
"s": 8839,
"text": "kirankadam633"
},
{
"code": null,
"e": 8868,
"s": 8853,
"text": "rameshtravel07"
},
{
"code": null,
"e": 8880,
"s": 8868,
"text": "krisania804"
},
{
"code": null,
"e": 8898,
"s": 8880,
"text": "rohitmishra051000"
},
{
"code": null,
"e": 8908,
"s": 8898,
"text": "Accenture"
},
{
"code": null,
"e": 8922,
"s": 8908,
"text": "number-digits"
},
{
"code": null,
"e": 8935,
"s": 8922,
"text": "Mathematical"
},
{
"code": null,
"e": 8945,
"s": 8935,
"text": "Accenture"
},
{
"code": null,
"e": 8958,
"s": 8945,
"text": "Mathematical"
},
{
"code": null,
"e": 9056,
"s": 8958,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9088,
"s": 9056,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 9150,
"s": 9088,
"text": "Sum of the series (1*2) + (2*3) + (3*4) + ...... upto n terms"
},
{
"code": null,
"e": 9196,
"s": 9150,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 9240,
"s": 9196,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 9275,
"s": 9240,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 9317,
"s": 9275,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 9349,
"s": 9317,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 9390,
"s": 9349,
"text": "Median of two sorted arrays of same size"
},
{
"code": null,
"e": 9461,
"s": 9390,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
}
]
|
Swing Examples - Change the default icon of the window | Following example showcase how to change the default icon of the window in Swing based application.
We are using the following APIs.
ImageIcon − To create an image icon.
ImageIcon − To create an image icon.
JFrame.setIconImage() − To set the icon to the window.
JFrame.setIconImage() − To set the icon to the window.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class SwingTester {
public static void main(String[] args) {
createWindow();
}
private static void createWindow() {
JFrame frame = new JFrame("Swing Tester");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon arrowIcon = null;
java.net.URL imgURL = SwingTester.class.getResource("arrow.jpg");
if (imgURL != null) {
arrowIcon = new ImageIcon(imgURL);
frame.setIconImage(arrowIcon.getImage());
} else {
JOptionPane.showMessageDialog(frame, "Icon image not found.");
}
createUI(frame);
frame.setSize(560, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void createUI(JFrame frame){
JPanel panel = new JPanel();
LayoutManager layout = new FlowLayout();
panel.setLayout(layout);
panel.add(new JLabel("Hello World!"));
frame.getContentPane().add(panel, BorderLayout.CENTER);
}
}
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2139,
"s": 2039,
"text": "Following example showcase how to change the default icon of the window in Swing based application."
},
{
"code": null,
"e": 2172,
"s": 2139,
"text": "We are using the following APIs."
},
{
"code": null,
"e": 2209,
"s": 2172,
"text": "ImageIcon − To create an image icon."
},
{
"code": null,
"e": 2246,
"s": 2209,
"text": "ImageIcon − To create an image icon."
},
{
"code": null,
"e": 2301,
"s": 2246,
"text": "JFrame.setIconImage() − To set the icon to the window."
},
{
"code": null,
"e": 2356,
"s": 2301,
"text": "JFrame.setIconImage() − To set the icon to the window."
},
{
"code": null,
"e": 3618,
"s": 2356,
"text": "import java.awt.BorderLayout;\nimport java.awt.FlowLayout;\nimport java.awt.LayoutManager;\n\nimport javax.swing.ImageIcon;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\n\npublic class SwingTester {\n public static void main(String[] args) {\n createWindow(); \n }\n \n private static void createWindow() { \n JFrame frame = new JFrame(\"Swing Tester\"); \n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n ImageIcon arrowIcon = null;\n\n java.net.URL imgURL = SwingTester.class.getResource(\"arrow.jpg\");\n if (imgURL != null) {\n arrowIcon = new ImageIcon(imgURL);\n frame.setIconImage(arrowIcon.getImage());\n } else {\n JOptionPane.showMessageDialog(frame, \"Icon image not found.\");\n }\n\n createUI(frame);\n frame.setSize(560, 200); \n frame.setLocationRelativeTo(null); \n frame.setVisible(true);\n }\n\n private static void createUI(JFrame frame){ \n JPanel panel = new JPanel();\n LayoutManager layout = new FlowLayout(); \n panel.setLayout(layout); \n panel.add(new JLabel(\"Hello World!\"));\n\n frame.getContentPane().add(panel, BorderLayout.CENTER); \n }\n}"
},
{
"code": null,
"e": 3625,
"s": 3618,
"text": " Print"
},
{
"code": null,
"e": 3636,
"s": 3625,
"text": " Add Notes"
}
]
|
LESS - Namespaces and Accessors | Namespaces are used to group the mixins under a common name. Using namespaces, you can avoid conflict in name and encapsulate a group of mixins from outside.
The following example demonstrates the use of namespaces and accessors in the LESS file −
<html>
<head>
<title>Less Namespaces and Accessors</title>
<link rel = "stylesheet" type = "text/css" href = "style.css" />
</head>
<body>
<h1>Example using Namespaces and Accessors</h1>
<p class = "myclass">LESS enables customizable,
manageable and reusable style sheet for web site.</p>
</body>
</html>
Now create the style.less file.
.class1 {
.class2 {
.val(@param) {
font-size: @param;
color:green;
}
}
}
.myclass {
.class1 > .class2 > .val(20px);
}
You can compile the style.less file to style.css by using the following command −
lessc style.less style.css
Execute the above command; it will create the style.css file automatically with the following code −
.myclass {
font-size: 20px;
color: green;
}
Follow these steps to see how the above code works −
Save the above html code in the namespaces_accessors.html file.
Save the above html code in the namespaces_accessors.html file.
Open this HTML file in a browser, the following output will get displayed.
Open this HTML file in a browser, the following output will get displayed.
20 Lectures
1 hours
Anadi Sharma
44 Lectures
7.5 hours
Eduonix Learning Solutions
17 Lectures
2 hours
Zach Miller
23 Lectures
1.5 hours
Zach Miller
34 Lectures
4 hours
Syed Raza
31 Lectures
3 hours
Harshit Srivastava
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2708,
"s": 2550,
"text": "Namespaces are used to group the mixins under a common name. Using namespaces, you can avoid conflict in name and encapsulate a group of mixins from outside."
},
{
"code": null,
"e": 2798,
"s": 2708,
"text": "The following example demonstrates the use of namespaces and accessors in the LESS file −"
},
{
"code": null,
"e": 3150,
"s": 2798,
"text": "<html>\n <head>\n <title>Less Namespaces and Accessors</title>\n <link rel = \"stylesheet\" type = \"text/css\" href = \"style.css\" />\n </head>\n \n <body>\n <h1>Example using Namespaces and Accessors</h1>\n <p class = \"myclass\">LESS enables customizable, \n manageable and reusable style sheet for web site.</p>\n </body>\n</html>"
},
{
"code": null,
"e": 3182,
"s": 3150,
"text": "Now create the style.less file."
},
{
"code": null,
"e": 3340,
"s": 3182,
"text": ".class1 {\n .class2 {\n .val(@param) {\n font-size: @param;\n color:green;\n }\n }\n}\n\n.myclass {\n .class1 > .class2 > .val(20px);\n}"
},
{
"code": null,
"e": 3422,
"s": 3340,
"text": "You can compile the style.less file to style.css by using the following command −"
},
{
"code": null,
"e": 3450,
"s": 3422,
"text": "lessc style.less style.css\n"
},
{
"code": null,
"e": 3551,
"s": 3450,
"text": "Execute the above command; it will create the style.css file automatically with the following code −"
},
{
"code": null,
"e": 3601,
"s": 3551,
"text": ".myclass {\n font-size: 20px;\n color: green;\n}"
},
{
"code": null,
"e": 3654,
"s": 3601,
"text": "Follow these steps to see how the above code works −"
},
{
"code": null,
"e": 3718,
"s": 3654,
"text": "Save the above html code in the namespaces_accessors.html file."
},
{
"code": null,
"e": 3782,
"s": 3718,
"text": "Save the above html code in the namespaces_accessors.html file."
},
{
"code": null,
"e": 3857,
"s": 3782,
"text": "Open this HTML file in a browser, the following output will get displayed."
},
{
"code": null,
"e": 3932,
"s": 3857,
"text": "Open this HTML file in a browser, the following output will get displayed."
},
{
"code": null,
"e": 3965,
"s": 3932,
"text": "\n 20 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3979,
"s": 3965,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4014,
"s": 3979,
"text": "\n 44 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 4042,
"s": 4014,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4075,
"s": 4042,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4088,
"s": 4075,
"text": " Zach Miller"
},
{
"code": null,
"e": 4123,
"s": 4088,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4136,
"s": 4123,
"text": " Zach Miller"
},
{
"code": null,
"e": 4169,
"s": 4136,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4180,
"s": 4169,
"text": " Syed Raza"
},
{
"code": null,
"e": 4213,
"s": 4180,
"text": "\n 31 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 4233,
"s": 4213,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 4240,
"s": 4233,
"text": " Print"
},
{
"code": null,
"e": 4251,
"s": 4240,
"text": " Add Notes"
}
]
|
System Design Using Microcontroller | Microprocessors and microcontrollers can be used to design some tools or systems to perform some special tasks. Using microcontrollers, we can make different types of modules or systems. Here is a list of some systems that can be designed by using microcontrollers −
Electronic Voting Machine
Electronic Voting Machine
RFID based Access Control System
RFID based Access Control System
Heart Rate monitoring system
Heart Rate monitoring system
Automatic Plant watering system
Automatic Plant watering system
Ultrasonic range finding system
Ultrasonic range finding system
Water level controlling system
Water level controlling system
Gas leakage detection system
Gas leakage detection system
Frequency Meters
Frequency Meters
Temperature measuring system
Temperature measuring system
There are many such systems that can be made by using some microcontrollers.
To design a system, we have to follow some basic steps. We have to design the overview of the system, and some functional block designs to construct the system easily. Then we have to design the circuit diagrams, and apply the component values after doing some calculations. Then after checking the entire circuit diagrams, at last we should start the work practically. In this phase we will implement the circuits by using required components.
In this article we will see how we can design a Digital Tachometer using microcontroller. Here we are using the Intel 8051 Microcontroller.
A Tachometer is basically a system that can measure the revolution/second of some rotating wheel, disc, shaft etc. Our tachometer can measure up to 255 revolution/second at an accuracy of 1 revolution/second.
Now let us see how the circuit diagrams will be for this digital tachometer.
We can divide this circuit into some several parts. In the first part we will see how the circuit is taking information physically. There are two components Q4 and D4. The Q4 is a photo transistor (2N5777), and D4 is one Red LED. If light comes into this photo transistor, it collector current turns drops towards 0. At first we have to attach some rotating disc on the shaft, and there will be one punch hole. When the disc is rotating, at the upper portion of the disc the LED is attached, and at the lower portion the photo transistor is set. When the disc comes in the same line, the light hits the photo transistor, and the collector current drops down to zero. This following figure is showing how it will be looking if we see that using an oscilloscope.
In the next part we can see there is an OPAMP (Operational Amplifier) in the circuit. For the OPAMP, we have used LM234 Chip. This chip is holding four OPAMPs, but here we have used one of them. In this circuit the OPAMP is connected as a voltage comparator. Here the reference voltage is 3.5V. So if the output voltage of the photo transistor is greater than 3.5V, then it will generate high pulse, otherwise it will generate 0 level signal. From this comparator we will get the square wave pulses of the previous output.
From this falling edge we can understand that hole has come, so there is one revolution. This clock pulse is fed into the microcontroller. This signal can be used to count the number of revolutions.
At the third part the microcontroller is working. This microcontroller is performing two tasks together. These two tasks are −
Counting the number of negative edges from the output of the comparator.
Counting the number of negative edges from the output of the comparator.
Do necessary mathematics, and display the count on the seven segment display array.
Do necessary mathematics, and display the count on the seven segment display array.
To count the revolutions, we have used both the timers (Timer0 and Timer1) of 8085. Here Timer1 is configured as auto-reload 8-bit counter, and for registering the number of incoming zeros are stored into Timer0. The Timer0 is set as 16-bit timer, and it generates the necessary one second time span for the Timer1 to count.
Program of 8051 for the Digital Tachometer
ORG 000H
MOV DPTR,#LUT ; Loads the address of LUT to DPTR
MOV P1,#00000000B ; Sets P1 and P0 as an output port
MOV P0,#00000000B
MAIN: MOV R6,#14D
SETB P3.5
MOV TMOD,#01100001B ; Sets Timer1 as Mode2 & Timer0 as Mode1
timer
MOV TL1,#00000000B ; loads starting value to TL1
MOV TH1,#00000000B ; loads starting value to TH1
SETB TR1 ; starts Timer1 (counter)
BACK: MOV TH0,#00000000B ; loads starting value to TH0
MOV TL0,#00000000B ; loads starting value to TL0
SETB TR0 ; starts Timer0
HERE: JNB TF0,HERE ; checks for Timer 0 roll over
CLR TR0 ; stops Timer0
CLR TF0 ; clears Timer Flag 0
DJNZ R6,BACK
CLR TR1 ; stops Timer1 (counter)
CLR TF0 ; clears Timer Flag 0
CLR TF1 ; clears Timer Flag 1
ACALL DLOOP ; Calls subroutine DLOOP for displaying
the count
SJMP MAIN ; jumps back to the main loop
DLOOP: MOV R5,#100D
BACK1: MOV A,TL1 ; loads the count to the accumulator
MOV B,#100D
DIV AB ; isolates the first digit of the count
SETB P1.0
ACALL DISPLAY ; converts the 1st digit to 7 seg-display
pattern
MOV P0,A ; puts the pattern to Port 0
ACALL DELAY ; 1mS delay
ACALL DELAY
MOV A,B
MOV B,#10D
DIV AB ; isolates the second digit of the count
CLR P1.0
SETB P1.1
ACALL DISPLAY ; converts the 2nd digit to 7 seg-display
pattern
MOV P0,A
ACALL DELAY
ACALL DELAY
MOV A,B ; Loads the last digit of the count to
accumulator
CLR P1.1
SETB P1.2
ACALL DISPLAY ; converts the 3rd digit to 7 seg-display
pattern
MOV P0,A
ACALL DELAY
ACALL DELAY
CLR P1.2
DJNZ R5,BACK1 ; repeats the subroutine DLOOP 100 times
RET
DELAY: MOV R7,#250D ; Subroutine to generate 1mS delay
DEL1: DJNZ R7,DEL1
RET
DISPLAY: MOVC A,@A+DPTR ; gets 7 seg digit drive pattern for
current value in A
CPL A
RET
LUT: DB 3FH ; Look up table for 7-seg-display
DB 06H
DB 5BH
DB 4FH
DB 66H
DB 6DH
DB 7DH
DB 07H
DB 7FH
DB 6FH
END | [
{
"code": null,
"e": 1329,
"s": 1062,
"text": "Microprocessors and microcontrollers can be used to design some tools or systems to perform some special tasks. Using microcontrollers, we can make different types of modules or systems. Here is a list of some systems that can be designed by using microcontrollers −"
},
{
"code": null,
"e": 1355,
"s": 1329,
"text": "Electronic Voting Machine"
},
{
"code": null,
"e": 1381,
"s": 1355,
"text": "Electronic Voting Machine"
},
{
"code": null,
"e": 1414,
"s": 1381,
"text": "RFID based Access Control System"
},
{
"code": null,
"e": 1447,
"s": 1414,
"text": "RFID based Access Control System"
},
{
"code": null,
"e": 1476,
"s": 1447,
"text": "Heart Rate monitoring system"
},
{
"code": null,
"e": 1505,
"s": 1476,
"text": "Heart Rate monitoring system"
},
{
"code": null,
"e": 1537,
"s": 1505,
"text": "Automatic Plant watering system"
},
{
"code": null,
"e": 1569,
"s": 1537,
"text": "Automatic Plant watering system"
},
{
"code": null,
"e": 1601,
"s": 1569,
"text": "Ultrasonic range finding system"
},
{
"code": null,
"e": 1633,
"s": 1601,
"text": "Ultrasonic range finding system"
},
{
"code": null,
"e": 1664,
"s": 1633,
"text": "Water level controlling system"
},
{
"code": null,
"e": 1695,
"s": 1664,
"text": "Water level controlling system"
},
{
"code": null,
"e": 1724,
"s": 1695,
"text": "Gas leakage detection system"
},
{
"code": null,
"e": 1753,
"s": 1724,
"text": "Gas leakage detection system"
},
{
"code": null,
"e": 1770,
"s": 1753,
"text": "Frequency Meters"
},
{
"code": null,
"e": 1787,
"s": 1770,
"text": "Frequency Meters"
},
{
"code": null,
"e": 1816,
"s": 1787,
"text": "Temperature measuring system"
},
{
"code": null,
"e": 1845,
"s": 1816,
"text": "Temperature measuring system"
},
{
"code": null,
"e": 1922,
"s": 1845,
"text": "There are many such systems that can be made by using some microcontrollers."
},
{
"code": null,
"e": 2367,
"s": 1922,
"text": "To design a system, we have to follow some basic steps. We have to design the overview of the system, and some functional block designs to construct the system easily. Then we have to design the circuit diagrams, and apply the component values after doing some calculations. Then after checking the entire circuit diagrams, at last we should start the work practically. In this phase we will implement the circuits by using required components."
},
{
"code": null,
"e": 2507,
"s": 2367,
"text": "In this article we will see how we can design a Digital Tachometer using microcontroller. Here we are using the Intel 8051 Microcontroller."
},
{
"code": null,
"e": 2716,
"s": 2507,
"text": "A Tachometer is basically a system that can measure the revolution/second of some rotating wheel, disc, shaft etc. Our tachometer can measure up to 255 revolution/second at an accuracy of 1 revolution/second."
},
{
"code": null,
"e": 2793,
"s": 2716,
"text": "Now let us see how the circuit diagrams will be for this digital tachometer."
},
{
"code": null,
"e": 3554,
"s": 2793,
"text": "We can divide this circuit into some several parts. In the first part we will see how the circuit is taking information physically. There are two components Q4 and D4. The Q4 is a photo transistor (2N5777), and D4 is one Red LED. If light comes into this photo transistor, it collector current turns drops towards 0. At first we have to attach some rotating disc on the shaft, and there will be one punch hole. When the disc is rotating, at the upper portion of the disc the LED is attached, and at the lower portion the photo transistor is set. When the disc comes in the same line, the light hits the photo transistor, and the collector current drops down to zero. This following figure is showing how it will be looking if we see that using an oscilloscope."
},
{
"code": null,
"e": 4077,
"s": 3554,
"text": "In the next part we can see there is an OPAMP (Operational Amplifier) in the circuit. For the OPAMP, we have used LM234 Chip. This chip is holding four OPAMPs, but here we have used one of them. In this circuit the OPAMP is connected as a voltage comparator. Here the reference voltage is 3.5V. So if the output voltage of the photo transistor is greater than 3.5V, then it will generate high pulse, otherwise it will generate 0 level signal. From this comparator we will get the square wave pulses of the previous output."
},
{
"code": null,
"e": 4276,
"s": 4077,
"text": "From this falling edge we can understand that hole has come, so there is one revolution. This clock pulse is fed into the microcontroller. This signal can be used to count the number of revolutions."
},
{
"code": null,
"e": 4403,
"s": 4276,
"text": "At the third part the microcontroller is working. This microcontroller is performing two tasks together. These two tasks are −"
},
{
"code": null,
"e": 4476,
"s": 4403,
"text": "Counting the number of negative edges from the output of the comparator."
},
{
"code": null,
"e": 4549,
"s": 4476,
"text": "Counting the number of negative edges from the output of the comparator."
},
{
"code": null,
"e": 4633,
"s": 4549,
"text": "Do necessary mathematics, and display the count on the seven segment display array."
},
{
"code": null,
"e": 4717,
"s": 4633,
"text": "Do necessary mathematics, and display the count on the seven segment display array."
},
{
"code": null,
"e": 5042,
"s": 4717,
"text": "To count the revolutions, we have used both the timers (Timer0 and Timer1) of 8085. Here Timer1 is configured as auto-reload 8-bit counter, and for registering the number of incoming zeros are stored into Timer0. The Timer0 is set as 16-bit timer, and it generates the necessary one second time span for the Timer1 to count."
},
{
"code": null,
"e": 5085,
"s": 5042,
"text": "Program of 8051 for the Digital Tachometer"
},
{
"code": null,
"e": 6870,
"s": 5085,
"text": "ORG 000H\nMOV DPTR,#LUT ; Loads the address of LUT to DPTR\nMOV P1,#00000000B ; Sets P1 and P0 as an output port\nMOV P0,#00000000B\nMAIN: MOV R6,#14D\nSETB P3.5\nMOV TMOD,#01100001B ; Sets Timer1 as Mode2 & Timer0 as Mode1\ntimer\nMOV TL1,#00000000B ; loads starting value to TL1\nMOV TH1,#00000000B ; loads starting value to TH1\nSETB TR1 ; starts Timer1 (counter)\nBACK: MOV TH0,#00000000B ; loads starting value to TH0\nMOV TL0,#00000000B ; loads starting value to TL0\nSETB TR0 ; starts Timer0\nHERE: JNB TF0,HERE ; checks for Timer 0 roll over\nCLR TR0 ; stops Timer0\nCLR TF0 ; clears Timer Flag 0\nDJNZ R6,BACK\nCLR TR1 ; stops Timer1 (counter)\nCLR TF0 ; clears Timer Flag 0\nCLR TF1 ; clears Timer Flag 1\nACALL DLOOP ; Calls subroutine DLOOP for displaying\nthe count\nSJMP MAIN ; jumps back to the main loop\nDLOOP: MOV R5,#100D\nBACK1: MOV A,TL1 ; loads the count to the accumulator\nMOV B,#100D\nDIV AB ; isolates the first digit of the count\nSETB P1.0\nACALL DISPLAY ; converts the 1st digit to 7 seg-display\npattern\nMOV P0,A ; puts the pattern to Port 0\nACALL DELAY ; 1mS delay\nACALL DELAY\nMOV A,B\nMOV B,#10D\nDIV AB ; isolates the second digit of the count\nCLR P1.0\nSETB P1.1\nACALL DISPLAY ; converts the 2nd digit to 7 seg-display\npattern\nMOV P0,A\nACALL DELAY\nACALL DELAY\nMOV A,B ; Loads the last digit of the count to\naccumulator\nCLR P1.1\nSETB P1.2\nACALL DISPLAY ; converts the 3rd digit to 7 seg-display\npattern\nMOV P0,A\nACALL DELAY\nACALL DELAY\nCLR P1.2\nDJNZ R5,BACK1 ; repeats the subroutine DLOOP 100 times\nRET\nDELAY: MOV R7,#250D ; Subroutine to generate 1mS delay\nDEL1: DJNZ R7,DEL1\nRET\nDISPLAY: MOVC A,@A+DPTR ; gets 7 seg digit drive pattern for\ncurrent value in A\nCPL A\nRET\nLUT: DB 3FH ; Look up table for 7-seg-display\nDB 06H\nDB 5BH\nDB 4FH\nDB 66H\nDB 6DH\nDB 7DH\nDB 07H\nDB 7FH\nDB 6FH\nEND"
}
]
|
An Overview of Data Analysis with the Tidyverse Library in R | by Rashida Nasrin Sucky | Towards Data Science | The ‘tidyverse’ package in R is a very useful tool for data analysis in R as it covers almost everything you need to analyze a dataset. It is a combination of several big libraries that makes it a huge library to learn. In his article, I will try to provide a good overview of the tidyverse library that gives enough resources to perform a data analysis task well and also a great base for further learning. It can also be used as a cheat sheet.
If one does not have years of experience, it can be useful to have a list of operations or data analysis ideas on a page in front of you. So, I tried to compile quite a good amount of commonly used operations on this page to help myself and you.
The everyday data analysis packages that are included in tidyverse package are:
ggplot2
dplyr
tidyr
readr
purr
tibble
stringr
forcats
This article touches all of these packages except tibble. If you do not know what tibble is, it is also a kind of DataFrame. I am not going on details here. I used simple data frames for all the example here.
I will start with some simple things and slowly move towards some more complex tasks.
Let’s start!
First import the tidyverse library.
library(tidyverse)
I will start with some simple functions of stringr library which are pretty self-explanatory. So, I will not explain them too much.
Converting a string to lower case:
x = "Happy New Year 2022"str_to_lower(x)
Output:
[1] "happy new year 2022"
Converting a string to upper case:
str_to_upper(x)
Output:
[1] "HAPPY NEW YEAR 2022"
Combining several strings to one:
str_c("I ", "am ", "very ", "happy")
Output:
[1] "I am very happy"
Taking a subset of a list of strings:
Here I will make a list of strings and then take only the first three letters of each string:
x = c("Apple", "Tears", "Romkom")str_sub(x, 1, 3)
Output:
[1] "App" "Tea" "Rom"
For the next demonstrations, I will use a dataset called the flight dataset that is a part of the nycflights13 library.
library(nycflights13)
The library is imported. Now, you are ready to use the flight dataset. The flight dataset is big. It is a big dataset. So, it is not possible to show a screenshot here. Here are the columns of the dataset:
names(flights)
Output:
[1] "year" "month" "day" "dep_time" [5] "sched_dep_time" "dep_delay" "arr_time" "sched_arr_time"[9] "arr_delay" "carrier" "flight" "tailnum" [13] "origin" "dest" "air_time" "distance" [17] "hour" "minute" "time_hour"
I will start with the ‘unite’ function that combines two columns together. This code block below unites the flight and carrier columns and make a new column called ‘flight_carr’:
flights %>% unite_(.,"flight_carr", c("flight", "carrier"))
Here is the part of the dataset that shows the new flight_carr column:
Factor function is very useful when we have categorical data and we need to use them as levels. For visualizations and for machine learning, it is necessary to use the factor function for categorical data to store them as levels.
Here I am factorizing the carrier column and printing the unique carriers:
carr = factor(flights$carrier)levels(carr)
Output:
[1] "9E" "AA" "AS" "B6" "DL" "EV" "F9" "FL" "HA" "MQ" "OO" "UA" "US"[14] "VX" "WN" "YV"
Let’s see the number count of each carrier:
fct_count(carr)
The next one is the map_dbl function from the purr package that takes a statistical function and returns the result. Here I will take the ‘distance’ and ‘sched_arr_time’ columns and find the ‘mean’ of both of them:
map_dbl(flights[, c("distance", "sched_arr_time")], ~mean(.x))
Output:
distance sched_arr_time 1039.913 1536.380
GGPLOT2 is a huge visualization library that comes with tidyverse package as well. Here is an example:
ggplot(data = flights) + aes(x = distance) + geom_density(adjust = 1, fill = "#0c4c8a") + theme_minimal()
I have a detailed tutorial on ggplot2 where you will find a collection of visualization techniques:
towardsdatascience.com
Let’s see some functions of lubridate package:
dates = c("January 18, 2020", "May 19, 2020", "July 20, 2020")mdy(dates)
Output:
[1] "2020-01-18" "2020-05-19" "2020-07-20"
Hour-minutes-seconds data:
x = c("11:03:07", "09:35:20", "09:18:32")hms(x)
Output:
[1] "11H 3M 7S" "9H 35M 20S" "9H 18M 32S"
Let’s go back to our flights' dataset. There is the year, month, and day data in the flights' dataset. We can make a date column using that and find the number of flights on each date and the mean distance.
flights %>% group_by(date = make_date(year, month, day)) %>% summarise(number_of_flights = n(), mean_distance = mean(distance, na.rm = TRUE))
How to take a subset of a DataFrame?
This code block takes a sample of 15 rows of data from the flights' dataset.
flights %>% slice_sample(n = 15)
The following code block takes a sample of 15% data from the flights' dataset:
flights %>% slice_sample(prop = 0.15)
Selecting specific columns from a large dataset
Here I am taking origin, dest, carrier, and flight columns from the flight dataset:
flights %>% select(origin, dest, carrier, flight)
What if from this big flights dataset I want most of the columns except time_hour and tailnum columns.
select(flights, -time_hour, -tailnum)
This code block will select all the columns of the flights' dataset except time_hour and tailnum columns.
Selecting the columns using the portion of the column names can be helpful as well.
The following line of code selects all the columns that start with “air_”:
flights %>% select(starts_with("air_"))
There is only one column that starts with “air_”.
These are the columns that end with “delay”:
flights %>% select(ends_with("delay"))
The following columns contain the part “dep” in them.
flights %>% select(contains("dep"))
How to filter the rows based on specific conditions?
Keeping the rows of data where ‘dest’ starts with “FL” and filtering out the rest of the data:
flights %>% filter(dest %>% str_detect("^FL"))
Here is the part of the output data:
Look at the ‘dest’ column above. All the values start with ‘FL’.
Here is another example of a filter function. Keeping the rows where month = 2 and filtering the rest.
filter(flights, month == 2)
This line of code will return the dataset where the month value is 2.
Using filter and select both in the same line of code
Selecting the columns origin, dest, distance, and arr_time where distance value is greater than 650:
select(filter(flights, distance > 650), origin, dest, distance, arr_time)
The same thing can be done using piping as well:
flights %>% filter(distance > 650) %>% select(origin, dest, distance, arr_time)
In the following example, I am selecting the flight and distance from the flights' dataset and taking the average distance where the flight number is 1545.
flights %>% select(flight, distance) %>% filter(flight == 1545) %>% summarise(avg_dist = mean(distance))
Creating New Columns Using the Existing Columns
I am creating two new columns arr_time_new and arr_time_old adding and subtracting 20 with the arr_time column using mutate operation. Before that, I am using the filter to remove the null values.
flights %>% filter(!is.na(arr_time)) %>% mutate(arr_time_new = arr_time + 20, arr_time_old = arr_time -20)
One last example of mutating. Here we will define a long-distance flight as the distance greater than 1000 and count how many flights are long-distance as per this definition.
flights %>% mutate(long_distance = (distance >= 1000)) %>% count(long_distance)
Las Vegas arrival delay and Seattle arrival on time count:
flights %>% mutate(dest = case_when( (dest == 'LAS') & arr_delay > 20 ~ "Las Vegas arriavl - Delayes", (dest == "SEA") & arr_delay <= 20 ~ "Seattle arrival - On time" )) %>% count(dest)
Replacing the names and count
The origins are represented as EWR, LGA, and JFK. We will replace them with their full name and count the number of flights and present them in sorted order:
flights %>% mutate(origin = str_replace_all(origin, c( "^EWR$" = "Newark International", "^LGA$" = "LaGuaria Airport", "^JFK$" = "John F. Kennedy International" ))) %>% count(origin)
Summarizing Data Using Group By Function
I want to know the average distance of all the flights each month. In this case, I will use the group_by function on the month column and find the mean distance using summarise on distance column:
flights %>% group_by(month)%>% summarize(mean_distance = mean(distance, na.rm = TRUE))
Group by function can be used on several variables and more than summarisation function can be used as well.
Here is an example. Another function called ‘arrange’ is also used here to get the dataset sorted by mean distance.
flights %>% filter(!is.na(distance))%>% group_by(year, month) %>% summarize(mean_distance = mean(distance), min_distance = min(distance)) %>% arrange(mean_distance)
Look, the dataset is arranged according to mean distance in ascending order.
Count Function
Let’s count the flight by flight number:
flights %>% count(flight)
Counting the number of flights of each origin and sorting them by the number of flights:
flights %>% count(origin, sort = TRUE)
Let’s see how many flights are there for each origin-destination combination:
flights %>% count(origin, dest)
Making a flight path column that shows origin -> destination combination and count the flights of each flight path:
flights %>% count(flight_path = str_c(origin, "->", dest), sort = TRUE)
Spread Function
To demonstrate the spread function, let’s prepare something first. I am making the mean dep_delay for each origin-destination combination:
flg = flights %>% filter(!is.na(dep_delay)) %>% group_by(origin, dest) %>% summarize(mean_dep_delay = mean(dep_delay))flg
Here is the use of spread where the key is the origin and value is the mean_dep_delay:
flg %>% spread(key = origin, value=mean_dep_delay)
Look origin is spread. There are three origins in this dataset and they became the columns of this spread dataset now. For each destination mean dep_delay from each origin is shown here.
But the problem is there are some null values in this output dataset. We can fill them up with zeros using this code:
flights_spread = flg %>% spread(origin, mean_dep_delay, fill=0)
Please feel free to run this code yourself and see the result.
Gather Function
Using the gather function I will gather the values from the values of mean_dep_delay of the columns ‘EWR’ to the column ‘LGA’:
flights_spread %>% gather(key = "origin", value = "mean_dep_delay", EWR:LGA)
That’s all in this article!
There is so much more that can be done with the tidyverse package. I tried to give an overview that touches quite a lot of things in different areas. Hope you will use this to do some interesting work yourself.
Feel free to follow me on Twitter and check out my new YouTube channel | [
{
"code": null,
"e": 618,
"s": 172,
"text": "The ‘tidyverse’ package in R is a very useful tool for data analysis in R as it covers almost everything you need to analyze a dataset. It is a combination of several big libraries that makes it a huge library to learn. In his article, I will try to provide a good overview of the tidyverse library that gives enough resources to perform a data analysis task well and also a great base for further learning. It can also be used as a cheat sheet."
},
{
"code": null,
"e": 864,
"s": 618,
"text": "If one does not have years of experience, it can be useful to have a list of operations or data analysis ideas on a page in front of you. So, I tried to compile quite a good amount of commonly used operations on this page to help myself and you."
},
{
"code": null,
"e": 944,
"s": 864,
"text": "The everyday data analysis packages that are included in tidyverse package are:"
},
{
"code": null,
"e": 952,
"s": 944,
"text": "ggplot2"
},
{
"code": null,
"e": 958,
"s": 952,
"text": "dplyr"
},
{
"code": null,
"e": 964,
"s": 958,
"text": "tidyr"
},
{
"code": null,
"e": 970,
"s": 964,
"text": "readr"
},
{
"code": null,
"e": 975,
"s": 970,
"text": "purr"
},
{
"code": null,
"e": 982,
"s": 975,
"text": "tibble"
},
{
"code": null,
"e": 990,
"s": 982,
"text": "stringr"
},
{
"code": null,
"e": 998,
"s": 990,
"text": "forcats"
},
{
"code": null,
"e": 1207,
"s": 998,
"text": "This article touches all of these packages except tibble. If you do not know what tibble is, it is also a kind of DataFrame. I am not going on details here. I used simple data frames for all the example here."
},
{
"code": null,
"e": 1293,
"s": 1207,
"text": "I will start with some simple things and slowly move towards some more complex tasks."
},
{
"code": null,
"e": 1306,
"s": 1293,
"text": "Let’s start!"
},
{
"code": null,
"e": 1342,
"s": 1306,
"text": "First import the tidyverse library."
},
{
"code": null,
"e": 1361,
"s": 1342,
"text": "library(tidyverse)"
},
{
"code": null,
"e": 1493,
"s": 1361,
"text": "I will start with some simple functions of stringr library which are pretty self-explanatory. So, I will not explain them too much."
},
{
"code": null,
"e": 1528,
"s": 1493,
"text": "Converting a string to lower case:"
},
{
"code": null,
"e": 1569,
"s": 1528,
"text": "x = \"Happy New Year 2022\"str_to_lower(x)"
},
{
"code": null,
"e": 1577,
"s": 1569,
"text": "Output:"
},
{
"code": null,
"e": 1603,
"s": 1577,
"text": "[1] \"happy new year 2022\""
},
{
"code": null,
"e": 1638,
"s": 1603,
"text": "Converting a string to upper case:"
},
{
"code": null,
"e": 1654,
"s": 1638,
"text": "str_to_upper(x)"
},
{
"code": null,
"e": 1662,
"s": 1654,
"text": "Output:"
},
{
"code": null,
"e": 1688,
"s": 1662,
"text": "[1] \"HAPPY NEW YEAR 2022\""
},
{
"code": null,
"e": 1722,
"s": 1688,
"text": "Combining several strings to one:"
},
{
"code": null,
"e": 1759,
"s": 1722,
"text": "str_c(\"I \", \"am \", \"very \", \"happy\")"
},
{
"code": null,
"e": 1767,
"s": 1759,
"text": "Output:"
},
{
"code": null,
"e": 1789,
"s": 1767,
"text": "[1] \"I am very happy\""
},
{
"code": null,
"e": 1827,
"s": 1789,
"text": "Taking a subset of a list of strings:"
},
{
"code": null,
"e": 1921,
"s": 1827,
"text": "Here I will make a list of strings and then take only the first three letters of each string:"
},
{
"code": null,
"e": 1971,
"s": 1921,
"text": "x = c(\"Apple\", \"Tears\", \"Romkom\")str_sub(x, 1, 3)"
},
{
"code": null,
"e": 1979,
"s": 1971,
"text": "Output:"
},
{
"code": null,
"e": 2001,
"s": 1979,
"text": "[1] \"App\" \"Tea\" \"Rom\""
},
{
"code": null,
"e": 2121,
"s": 2001,
"text": "For the next demonstrations, I will use a dataset called the flight dataset that is a part of the nycflights13 library."
},
{
"code": null,
"e": 2143,
"s": 2121,
"text": "library(nycflights13)"
},
{
"code": null,
"e": 2349,
"s": 2143,
"text": "The library is imported. Now, you are ready to use the flight dataset. The flight dataset is big. It is a big dataset. So, it is not possible to show a screenshot here. Here are the columns of the dataset:"
},
{
"code": null,
"e": 2364,
"s": 2349,
"text": "names(flights)"
},
{
"code": null,
"e": 2372,
"s": 2364,
"text": "Output:"
},
{
"code": null,
"e": 2709,
"s": 2372,
"text": "[1] \"year\" \"month\" \"day\" \"dep_time\" [5] \"sched_dep_time\" \"dep_delay\" \"arr_time\" \"sched_arr_time\"[9] \"arr_delay\" \"carrier\" \"flight\" \"tailnum\" [13] \"origin\" \"dest\" \"air_time\" \"distance\" [17] \"hour\" \"minute\" \"time_hour\""
},
{
"code": null,
"e": 2888,
"s": 2709,
"text": "I will start with the ‘unite’ function that combines two columns together. This code block below unites the flight and carrier columns and make a new column called ‘flight_carr’:"
},
{
"code": null,
"e": 2949,
"s": 2888,
"text": "flights %>% unite_(.,\"flight_carr\", c(\"flight\", \"carrier\"))"
},
{
"code": null,
"e": 3020,
"s": 2949,
"text": "Here is the part of the dataset that shows the new flight_carr column:"
},
{
"code": null,
"e": 3250,
"s": 3020,
"text": "Factor function is very useful when we have categorical data and we need to use them as levels. For visualizations and for machine learning, it is necessary to use the factor function for categorical data to store them as levels."
},
{
"code": null,
"e": 3325,
"s": 3250,
"text": "Here I am factorizing the carrier column and printing the unique carriers:"
},
{
"code": null,
"e": 3368,
"s": 3325,
"text": "carr = factor(flights$carrier)levels(carr)"
},
{
"code": null,
"e": 3376,
"s": 3368,
"text": "Output:"
},
{
"code": null,
"e": 3464,
"s": 3376,
"text": "[1] \"9E\" \"AA\" \"AS\" \"B6\" \"DL\" \"EV\" \"F9\" \"FL\" \"HA\" \"MQ\" \"OO\" \"UA\" \"US\"[14] \"VX\" \"WN\" \"YV\""
},
{
"code": null,
"e": 3508,
"s": 3464,
"text": "Let’s see the number count of each carrier:"
},
{
"code": null,
"e": 3524,
"s": 3508,
"text": "fct_count(carr)"
},
{
"code": null,
"e": 3739,
"s": 3524,
"text": "The next one is the map_dbl function from the purr package that takes a statistical function and returns the result. Here I will take the ‘distance’ and ‘sched_arr_time’ columns and find the ‘mean’ of both of them:"
},
{
"code": null,
"e": 3802,
"s": 3739,
"text": "map_dbl(flights[, c(\"distance\", \"sched_arr_time\")], ~mean(.x))"
},
{
"code": null,
"e": 3810,
"s": 3802,
"text": "Output:"
},
{
"code": null,
"e": 3858,
"s": 3810,
"text": "distance sched_arr_time 1039.913 1536.380"
},
{
"code": null,
"e": 3961,
"s": 3858,
"text": "GGPLOT2 is a huge visualization library that comes with tidyverse package as well. Here is an example:"
},
{
"code": null,
"e": 4073,
"s": 3961,
"text": "ggplot(data = flights) + aes(x = distance) + geom_density(adjust = 1, fill = \"#0c4c8a\") + theme_minimal()"
},
{
"code": null,
"e": 4173,
"s": 4073,
"text": "I have a detailed tutorial on ggplot2 where you will find a collection of visualization techniques:"
},
{
"code": null,
"e": 4196,
"s": 4173,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 4243,
"s": 4196,
"text": "Let’s see some functions of lubridate package:"
},
{
"code": null,
"e": 4316,
"s": 4243,
"text": "dates = c(\"January 18, 2020\", \"May 19, 2020\", \"July 20, 2020\")mdy(dates)"
},
{
"code": null,
"e": 4324,
"s": 4316,
"text": "Output:"
},
{
"code": null,
"e": 4367,
"s": 4324,
"text": "[1] \"2020-01-18\" \"2020-05-19\" \"2020-07-20\""
},
{
"code": null,
"e": 4394,
"s": 4367,
"text": "Hour-minutes-seconds data:"
},
{
"code": null,
"e": 4442,
"s": 4394,
"text": "x = c(\"11:03:07\", \"09:35:20\", \"09:18:32\")hms(x)"
},
{
"code": null,
"e": 4450,
"s": 4442,
"text": "Output:"
},
{
"code": null,
"e": 4493,
"s": 4450,
"text": "[1] \"11H 3M 7S\" \"9H 35M 20S\" \"9H 18M 32S\""
},
{
"code": null,
"e": 4700,
"s": 4493,
"text": "Let’s go back to our flights' dataset. There is the year, month, and day data in the flights' dataset. We can make a date column using that and find the number of flights on each date and the mean distance."
},
{
"code": null,
"e": 4845,
"s": 4700,
"text": "flights %>% group_by(date = make_date(year, month, day)) %>% summarise(number_of_flights = n(), mean_distance = mean(distance, na.rm = TRUE))"
},
{
"code": null,
"e": 4882,
"s": 4845,
"text": "How to take a subset of a DataFrame?"
},
{
"code": null,
"e": 4959,
"s": 4882,
"text": "This code block takes a sample of 15 rows of data from the flights' dataset."
},
{
"code": null,
"e": 4993,
"s": 4959,
"text": "flights %>% slice_sample(n = 15)"
},
{
"code": null,
"e": 5072,
"s": 4993,
"text": "The following code block takes a sample of 15% data from the flights' dataset:"
},
{
"code": null,
"e": 5111,
"s": 5072,
"text": "flights %>% slice_sample(prop = 0.15)"
},
{
"code": null,
"e": 5159,
"s": 5111,
"text": "Selecting specific columns from a large dataset"
},
{
"code": null,
"e": 5243,
"s": 5159,
"text": "Here I am taking origin, dest, carrier, and flight columns from the flight dataset:"
},
{
"code": null,
"e": 5294,
"s": 5243,
"text": "flights %>% select(origin, dest, carrier, flight)"
},
{
"code": null,
"e": 5397,
"s": 5294,
"text": "What if from this big flights dataset I want most of the columns except time_hour and tailnum columns."
},
{
"code": null,
"e": 5435,
"s": 5397,
"text": "select(flights, -time_hour, -tailnum)"
},
{
"code": null,
"e": 5541,
"s": 5435,
"text": "This code block will select all the columns of the flights' dataset except time_hour and tailnum columns."
},
{
"code": null,
"e": 5625,
"s": 5541,
"text": "Selecting the columns using the portion of the column names can be helpful as well."
},
{
"code": null,
"e": 5700,
"s": 5625,
"text": "The following line of code selects all the columns that start with “air_”:"
},
{
"code": null,
"e": 5741,
"s": 5700,
"text": "flights %>% select(starts_with(\"air_\"))"
},
{
"code": null,
"e": 5791,
"s": 5741,
"text": "There is only one column that starts with “air_”."
},
{
"code": null,
"e": 5836,
"s": 5791,
"text": "These are the columns that end with “delay”:"
},
{
"code": null,
"e": 5876,
"s": 5836,
"text": "flights %>% select(ends_with(\"delay\"))"
},
{
"code": null,
"e": 5930,
"s": 5876,
"text": "The following columns contain the part “dep” in them."
},
{
"code": null,
"e": 5967,
"s": 5930,
"text": "flights %>% select(contains(\"dep\"))"
},
{
"code": null,
"e": 6020,
"s": 5967,
"text": "How to filter the rows based on specific conditions?"
},
{
"code": null,
"e": 6115,
"s": 6020,
"text": "Keeping the rows of data where ‘dest’ starts with “FL” and filtering out the rest of the data:"
},
{
"code": null,
"e": 6163,
"s": 6115,
"text": "flights %>% filter(dest %>% str_detect(\"^FL\"))"
},
{
"code": null,
"e": 6200,
"s": 6163,
"text": "Here is the part of the output data:"
},
{
"code": null,
"e": 6265,
"s": 6200,
"text": "Look at the ‘dest’ column above. All the values start with ‘FL’."
},
{
"code": null,
"e": 6368,
"s": 6265,
"text": "Here is another example of a filter function. Keeping the rows where month = 2 and filtering the rest."
},
{
"code": null,
"e": 6396,
"s": 6368,
"text": "filter(flights, month == 2)"
},
{
"code": null,
"e": 6466,
"s": 6396,
"text": "This line of code will return the dataset where the month value is 2."
},
{
"code": null,
"e": 6520,
"s": 6466,
"text": "Using filter and select both in the same line of code"
},
{
"code": null,
"e": 6621,
"s": 6520,
"text": "Selecting the columns origin, dest, distance, and arr_time where distance value is greater than 650:"
},
{
"code": null,
"e": 6695,
"s": 6621,
"text": "select(filter(flights, distance > 650), origin, dest, distance, arr_time)"
},
{
"code": null,
"e": 6744,
"s": 6695,
"text": "The same thing can be done using piping as well:"
},
{
"code": null,
"e": 6826,
"s": 6744,
"text": "flights %>% filter(distance > 650) %>% select(origin, dest, distance, arr_time)"
},
{
"code": null,
"e": 6982,
"s": 6826,
"text": "In the following example, I am selecting the flight and distance from the flights' dataset and taking the average distance where the flight number is 1545."
},
{
"code": null,
"e": 7090,
"s": 6982,
"text": "flights %>% select(flight, distance) %>% filter(flight == 1545) %>% summarise(avg_dist = mean(distance))"
},
{
"code": null,
"e": 7138,
"s": 7090,
"text": "Creating New Columns Using the Existing Columns"
},
{
"code": null,
"e": 7335,
"s": 7138,
"text": "I am creating two new columns arr_time_new and arr_time_old adding and subtracting 20 with the arr_time column using mutate operation. Before that, I am using the filter to remove the null values."
},
{
"code": null,
"e": 7452,
"s": 7335,
"text": "flights %>% filter(!is.na(arr_time)) %>% mutate(arr_time_new = arr_time + 20, arr_time_old = arr_time -20)"
},
{
"code": null,
"e": 7628,
"s": 7452,
"text": "One last example of mutating. Here we will define a long-distance flight as the distance greater than 1000 and count how many flights are long-distance as per this definition."
},
{
"code": null,
"e": 7710,
"s": 7628,
"text": "flights %>% mutate(long_distance = (distance >= 1000)) %>% count(long_distance)"
},
{
"code": null,
"e": 7769,
"s": 7710,
"text": "Las Vegas arrival delay and Seattle arrival on time count:"
},
{
"code": null,
"e": 7964,
"s": 7769,
"text": "flights %>% mutate(dest = case_when( (dest == 'LAS') & arr_delay > 20 ~ \"Las Vegas arriavl - Delayes\", (dest == \"SEA\") & arr_delay <= 20 ~ \"Seattle arrival - On time\" )) %>% count(dest)"
},
{
"code": null,
"e": 7994,
"s": 7964,
"text": "Replacing the names and count"
},
{
"code": null,
"e": 8152,
"s": 7994,
"text": "The origins are represented as EWR, LGA, and JFK. We will replace them with their full name and count the number of flights and present them in sorted order:"
},
{
"code": null,
"e": 8347,
"s": 8152,
"text": "flights %>% mutate(origin = str_replace_all(origin, c( \"^EWR$\" = \"Newark International\", \"^LGA$\" = \"LaGuaria Airport\", \"^JFK$\" = \"John F. Kennedy International\" ))) %>% count(origin)"
},
{
"code": null,
"e": 8388,
"s": 8347,
"text": "Summarizing Data Using Group By Function"
},
{
"code": null,
"e": 8585,
"s": 8388,
"text": "I want to know the average distance of all the flights each month. In this case, I will use the group_by function on the month column and find the mean distance using summarise on distance column:"
},
{
"code": null,
"e": 8674,
"s": 8585,
"text": "flights %>% group_by(month)%>% summarize(mean_distance = mean(distance, na.rm = TRUE))"
},
{
"code": null,
"e": 8783,
"s": 8674,
"text": "Group by function can be used on several variables and more than summarisation function can be used as well."
},
{
"code": null,
"e": 8899,
"s": 8783,
"text": "Here is an example. Another function called ‘arrange’ is also used here to get the dataset sorted by mean distance."
},
{
"code": null,
"e": 9079,
"s": 8899,
"text": "flights %>% filter(!is.na(distance))%>% group_by(year, month) %>% summarize(mean_distance = mean(distance), min_distance = min(distance)) %>% arrange(mean_distance)"
},
{
"code": null,
"e": 9156,
"s": 9079,
"text": "Look, the dataset is arranged according to mean distance in ascending order."
},
{
"code": null,
"e": 9171,
"s": 9156,
"text": "Count Function"
},
{
"code": null,
"e": 9212,
"s": 9171,
"text": "Let’s count the flight by flight number:"
},
{
"code": null,
"e": 9239,
"s": 9212,
"text": "flights %>% count(flight)"
},
{
"code": null,
"e": 9328,
"s": 9239,
"text": "Counting the number of flights of each origin and sorting them by the number of flights:"
},
{
"code": null,
"e": 9368,
"s": 9328,
"text": "flights %>% count(origin, sort = TRUE)"
},
{
"code": null,
"e": 9446,
"s": 9368,
"text": "Let’s see how many flights are there for each origin-destination combination:"
},
{
"code": null,
"e": 9479,
"s": 9446,
"text": "flights %>% count(origin, dest)"
},
{
"code": null,
"e": 9595,
"s": 9479,
"text": "Making a flight path column that shows origin -> destination combination and count the flights of each flight path:"
},
{
"code": null,
"e": 9668,
"s": 9595,
"text": "flights %>% count(flight_path = str_c(origin, \"->\", dest), sort = TRUE)"
},
{
"code": null,
"e": 9684,
"s": 9668,
"text": "Spread Function"
},
{
"code": null,
"e": 9823,
"s": 9684,
"text": "To demonstrate the spread function, let’s prepare something first. I am making the mean dep_delay for each origin-destination combination:"
},
{
"code": null,
"e": 9948,
"s": 9823,
"text": "flg = flights %>% filter(!is.na(dep_delay)) %>% group_by(origin, dest) %>% summarize(mean_dep_delay = mean(dep_delay))flg"
},
{
"code": null,
"e": 10035,
"s": 9948,
"text": "Here is the use of spread where the key is the origin and value is the mean_dep_delay:"
},
{
"code": null,
"e": 10087,
"s": 10035,
"text": "flg %>% spread(key = origin, value=mean_dep_delay)"
},
{
"code": null,
"e": 10274,
"s": 10087,
"text": "Look origin is spread. There are three origins in this dataset and they became the columns of this spread dataset now. For each destination mean dep_delay from each origin is shown here."
},
{
"code": null,
"e": 10392,
"s": 10274,
"text": "But the problem is there are some null values in this output dataset. We can fill them up with zeros using this code:"
},
{
"code": null,
"e": 10457,
"s": 10392,
"text": "flights_spread = flg %>% spread(origin, mean_dep_delay, fill=0)"
},
{
"code": null,
"e": 10520,
"s": 10457,
"text": "Please feel free to run this code yourself and see the result."
},
{
"code": null,
"e": 10536,
"s": 10520,
"text": "Gather Function"
},
{
"code": null,
"e": 10663,
"s": 10536,
"text": "Using the gather function I will gather the values from the values of mean_dep_delay of the columns ‘EWR’ to the column ‘LGA’:"
},
{
"code": null,
"e": 10741,
"s": 10663,
"text": "flights_spread %>% gather(key = \"origin\", value = \"mean_dep_delay\", EWR:LGA)"
},
{
"code": null,
"e": 10769,
"s": 10741,
"text": "That’s all in this article!"
},
{
"code": null,
"e": 10980,
"s": 10769,
"text": "There is so much more that can be done with the tidyverse package. I tried to give an overview that touches quite a lot of things in different areas. Hope you will use this to do some interesting work yourself."
}
]
|
Android - RSS Reader | RSS stands for Really Simple Syndication. RSS is an easy way to share your website updates and content with your users so that users might not have to visit your site daily for any kind of updates.
RSS is a document that is created by the website with .xml extension. You can easily parse this document and show it to the user in your application. An RSS document looks like this.
<rss version="2.0">
<channel>
<title>Sample RSS</title>
<link>http://www.google.com</link>
<description>World's best search engine</description>
</channel>
</rss>
An RSS document such as above has the following elements.
channel
This element is used to describe the RSS feed
title
Defines the title of the channel
link
Defines the hyper link to the channel
description
Describes the channel
Parsing an RSS document is more like parsing XML. So now lets see how to parse an XML document.
For this, We will create XMLPullParser object , but in order to create that we will first create XmlPullParserFactory object and then call its newPullParser() method to create XMLPullParser. Its syntax is given below −
private XmlPullParserFactory xmlFactoryObject = XmlPullParserFactory.newInstance();
private XmlPullParser myparser = xmlFactoryObject.newPullParser();
The next step involves specifying the file for XmlPullParser that contains XML. It could be a file or could be a Stream. In our case it is a stream.Its syntax is given below −
myparser.setInput(stream, null);
The last step is to parse the XML. An XML file consist of events , Name , Text , AttributesValue e.t.c. So XMLPullParser has a separate function for parsing each of the component of XML file. Its syntax is given below −
int event = myParser.getEventType();
while (event != XmlPullParser.END_DOCUMENT) {
String name=myParser.getName();
switch (event){
case XmlPullParser.START_TAG:
break;
case XmlPullParser.END_TAG:
if(name.equals("temperature")){
temperature = myParser.getAttributeValue(null,"value");
}
break;
}
event = myParser.next();
}
The method getEventType returns the type of event that happens. e.g: Document start, tag start e.t.c. The method getName returns the name of the tag and since we are only interested in temperature, so we just check in conditional statement that if we got a temperature tag, we call the method getAttributeValue to return us the value of temperature tag.
Apart from the these methods, there are other methods provided by this class for better parsing XML files. These methods are listed below −
getAttributeCount()
This method just Returns the number of attributes of the current start tag.
getAttributeName(int index)
This method returns the name of the attribute specified by the index value.
getColumnNumber()
This method returns the Returns the current column number, starting from 0.
getDepth()
This method returns Returns the current depth of the element.
getLineNumber()
Returns the current line number, starting from 1.
getNamespace()
This method returns the name space URI of the current element.
getPrefix()
This method returns the prefix of the current element.
getName()
This method returns the name of the tag.
getText()
This method returns the text for that particular element.
isWhitespace()
This method checks whether the current TEXT event contains only white space characters.
Here is an example demonstrating the use of XMLPullParser class. It creates a basic Parsing application that allows you to parse an RSS document present here at /android/sampleXML.xml and then show the result.
To experiment with this example, you can run this on an actual device or in an emulator.
Following is the content of the modified main activity file src/MainActivity.java.
package com.example.sairamkrishna.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
EditText title,link,description;
Button b1,b2;
private String finalUrl="http://tutorialspoint.com/android/sampleXML.xml";
private HandleXML obj;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
title = (EditText) findViewById(R.id.editText);
link = (EditText) findViewById(R.id.editText2);
description = (EditText) findViewById(R.id.editText3);
b1=(Button)findViewById(R.id.button);
b2=(Button)findViewById(R.id.button2);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
obj = new HandleXML(finalUrl);
obj.fetchXML();
while(obj.parsingComplete);
title.setText(obj.getTitle());
link.setText(obj.getLink());
description.setText(obj.getDescription());
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent in=new Intent(MainActivity.this,second.class);
startActivity(in);
}
});
}
}
Following is the content of the java file src/HandleXML.java.
package com.example.rssreader;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import android.util.Log;
public class HandleXML {
private String title = "title";
private String link = "link";
private String description = "description";
private String urlString = null;
private XmlPullParserFactory xmlFactoryObject;
public volatile boolean parsingComplete = true;
public HandleXML(String url){
this.urlString = url;
}
public String getTitle(){
return title;
}
public String getLink(){
return link;
}
public String getDescription(){
return description;
}
public void parseXMLAndStoreIt(XmlPullParser myParser) {
int event;
String text=null;
try {
event = myParser.getEventType();
while (event != XmlPullParser.END_DOCUMENT) {
String name=myParser.getName();
switch (event){
case XmlPullParser.START_TAG:
break;
case XmlPullParser.TEXT:
text = myParser.getText();
break;
case XmlPullParser.END_TAG:
if(name.equals("title")){
title = text;
}
else if(name.equals("link")){
link = text;
}
else if(name.equals("description")){
description = text;
}
else{
}
break;
}
event = myParser.next();
}
parsingComplete = false;
}
catch (Exception e) {
e.printStackTrace();
}
}
public void fetchXML(){
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
InputStream stream = conn.getInputStream();
xmlFactoryObject = XmlPullParserFactory.newInstance();
XmlPullParser myparser = xmlFactoryObject.newPullParser();
myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
myparser.setInput(stream, null);
parseXMLAndStoreIt(myparser);
stream.close();
}
catch (Exception e) {
}
}
});
thread.start();
}
}
Create a file and named as second.java file under directory java/second.java
package com.example.sairamkrishna.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
public class second extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
WebView w1=(WebView)findViewById(R.id.webView);
w1.loadUrl("http://tutorialspoint.com/android/sampleXML.xml");
}
}
Create a xml file at res/layout/second_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/webView"
android:layout_gravity="center_horizontal" />
</LinearLayout>
Modify the content of res/layout/activity_main.xml to the following −
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:transitionGroup="true">
<TextView android:text="RSS example" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:theme="@style/Base.TextAppearance.AppCompat" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_below="@+id/imageView"
android:hint="Tittle"
android:textColorHint="#ff69ff0e"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText2"
android:layout_below="@+id/editText"
android:layout_alignLeft="@+id/editText"
android:layout_alignStart="@+id/editText"
android:textColorHint="#ff21ff11"
android:hint="Link"
android:layout_alignRight="@+id/editText"
android:layout_alignEnd="@+id/editText" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText3"
android:layout_below="@+id/editText2"
android:layout_alignLeft="@+id/editText2"
android:layout_alignStart="@+id/editText2"
android:hint="Description"
android:textColorHint="#ff33ff20"
android:layout_alignRight="@+id/editText2"
android:layout_alignEnd="@+id/editText2" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fetch"
android:id="@+id/button"
android:layout_below="@+id/editText3"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="@+id/imageView"
android:layout_toStartOf="@+id/imageView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result"
android:id="@+id/button2"
android:layout_alignTop="@+id/button"
android:layout_alignRight="@+id/editText3"
android:layout_alignEnd="@+id/editText3" />
</RelativeLayout>
Modify the res/values/string.xml to the following
<resources>
<string name="app_name">My Application</string>
</resources>
This is the default AndroidManifest.xml.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".second"></activity>
</application>
</manifest>
Let's try to run your application. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −
Just press the Fetch Feed button to fetch RSS feed. After pressing, following screen would appear which would show the RSS data.
Just press the result button to see XML, which is placed at http://tutorialspoint.com/android/sampleXML.xml
46 Lectures
7.5 hours
Aditya Dua
32 Lectures
3.5 hours
Sharad Kumar
9 Lectures
1 hours
Abhilash Nelson
14 Lectures
1.5 hours
Abhilash Nelson
15 Lectures
1.5 hours
Abhilash Nelson
10 Lectures
1 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3805,
"s": 3607,
"text": "RSS stands for Really Simple Syndication. RSS is an easy way to share your website updates and content with your users so that users might not have to visit your site daily for any kind of updates."
},
{
"code": null,
"e": 3988,
"s": 3805,
"text": "RSS is a document that is created by the website with .xml extension. You can easily parse this document and show it to the user in your application. An RSS document looks like this."
},
{
"code": null,
"e": 4175,
"s": 3988,
"text": "<rss version=\"2.0\">\n <channel>\n <title>Sample RSS</title>\n <link>http://www.google.com</link>\n <description>World's best search engine</description>\n </channel>\n</rss>"
},
{
"code": null,
"e": 4233,
"s": 4175,
"text": "An RSS document such as above has the following elements."
},
{
"code": null,
"e": 4241,
"s": 4233,
"text": "channel"
},
{
"code": null,
"e": 4287,
"s": 4241,
"text": "This element is used to describe the RSS feed"
},
{
"code": null,
"e": 4293,
"s": 4287,
"text": "title"
},
{
"code": null,
"e": 4327,
"s": 4293,
"text": "Defines the title of the channel "
},
{
"code": null,
"e": 4332,
"s": 4327,
"text": "link"
},
{
"code": null,
"e": 4370,
"s": 4332,
"text": "Defines the hyper link to the channel"
},
{
"code": null,
"e": 4382,
"s": 4370,
"text": "description"
},
{
"code": null,
"e": 4404,
"s": 4382,
"text": "Describes the channel"
},
{
"code": null,
"e": 4500,
"s": 4404,
"text": "Parsing an RSS document is more like parsing XML. So now lets see how to parse an XML document."
},
{
"code": null,
"e": 4719,
"s": 4500,
"text": "For this, We will create XMLPullParser object , but in order to create that we will first create XmlPullParserFactory object and then call its newPullParser() method to create XMLPullParser. Its syntax is given below −"
},
{
"code": null,
"e": 4871,
"s": 4719,
"text": "private XmlPullParserFactory xmlFactoryObject = XmlPullParserFactory.newInstance();\nprivate XmlPullParser myparser = xmlFactoryObject.newPullParser();\n"
},
{
"code": null,
"e": 5047,
"s": 4871,
"text": "The next step involves specifying the file for XmlPullParser that contains XML. It could be a file or could be a Stream. In our case it is a stream.Its syntax is given below −"
},
{
"code": null,
"e": 5081,
"s": 5047,
"text": "myparser.setInput(stream, null);\n"
},
{
"code": null,
"e": 5301,
"s": 5081,
"text": "The last step is to parse the XML. An XML file consist of events , Name , Text , AttributesValue e.t.c. So XMLPullParser has a separate function for parsing each of the component of XML file. Its syntax is given below −"
},
{
"code": null,
"e": 5701,
"s": 5301,
"text": "int event = myParser.getEventType();\nwhile (event != XmlPullParser.END_DOCUMENT) {\n String name=myParser.getName();\n \n switch (event){\n case XmlPullParser.START_TAG:\n break;\n \n case XmlPullParser.END_TAG:\n if(name.equals(\"temperature\")){\n temperature = myParser.getAttributeValue(null,\"value\");\n }\n break;\n }\t\t \n event = myParser.next(); \t\t\t\t\t\n}"
},
{
"code": null,
"e": 6055,
"s": 5701,
"text": "The method getEventType returns the type of event that happens. e.g: Document start, tag start e.t.c. The method getName returns the name of the tag and since we are only interested in temperature, so we just check in conditional statement that if we got a temperature tag, we call the method getAttributeValue to return us the value of temperature tag."
},
{
"code": null,
"e": 6195,
"s": 6055,
"text": "Apart from the these methods, there are other methods provided by this class for better parsing XML files. These methods are listed below −"
},
{
"code": null,
"e": 6215,
"s": 6195,
"text": "getAttributeCount()"
},
{
"code": null,
"e": 6291,
"s": 6215,
"text": "This method just Returns the number of attributes of the current start tag."
},
{
"code": null,
"e": 6319,
"s": 6291,
"text": "getAttributeName(int index)"
},
{
"code": null,
"e": 6395,
"s": 6319,
"text": "This method returns the name of the attribute specified by the index value."
},
{
"code": null,
"e": 6413,
"s": 6395,
"text": "getColumnNumber()"
},
{
"code": null,
"e": 6489,
"s": 6413,
"text": "This method returns the Returns the current column number, starting from 0."
},
{
"code": null,
"e": 6500,
"s": 6489,
"text": "getDepth()"
},
{
"code": null,
"e": 6562,
"s": 6500,
"text": "This method returns Returns the current depth of the element."
},
{
"code": null,
"e": 6578,
"s": 6562,
"text": "getLineNumber()"
},
{
"code": null,
"e": 6628,
"s": 6578,
"text": "Returns the current line number, starting from 1."
},
{
"code": null,
"e": 6643,
"s": 6628,
"text": "getNamespace()"
},
{
"code": null,
"e": 6706,
"s": 6643,
"text": "This method returns the name space URI of the current element."
},
{
"code": null,
"e": 6718,
"s": 6706,
"text": "getPrefix()"
},
{
"code": null,
"e": 6773,
"s": 6718,
"text": "This method returns the prefix of the current element."
},
{
"code": null,
"e": 6783,
"s": 6773,
"text": "getName()"
},
{
"code": null,
"e": 6824,
"s": 6783,
"text": "This method returns the name of the tag."
},
{
"code": null,
"e": 6834,
"s": 6824,
"text": "getText()"
},
{
"code": null,
"e": 6892,
"s": 6834,
"text": "This method returns the text for that particular element."
},
{
"code": null,
"e": 6907,
"s": 6892,
"text": "isWhitespace()"
},
{
"code": null,
"e": 6995,
"s": 6907,
"text": "This method checks whether the current TEXT event contains only white space characters."
},
{
"code": null,
"e": 7205,
"s": 6995,
"text": "Here is an example demonstrating the use of XMLPullParser class. It creates a basic Parsing application that allows you to parse an RSS document present here at /android/sampleXML.xml and then show the result."
},
{
"code": null,
"e": 7294,
"s": 7205,
"text": "To experiment with this example, you can run this on an actual device or in an emulator."
},
{
"code": null,
"e": 7377,
"s": 7294,
"text": "Following is the content of the modified main activity file src/MainActivity.java."
},
{
"code": null,
"e": 8853,
"s": 7377,
"text": "package com.example.sairamkrishna.myapplication;\n\nimport android.app.Activity;\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.view.View;\n\nimport android.widget.Button;\nimport android.widget.EditText;\n\n\npublic class MainActivity extends Activity {\n EditText title,link,description;\n Button b1,b2;\n private String finalUrl=\"http://tutorialspoint.com/android/sampleXML.xml\";\n private HandleXML obj;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n title = (EditText) findViewById(R.id.editText);\n link = (EditText) findViewById(R.id.editText2);\n description = (EditText) findViewById(R.id.editText3);\n\n b1=(Button)findViewById(R.id.button);\n b2=(Button)findViewById(R.id.button2);\n b1.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n obj = new HandleXML(finalUrl);\n obj.fetchXML();\n\n while(obj.parsingComplete);\n title.setText(obj.getTitle());\n link.setText(obj.getLink());\n description.setText(obj.getDescription());\n }\n });\n\n b2.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Intent in=new Intent(MainActivity.this,second.class);\n startActivity(in);\n }\n });\n }\n\n}"
},
{
"code": null,
"e": 8915,
"s": 8853,
"text": "Following is the content of the java file src/HandleXML.java."
},
{
"code": null,
"e": 12046,
"s": 8915,
"text": "package com.example.rssreader;\n\nimport java.io.InputStream;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\n\nimport org.xmlpull.v1.XmlPullParser;\nimport org.xmlpull.v1.XmlPullParserFactory;\n\nimport android.util.Log;\n\npublic class HandleXML {\n private String title = \"title\";\n private String link = \"link\";\n private String description = \"description\";\n private String urlString = null;\n private XmlPullParserFactory xmlFactoryObject;\n public volatile boolean parsingComplete = true;\n \n public HandleXML(String url){\n this.urlString = url;\n }\n \n public String getTitle(){\n return title;\n }\n \n public String getLink(){\n return link;\n }\n \n public String getDescription(){\n return description;\n }\n \n public void parseXMLAndStoreIt(XmlPullParser myParser) {\n int event;\n String text=null;\n \n try {\n event = myParser.getEventType();\n \n while (event != XmlPullParser.END_DOCUMENT) {\n String name=myParser.getName();\n \n switch (event){\n case XmlPullParser.START_TAG:\n break;\n \n case XmlPullParser.TEXT:\n text = myParser.getText();\n break;\n \n case XmlPullParser.END_TAG:\n \n if(name.equals(\"title\")){\n title = text;\n }\n \n else if(name.equals(\"link\")){\n link = text;\n }\n \n else if(name.equals(\"description\")){\n description = text;\n }\n \n else{\n }\n \n break;\n }\n \n event = myParser.next(); \n }\n \n parsingComplete = false;\n }\n \n catch (Exception e) {\n e.printStackTrace();\n }\n }\n \n public void fetchXML(){\n Thread thread = new Thread(new Runnable(){\n @Override\n public void run() {\n \n try {\n URL url = new URL(urlString);\n HttpURLConnection conn = (HttpURLConnection) url.openConnection();\n \n conn.setReadTimeout(10000 /* milliseconds */);\n conn.setConnectTimeout(15000 /* milliseconds */);\n conn.setRequestMethod(\"GET\");\n conn.setDoInput(true);\n \n // Starts the query\n conn.connect();\n InputStream stream = conn.getInputStream();\n \n xmlFactoryObject = XmlPullParserFactory.newInstance();\n XmlPullParser myparser = xmlFactoryObject.newPullParser();\n \n myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);\n myparser.setInput(stream, null);\n \n parseXMLAndStoreIt(myparser);\n stream.close();\n }\n \n catch (Exception e) {\n }\n }\n });\n thread.start(); \n }\n}"
},
{
"code": null,
"e": 12123,
"s": 12046,
"text": "Create a file and named as second.java file under directory java/second.java"
},
{
"code": null,
"e": 12588,
"s": 12123,
"text": "package com.example.sairamkrishna.myapplication;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.webkit.WebView;\n\npublic class second extends Activity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.second_activity);\n WebView w1=(WebView)findViewById(R.id.webView);\n w1.loadUrl(\"http://tutorialspoint.com/android/sampleXML.xml\");\n }\n}"
},
{
"code": null,
"e": 12640,
"s": 12588,
"text": "Create a xml file at res/layout/second_activity.xml"
},
{
"code": null,
"e": 13064,
"s": 12640,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:orientation=\"vertical\" android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\">\n \n <WebView\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:id=\"@+id/webView\"\n android:layout_gravity=\"center_horizontal\" />\n</LinearLayout>"
},
{
"code": null,
"e": 13134,
"s": 13064,
"text": "Modify the content of res/layout/activity_main.xml to the following −"
},
{
"code": null,
"e": 16645,
"s": 13134,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" android:paddingLeft=\"@dimen/activity_horizontal_margin\"\n android:paddingRight=\"@dimen/activity_horizontal_margin\"\n android:paddingTop=\"@dimen/activity_vertical_margin\"\n android:paddingBottom=\"@dimen/activity_vertical_margin\"\n tools:context=\".MainActivity\"\n android:transitionGroup=\"true\">\n \n <TextView android:text=\"RSS example\" android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/textview\"\n android:textSize=\"35dp\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\" />\n \n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Tutorials point\"\n android:id=\"@+id/textView\"\n android:layout_below=\"@+id/textview\"\n android:layout_centerHorizontal=\"true\"\n android:textColor=\"#ff7aff24\"\n android:textSize=\"35dp\" />\n \n <ImageView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/imageView\"\n android:src=\"@drawable/abc\"\n android:layout_below=\"@+id/textView\"\n android:layout_centerHorizontal=\"true\"\n android:theme=\"@style/Base.TextAppearance.AppCompat\" />\n \n <EditText\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/editText\"\n android:layout_below=\"@+id/imageView\"\n android:hint=\"Tittle\"\n android:textColorHint=\"#ff69ff0e\"\n android:layout_alignParentRight=\"true\"\n android:layout_alignParentEnd=\"true\"\n android:layout_alignParentLeft=\"true\"\n android:layout_alignParentStart=\"true\" />\n \n <EditText\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/editText2\"\n android:layout_below=\"@+id/editText\"\n android:layout_alignLeft=\"@+id/editText\"\n android:layout_alignStart=\"@+id/editText\"\n android:textColorHint=\"#ff21ff11\"\n android:hint=\"Link\"\n android:layout_alignRight=\"@+id/editText\"\n android:layout_alignEnd=\"@+id/editText\" />\n \n <EditText\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/editText3\"\n android:layout_below=\"@+id/editText2\"\n android:layout_alignLeft=\"@+id/editText2\"\n android:layout_alignStart=\"@+id/editText2\"\n android:hint=\"Description\"\n android:textColorHint=\"#ff33ff20\"\n android:layout_alignRight=\"@+id/editText2\"\n android:layout_alignEnd=\"@+id/editText2\" />\n \n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Fetch\"\n android:id=\"@+id/button\"\n android:layout_below=\"@+id/editText3\"\n android:layout_alignParentLeft=\"true\"\n android:layout_alignParentStart=\"true\"\n android:layout_toLeftOf=\"@+id/imageView\"\n android:layout_toStartOf=\"@+id/imageView\" />\n \n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Result\"\n android:id=\"@+id/button2\"\n android:layout_alignTop=\"@+id/button\"\n android:layout_alignRight=\"@+id/editText3\"\n android:layout_alignEnd=\"@+id/editText3\" />\n\n</RelativeLayout>"
},
{
"code": null,
"e": 16695,
"s": 16645,
"text": "Modify the res/values/string.xml to the following"
},
{
"code": null,
"e": 16771,
"s": 16695,
"text": "<resources>\n <string name=\"app_name\">My Application</string>\n</resources>"
},
{
"code": null,
"e": 16812,
"s": 16771,
"text": "This is the default AndroidManifest.xml."
},
{
"code": null,
"e": 17630,
"s": 16812,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.sairamkrishna.myapplication\" >\n <uses-permission android:name=\"android.permission.INTERNET\"/>\n \n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:theme=\"@style/AppTheme\" >\n \n <activity\n android:name=\".MainActivity\"\n android:label=\"@string/app_name\" >\n \n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n \n </activity>\n \n <activity android:name=\".second\"></activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 18007,
"s": 17630,
"text": "Let's try to run your application. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −"
},
{
"code": null,
"e": 18136,
"s": 18007,
"text": "Just press the Fetch Feed button to fetch RSS feed. After pressing, following screen would appear which would show the RSS data."
},
{
"code": null,
"e": 18244,
"s": 18136,
"text": "Just press the result button to see XML, which is placed at http://tutorialspoint.com/android/sampleXML.xml"
},
{
"code": null,
"e": 18279,
"s": 18244,
"text": "\n 46 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 18291,
"s": 18279,
"text": " Aditya Dua"
},
{
"code": null,
"e": 18326,
"s": 18291,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 18340,
"s": 18326,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 18372,
"s": 18340,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 18389,
"s": 18372,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 18424,
"s": 18389,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 18441,
"s": 18424,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 18476,
"s": 18441,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 18493,
"s": 18476,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 18526,
"s": 18493,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 18543,
"s": 18526,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 18550,
"s": 18543,
"text": " Print"
},
{
"code": null,
"e": 18561,
"s": 18550,
"text": " Add Notes"
}
]
|
What to Log? From Python ETL Pipelines! | by Shiva Koreddi | Towards Data Science | As part of my work, I have been converting some of my ETL jobs developed on the traditional tool-based framework into a python framework and came across a few challenges. These few challenges are orchestration, code management, logging, version control, etc. For a few of them, there was not much effort required while developing them on a tool. But, in hand-written code like python ETL’s, these are quite a challenge! And this brings to one such challenge, our topic today!
Also instead of describing much on ‘how’, as there are many good articles already on a platform, our main focus today is ‘What’.
Glossary:
IntroductionETL SkeletonStructure of Log!!Sample ETL job with our log structure.Code Location.
Introduction
ETL Skeleton
Structure of Log!!
Sample ETL job with our log structure.
Code Location.
Introduction: When we design and develop ETL pipelines on tools we focus on components like sources, target objects, transformation logic, and a few support tasks to handle pipelines. These tools will also generate logs for all jobs that are actively running and can be monitored with their internal interfaces. Basically, I mean to say developing/maintaining logs is not a challenging activity in the tool. whereas on python, it is a separate activity that needs to be handled. Today, In our post we will discuss the basic skeleton of ETL jobs, a rough idea of details we can record in any pipeline, then later we structure them into our ETL code, and finally, we will develop a sample scenario with logs recorded.
ETL Skeleton: As we already know there are different kinds of ETL jobs like Merge/Upsert process, Staging loads, SCD 2 loads, Delta jobs, direct insert loads, etc. all these ETL jobs have a very basic structure(shown below in python) and i.e. the main function to call the modules in the pipeline, extract module, transformation module, and load module, Now, we can take the below Skeleton to also identify what could be our ETL log look like.
def extract(): passdef transformation(): passdef load(): passdef main(): extract() transformation() load() if __name__=="__main__": main()
Structure of Log: As we outlined the blueprint of the ETL job, let’s try to list down a rough idea of what details we can track from a job.
A list of details we can log —
display initialized elements/components like folder location, file location, server id, user id details, process details in a job
display extract stage details, like source file name, source file count if needed, the format of the file, file size, source table name, source DB connection details(except any secret credentials(user/passwords)), any exception or errors if file/source table missing or failed to fetch data messages.
display transformation stage details — like failed/exception messages if out of memory during data processing, any data/format conversion details if required.
display load stage details like file/target locations, number of records loaded, failed to load, constraints of any DB loads, load summary details.
display job summary like process run time, memory usage, CPU usage, these can also be tracked at extract, transform and load level to evenly identify bottlenecks of job.
Now let’s integrate the above details in our ETL skeleton and see how could be our log structure looks like!
##basic config##logging.config.fileConfig('logging.conf')logger = logging.getLogger(__name__)logger.setLevel(logging.DEBUG)#job parameters configconfig = configparser.ConfigParser()config.read('etlConfig.ini')JobConfig = config['ETL_Log_Job']formatter = logging.Formatter('%(levelname)s: %(asctime)s: %(process)s: %(funcName)s: %(message)s')##creating handlerstream_handler = logging.StreamHandler()file_handler = logging.FileHandler(JobConfig['LogName'])file_handler.setFormatter(formatter)logger.addHandler(file_handler)def extract(counter): logger.info('Start Extract Session') try: pass except ValueError as e: logger.error(e) logger.info("extract completed!")def transformation(counter): logger.info('Start Transformation Session') pass logger.info("Transformation completed,data ready to load!")def load(counter): logger.info('Start Load Session') try: pass except Exception as e: logger.error(e)def main(): start = time.time() ##extract start1 = time.time() extract() end1 = time.time() - start1 logger.info('Extract CPU usage {}%'.format(psutil.cpu_percent())) logger.info("Extract function took : {} seconds".format(end1)) ##transformation start2 = time.time() transformation() end2 = time.time() - start2 logger.info('Transform CPU usage{}%'.format(get_cpu_usage_pct())) logger.info("Transformation took : {} seconds".format(end2)) ##load start3 = time.time() load() end3 = time.time() - start3 logger.info('Load CPU usage {}%'.format(psutil.cpu_percent())) logger.info("Load took : {} seconds".format(end3)) end = time.time() - start logger.info("ETL Job took : {} seconds".format(end)) logger.info('Session Summary') logger.info('RAM memory {}% used:'.format(psutil.virtual_memory().percent)) logger.info('CPU usage {}%'.format(psutil.cpu_percent())) print("multiple threads took : {} seconds".format(end))if __name__=="__main__": logger.info('ETL Process Initialized') main()
And, if you observe the above code structure, I have created a config file to maintain all job level details. By importing this file into your code you can make use of different parts of the code including for logging.
etlConfig.ini :
##ETL jobs Parameters[ETL_Log_Job] ##Job nameJob_Name = etl_log_job.pyLogName = etl_log_job.logTgtConnection = Customers.dbSrcConnection = Customers.dbSrcObject = customer_file.csvTgtObject = customer##Add more job details as needed
Sample ETL job with our log structure:
import logging.configimport timeimport psutilimport configparserimport pandas as pdimport sqlite3##basic config##logging.config.fileConfig('logging.conf')logger = logging.getLogger(__name__)logger.setLevel(logging.DEBUG)#job parameters configconfig = configparser.ConfigParser()config.read('etlConfig.ini')JobConfig = config['ETL_Log_Job']formatter = logging.Formatter('%(levelname)s: %(asctime)s: %(process)s: %(funcName)s: %(message)s')##creating handlerstream_handler = logging.StreamHandler()file_handler = logging.FileHandler(JobConfig['LogName'])file_handler.setFormatter(formatter)logger.addHandler(file_handler)def extract():logger.info('Start Extract Session') logger.info('Source Filename: {}'.format(JobConfig['SrcObject']))try: df = pd.read_csv(JobConfig['SrcObject']) logger.info('Records count in source file: {}'.format(len(df.index))) except ValueError as e: logger.error(e) return logger.info("Read completed!!") return dfdef transformation(tdf): try: tdf = pd.read_csv(JobConfig['SrcObject']) tdf[['fname', 'lname']] = tdf.NAME.str.split(expand=True) ndf = tdf[['ID', 'fname', 'lname', 'ADDRESS']] logger.info('Transformation completed, data ready to load!') except Exception as e: logger.error(e) return return ndfdef load(ldf): logger.info('Start Load Session') try: conn = sqlite3.connect(JobConfig['TgtConnection']) cursor = conn.cursor() logger.info('Connection to {} database established'.format(JobConfig['TgtConnection1'])) except Exception as e: logger.error(e) return #3Load dataframe to table try: for index,row in ldf.iterrows(): query = """INSERT OR REPLACE INTO {0}(id,fname,lname,address) VALUES('{1}','{2}','{3}','{4}')""".format(JobConfig['TgtObject'],row['ID'],row['fname'],row['lname'],row['ADDRESS']) cursor.execute(query)except Exception as e: logger.error(e) return conn.commit() logger.info("Data Loaded into target table: {}".format(JobConfig['TgtObject'])) returndef main():start = time.time()##extract start1 = time.time() tdf = extract() end1 = time.time() - start1 logger.info('Extract CPU usage {}%'.format(psutil.cpu_percent())) logger.info("Extract function took : {} seconds".format(end1))##transformation start2 = time.time() ldf = transformation(tdf) end2 = time.time() - start2 logger.info('Transform CPU usage {}%'.format(psutil.cpu_percent())) logger.info("Transformation took : {} seconds".format(end2))##load start3 = time.time() load(ldf) end3 = time.time() - start3 logger.info('Load CPU usage {}%'.format(psutil.cpu_percent())) logger.info("Load took : {} seconds".format(end3)) end = time.time() - start logger.info("ETL Job took : {} seconds".format(end)) ##p = psutil.Process() ##ls = p.as_dict() ##print(p.as_dict()) logger.info('Session Summary') logger.info('RAM memory {}% used:'.format(psutil.virtual_memory().percent)) logger.info('CPU usage {}%'.format(psutil.cpu_percent())) print("multiple threads took : {} seconds".format(end))if __name__=="__main__": logger.info('ETL Process Initialized') main()
##Log output for above sample job
Few more improvements we can do to our Log:
By implementing config/parameter files for jobs it would also be easy to maintain job logging.We can add system-level summary details to later optimize or identify bottlenecks in our jobs. being able to identify CPU performance/usage of extract, transform and load can help developers more.If we are loading in targets, try to keep track of the load summary, which will help to identify the consistency of data loaded.The logging module in python is simple and effective to use in ETL jobs.also providing process id or thread id details could be helpful later to troubleshoot the process on other platforms.and giving server or node details where jobs are running will help dig our root causes.
By implementing config/parameter files for jobs it would also be easy to maintain job logging.
We can add system-level summary details to later optimize or identify bottlenecks in our jobs. being able to identify CPU performance/usage of extract, transform and load can help developers more.
If we are loading in targets, try to keep track of the load summary, which will help to identify the consistency of data loaded.
The logging module in python is simple and effective to use in ETL jobs.
also providing process id or thread id details could be helpful later to troubleshoot the process on other platforms.
and giving server or node details where jobs are running will help dig our root causes.
Sample Code location:
github.com
Thank you for reading this post, future work will involve other challenges while developing python ETL jobs like Orchestration, Code management, version control, etc.
Reference:
Elliot Forbes, https://tutorialedge.net/python/python-logging-best-practices/ (2017)
Elliot Forbes, https://tutorialedge.net/python/python-logging-best-practices/ (2017) | [
{
"code": null,
"e": 648,
"s": 172,
"text": "As part of my work, I have been converting some of my ETL jobs developed on the traditional tool-based framework into a python framework and came across a few challenges. These few challenges are orchestration, code management, logging, version control, etc. For a few of them, there was not much effort required while developing them on a tool. But, in hand-written code like python ETL’s, these are quite a challenge! And this brings to one such challenge, our topic today!"
},
{
"code": null,
"e": 777,
"s": 648,
"text": "Also instead of describing much on ‘how’, as there are many good articles already on a platform, our main focus today is ‘What’."
},
{
"code": null,
"e": 787,
"s": 777,
"text": "Glossary:"
},
{
"code": null,
"e": 882,
"s": 787,
"text": "IntroductionETL SkeletonStructure of Log!!Sample ETL job with our log structure.Code Location."
},
{
"code": null,
"e": 895,
"s": 882,
"text": "Introduction"
},
{
"code": null,
"e": 908,
"s": 895,
"text": "ETL Skeleton"
},
{
"code": null,
"e": 927,
"s": 908,
"text": "Structure of Log!!"
},
{
"code": null,
"e": 966,
"s": 927,
"text": "Sample ETL job with our log structure."
},
{
"code": null,
"e": 981,
"s": 966,
"text": "Code Location."
},
{
"code": null,
"e": 1697,
"s": 981,
"text": "Introduction: When we design and develop ETL pipelines on tools we focus on components like sources, target objects, transformation logic, and a few support tasks to handle pipelines. These tools will also generate logs for all jobs that are actively running and can be monitored with their internal interfaces. Basically, I mean to say developing/maintaining logs is not a challenging activity in the tool. whereas on python, it is a separate activity that needs to be handled. Today, In our post we will discuss the basic skeleton of ETL jobs, a rough idea of details we can record in any pipeline, then later we structure them into our ETL code, and finally, we will develop a sample scenario with logs recorded."
},
{
"code": null,
"e": 2141,
"s": 1697,
"text": "ETL Skeleton: As we already know there are different kinds of ETL jobs like Merge/Upsert process, Staging loads, SCD 2 loads, Delta jobs, direct insert loads, etc. all these ETL jobs have a very basic structure(shown below in python) and i.e. the main function to call the modules in the pipeline, extract module, transformation module, and load module, Now, we can take the below Skeleton to also identify what could be our ETL log look like."
},
{
"code": null,
"e": 2304,
"s": 2141,
"text": "def extract(): passdef transformation(): passdef load(): passdef main(): extract() transformation() load() if __name__==\"__main__\": main()"
},
{
"code": null,
"e": 2444,
"s": 2304,
"text": "Structure of Log: As we outlined the blueprint of the ETL job, let’s try to list down a rough idea of what details we can track from a job."
},
{
"code": null,
"e": 2475,
"s": 2444,
"text": "A list of details we can log —"
},
{
"code": null,
"e": 2605,
"s": 2475,
"text": "display initialized elements/components like folder location, file location, server id, user id details, process details in a job"
},
{
"code": null,
"e": 2906,
"s": 2605,
"text": "display extract stage details, like source file name, source file count if needed, the format of the file, file size, source table name, source DB connection details(except any secret credentials(user/passwords)), any exception or errors if file/source table missing or failed to fetch data messages."
},
{
"code": null,
"e": 3065,
"s": 2906,
"text": "display transformation stage details — like failed/exception messages if out of memory during data processing, any data/format conversion details if required."
},
{
"code": null,
"e": 3213,
"s": 3065,
"text": "display load stage details like file/target locations, number of records loaded, failed to load, constraints of any DB loads, load summary details."
},
{
"code": null,
"e": 3383,
"s": 3213,
"text": "display job summary like process run time, memory usage, CPU usage, these can also be tracked at extract, transform and load level to evenly identify bottlenecks of job."
},
{
"code": null,
"e": 3492,
"s": 3383,
"text": "Now let’s integrate the above details in our ETL skeleton and see how could be our log structure looks like!"
},
{
"code": null,
"e": 5523,
"s": 3492,
"text": "##basic config##logging.config.fileConfig('logging.conf')logger = logging.getLogger(__name__)logger.setLevel(logging.DEBUG)#job parameters configconfig = configparser.ConfigParser()config.read('etlConfig.ini')JobConfig = config['ETL_Log_Job']formatter = logging.Formatter('%(levelname)s: %(asctime)s: %(process)s: %(funcName)s: %(message)s')##creating handlerstream_handler = logging.StreamHandler()file_handler = logging.FileHandler(JobConfig['LogName'])file_handler.setFormatter(formatter)logger.addHandler(file_handler)def extract(counter): logger.info('Start Extract Session') try: pass except ValueError as e: logger.error(e) logger.info(\"extract completed!\")def transformation(counter): logger.info('Start Transformation Session') pass logger.info(\"Transformation completed,data ready to load!\")def load(counter): logger.info('Start Load Session') try: pass except Exception as e: logger.error(e)def main(): start = time.time() ##extract start1 = time.time() extract() end1 = time.time() - start1 logger.info('Extract CPU usage {}%'.format(psutil.cpu_percent())) logger.info(\"Extract function took : {} seconds\".format(end1)) ##transformation start2 = time.time() transformation() end2 = time.time() - start2 logger.info('Transform CPU usage{}%'.format(get_cpu_usage_pct())) logger.info(\"Transformation took : {} seconds\".format(end2)) ##load start3 = time.time() load() end3 = time.time() - start3 logger.info('Load CPU usage {}%'.format(psutil.cpu_percent())) logger.info(\"Load took : {} seconds\".format(end3)) end = time.time() - start logger.info(\"ETL Job took : {} seconds\".format(end)) logger.info('Session Summary') logger.info('RAM memory {}% used:'.format(psutil.virtual_memory().percent)) logger.info('CPU usage {}%'.format(psutil.cpu_percent())) print(\"multiple threads took : {} seconds\".format(end))if __name__==\"__main__\": logger.info('ETL Process Initialized') main()"
},
{
"code": null,
"e": 5742,
"s": 5523,
"text": "And, if you observe the above code structure, I have created a config file to maintain all job level details. By importing this file into your code you can make use of different parts of the code including for logging."
},
{
"code": null,
"e": 5758,
"s": 5742,
"text": "etlConfig.ini :"
},
{
"code": null,
"e": 5991,
"s": 5758,
"text": "##ETL jobs Parameters[ETL_Log_Job] ##Job nameJob_Name = etl_log_job.pyLogName = etl_log_job.logTgtConnection = Customers.dbSrcConnection = Customers.dbSrcObject = customer_file.csvTgtObject = customer##Add more job details as needed"
},
{
"code": null,
"e": 6030,
"s": 5991,
"text": "Sample ETL job with our log structure:"
},
{
"code": null,
"e": 9277,
"s": 6030,
"text": "import logging.configimport timeimport psutilimport configparserimport pandas as pdimport sqlite3##basic config##logging.config.fileConfig('logging.conf')logger = logging.getLogger(__name__)logger.setLevel(logging.DEBUG)#job parameters configconfig = configparser.ConfigParser()config.read('etlConfig.ini')JobConfig = config['ETL_Log_Job']formatter = logging.Formatter('%(levelname)s: %(asctime)s: %(process)s: %(funcName)s: %(message)s')##creating handlerstream_handler = logging.StreamHandler()file_handler = logging.FileHandler(JobConfig['LogName'])file_handler.setFormatter(formatter)logger.addHandler(file_handler)def extract():logger.info('Start Extract Session') logger.info('Source Filename: {}'.format(JobConfig['SrcObject']))try: df = pd.read_csv(JobConfig['SrcObject']) logger.info('Records count in source file: {}'.format(len(df.index))) except ValueError as e: logger.error(e) return logger.info(\"Read completed!!\") return dfdef transformation(tdf): try: tdf = pd.read_csv(JobConfig['SrcObject']) tdf[['fname', 'lname']] = tdf.NAME.str.split(expand=True) ndf = tdf[['ID', 'fname', 'lname', 'ADDRESS']] logger.info('Transformation completed, data ready to load!') except Exception as e: logger.error(e) return return ndfdef load(ldf): logger.info('Start Load Session') try: conn = sqlite3.connect(JobConfig['TgtConnection']) cursor = conn.cursor() logger.info('Connection to {} database established'.format(JobConfig['TgtConnection1'])) except Exception as e: logger.error(e) return #3Load dataframe to table try: for index,row in ldf.iterrows(): query = \"\"\"INSERT OR REPLACE INTO {0}(id,fname,lname,address) VALUES('{1}','{2}','{3}','{4}')\"\"\".format(JobConfig['TgtObject'],row['ID'],row['fname'],row['lname'],row['ADDRESS']) cursor.execute(query)except Exception as e: logger.error(e) return conn.commit() logger.info(\"Data Loaded into target table: {}\".format(JobConfig['TgtObject'])) returndef main():start = time.time()##extract start1 = time.time() tdf = extract() end1 = time.time() - start1 logger.info('Extract CPU usage {}%'.format(psutil.cpu_percent())) logger.info(\"Extract function took : {} seconds\".format(end1))##transformation start2 = time.time() ldf = transformation(tdf) end2 = time.time() - start2 logger.info('Transform CPU usage {}%'.format(psutil.cpu_percent())) logger.info(\"Transformation took : {} seconds\".format(end2))##load start3 = time.time() load(ldf) end3 = time.time() - start3 logger.info('Load CPU usage {}%'.format(psutil.cpu_percent())) logger.info(\"Load took : {} seconds\".format(end3)) end = time.time() - start logger.info(\"ETL Job took : {} seconds\".format(end)) ##p = psutil.Process() ##ls = p.as_dict() ##print(p.as_dict()) logger.info('Session Summary') logger.info('RAM memory {}% used:'.format(psutil.virtual_memory().percent)) logger.info('CPU usage {}%'.format(psutil.cpu_percent())) print(\"multiple threads took : {} seconds\".format(end))if __name__==\"__main__\": logger.info('ETL Process Initialized') main()"
},
{
"code": null,
"e": 9311,
"s": 9277,
"text": "##Log output for above sample job"
},
{
"code": null,
"e": 9355,
"s": 9311,
"text": "Few more improvements we can do to our Log:"
},
{
"code": null,
"e": 10050,
"s": 9355,
"text": "By implementing config/parameter files for jobs it would also be easy to maintain job logging.We can add system-level summary details to later optimize or identify bottlenecks in our jobs. being able to identify CPU performance/usage of extract, transform and load can help developers more.If we are loading in targets, try to keep track of the load summary, which will help to identify the consistency of data loaded.The logging module in python is simple and effective to use in ETL jobs.also providing process id or thread id details could be helpful later to troubleshoot the process on other platforms.and giving server or node details where jobs are running will help dig our root causes."
},
{
"code": null,
"e": 10145,
"s": 10050,
"text": "By implementing config/parameter files for jobs it would also be easy to maintain job logging."
},
{
"code": null,
"e": 10342,
"s": 10145,
"text": "We can add system-level summary details to later optimize or identify bottlenecks in our jobs. being able to identify CPU performance/usage of extract, transform and load can help developers more."
},
{
"code": null,
"e": 10471,
"s": 10342,
"text": "If we are loading in targets, try to keep track of the load summary, which will help to identify the consistency of data loaded."
},
{
"code": null,
"e": 10544,
"s": 10471,
"text": "The logging module in python is simple and effective to use in ETL jobs."
},
{
"code": null,
"e": 10662,
"s": 10544,
"text": "also providing process id or thread id details could be helpful later to troubleshoot the process on other platforms."
},
{
"code": null,
"e": 10750,
"s": 10662,
"text": "and giving server or node details where jobs are running will help dig our root causes."
},
{
"code": null,
"e": 10772,
"s": 10750,
"text": "Sample Code location:"
},
{
"code": null,
"e": 10783,
"s": 10772,
"text": "github.com"
},
{
"code": null,
"e": 10950,
"s": 10783,
"text": "Thank you for reading this post, future work will involve other challenges while developing python ETL jobs like Orchestration, Code management, version control, etc."
},
{
"code": null,
"e": 10961,
"s": 10950,
"text": "Reference:"
},
{
"code": null,
"e": 11046,
"s": 10961,
"text": "Elliot Forbes, https://tutorialedge.net/python/python-logging-best-practices/ (2017)"
}
]
|
Colored Flower by circles using Turtle in Python - GeeksforGeeks | 01 Aug, 2020
Turtle is an inbuilt module in Python. It provides drawing using a screen (cardboard) and turtle (pen). To draw something on the screen, we need to move the turtle (pen). To move turtle, there are some functions i.e forward(), backward(), etc.
Following steps are used :
Import Turtle
Set screen
Make Turtle Object
Define colors used for drawing
Loop to draw circles oriented by angle.
Below is the implementation :
Python3
# import turtle package import turtle # screen objectsc = turtle.Screen() # turtle objectpen = turtle.Turtle() # Driver Code# colorscol = ['violet', 'indigo', 'blue', 'green', 'yellow', 'orange', 'red'] # screen sizesc.setup(500,500) # screen colorsc.bgcolor('black') # turtle sizepen.pensize(4) # turtle objectpen.speed(20) # integer variable # for accessing colorsi = 0 # loop to draw 30 circles for angle in range(0, 360, 12): # color of circle pen.color(col[i]) if i == 6: i = 0 else: i += 1 # Set the orientation of # the turtle to angle pen.seth(angle) # circle of radius 80 pen.circle(80) # hide the turtlepen.ht()
Python-turtle
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
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python | [
{
"code": null,
"e": 24640,
"s": 24612,
"text": "\n01 Aug, 2020"
},
{
"code": null,
"e": 24884,
"s": 24640,
"text": "Turtle is an inbuilt module in Python. It provides drawing using a screen (cardboard) and turtle (pen). To draw something on the screen, we need to move the turtle (pen). To move turtle, there are some functions i.e forward(), backward(), etc."
},
{
"code": null,
"e": 24911,
"s": 24884,
"text": "Following steps are used :"
},
{
"code": null,
"e": 24925,
"s": 24911,
"text": "Import Turtle"
},
{
"code": null,
"e": 24936,
"s": 24925,
"text": "Set screen"
},
{
"code": null,
"e": 24955,
"s": 24936,
"text": "Make Turtle Object"
},
{
"code": null,
"e": 24986,
"s": 24955,
"text": "Define colors used for drawing"
},
{
"code": null,
"e": 25026,
"s": 24986,
"text": "Loop to draw circles oriented by angle."
},
{
"code": null,
"e": 25056,
"s": 25026,
"text": "Below is the implementation :"
},
{
"code": null,
"e": 25064,
"s": 25056,
"text": "Python3"
},
{
"code": "# import turtle package import turtle # screen objectsc = turtle.Screen() # turtle objectpen = turtle.Turtle() # Driver Code# colorscol = ['violet', 'indigo', 'blue', 'green', 'yellow', 'orange', 'red'] # screen sizesc.setup(500,500) # screen colorsc.bgcolor('black') # turtle sizepen.pensize(4) # turtle objectpen.speed(20) # integer variable # for accessing colorsi = 0 # loop to draw 30 circles for angle in range(0, 360, 12): # color of circle pen.color(col[i]) if i == 6: i = 0 else: i += 1 # Set the orientation of # the turtle to angle pen.seth(angle) # circle of radius 80 pen.circle(80) # hide the turtlepen.ht()",
"e": 25772,
"s": 25064,
"text": null
},
{
"code": null,
"e": 25786,
"s": 25772,
"text": "Python-turtle"
},
{
"code": null,
"e": 25793,
"s": 25786,
"text": "Python"
},
{
"code": null,
"e": 25891,
"s": 25793,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25909,
"s": 25891,
"text": "Python Dictionary"
},
{
"code": null,
"e": 25944,
"s": 25909,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 25966,
"s": 25944,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 25998,
"s": 25966,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26028,
"s": 25998,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26070,
"s": 26028,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26096,
"s": 26070,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26133,
"s": 26096,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26176,
"s": 26133,
"text": "Python program to convert a list to string"
}
]
|
C++ Program to implement Symbol Table - GeeksforGeeks | 11 Sep, 2018
Prerequisite: Symbol Table
A Symbol table is a data structure used by the compiler, where each identifier in program’s source code is stored along with information associated with it relating to its declaration. It stores identifier as well as it’s associated attributes like scope, type, line-number of occurrence, etc.
Symbol table can be implemented using various data structures like:
LinkedList
Hash Table
Tree
A common data structure used to implement a symbol table is HashTable.
Operations of Symbol table – The basic operations defined on a symbol table include:
Consider the following C++ function:
// Define a global functionint add(int a, int b){int sum = 0;sum = a + b;return sum;}
Symbol Table for above code:
Below is the C++ implementation of Symbol Table using the concept of Hashing with separate chaining:
// C++ program to implement Symbol Table#include <iostream>using namespace std; const int MAX = 100; class Node { string identifier, scope, type; int lineNo; Node* next; public: Node() { next = NULL; } Node(string key, string value, string type, int lineNo) { this->identifier = key; this->scope = value; this->type = type; this->lineNo = lineNo; next = NULL; } void print() { cout << "Identifier's Name:" << identifier << "\nType:" << type << "\nScope: " << scope << "\nLine Number: " << lineNo << endl; } friend class SymbolTable;}; class SymbolTable { Node* head[MAX]; public: SymbolTable() { for (int i = 0; i < MAX; i++) head[i] = NULL; } int hashf(string id); // hash function bool insert(string id, string scope, string Type, int lineno); string find(string id); bool deleteRecord(string id); bool modify(string id, string scope, string Type, int lineno);}; // Function to modify an identifierbool SymbolTable::modify(string id, string s, string t, int l){ int index = hashf(id); Node* start = head[index]; if (start == NULL) return "-1"; while (start != NULL) { if (start->identifier == id) { start->scope = s; start->type = t; start->lineNo = l; return true; } start = start->next; } return false; // id not found} // Function to delete an identifierbool SymbolTable::deleteRecord(string id){ int index = hashf(id); Node* tmp = head[index]; Node* par = head[index]; // no identifier is present at that index if (tmp == NULL) { return false; } // only one identifier is present if (tmp->identifier == id && tmp->next == NULL) { tmp->next = NULL; delete tmp; return true; } while (tmp->identifier != id && tmp->next != NULL) { par = tmp; tmp = tmp->next; } if (tmp->identifier == id && tmp->next != NULL) { par->next = tmp->next; tmp->next = NULL; delete tmp; return true; } // delete at the end else { par->next = NULL; tmp->next = NULL; delete tmp; return true; } return false;} // Function to find an identifierstring SymbolTable::find(string id){ int index = hashf(id); Node* start = head[index]; if (start == NULL) return "-1"; while (start != NULL) { if (start->identifier == id) { start->print(); return start->scope; } start = start->next; } return "-1"; // not found} // Function to insert an identifierbool SymbolTable::insert(string id, string scope, string Type, int lineno){ int index = hashf(id); Node* p = new Node(id, scope, Type, lineno); if (head[index] == NULL) { head[index] = p; cout << "\n" << id << " inserted"; return true; } else { Node* start = head[index]; while (start->next != NULL) start = start->next; start->next = p; cout << "\n" << id << " inserted"; return true; } return false;} int SymbolTable::hashf(string id){ int asciiSum = 0; for (int i = 0; i < id.length(); i++) { asciiSum = asciiSum + id[i]; } return (asciiSum % 100);} // Driver codeint main(){ SymbolTable st; string check; cout << "**** SYMBOL_TABLE ****\n"; // insert 'if' if (st.insert("if", "local", "keyword", 4)) cout << " -successfully"; else cout << "\nFailed to insert.\n"; // insert 'number' if (st.insert("number", "global", "variable", 2)) cout << " -successfully\n\n"; else cout << "\nFailed to insert\n"; // find 'if' check = st.find("if"); if (check != "-1") cout << "Identifier Is present\n"; else cout << "\nIdentifier Not Present\n"; // delete 'if' if (st.deleteRecord("if")) cout << "if Identifier is deleted\n"; else cout << "\nFailed to delete\n"; // modify 'number' if (st.modify("number", "global", "variable", 3)) cout << "\nNumber Identifier updated\n"; // find and print 'number' check = st.find("number"); if (check != "-1") cout << "Identifier Is present\n"; else cout << "\nIdentifier Not Present"; return 0;}
**** SYMBOL_TABLE ****
if inserted -successfully
number inserted -successfully
Identifier's Name:if
Type:keyword
Scope: local
Line Number: 4
Identifier Is present
if Identifier is deleted
number Identifier updated
Identifier's Name:number
Type:variable
Scope: global
Line Number: 3
Identifier Is present
Data Structures-Hash
Advanced Data Structure
C++ Programs
Compiler Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Insert Operation in B-Tree
How to design a tiny URL or URL shortener?
Design a Chess Game
Binomial Heap
Red-Black Tree | Set 3 (Delete)
Header files in C/C++ and its uses
C++ Program for QuickSort
How to return multiple values from a function in C or C++?
Program to print ASCII Value of a character
C++ program for hashing with chaining | [
{
"code": null,
"e": 24047,
"s": 24019,
"text": "\n11 Sep, 2018"
},
{
"code": null,
"e": 24074,
"s": 24047,
"text": "Prerequisite: Symbol Table"
},
{
"code": null,
"e": 24368,
"s": 24074,
"text": "A Symbol table is a data structure used by the compiler, where each identifier in program’s source code is stored along with information associated with it relating to its declaration. It stores identifier as well as it’s associated attributes like scope, type, line-number of occurrence, etc."
},
{
"code": null,
"e": 24436,
"s": 24368,
"text": "Symbol table can be implemented using various data structures like:"
},
{
"code": null,
"e": 24447,
"s": 24436,
"text": "LinkedList"
},
{
"code": null,
"e": 24458,
"s": 24447,
"text": "Hash Table"
},
{
"code": null,
"e": 24463,
"s": 24458,
"text": "Tree"
},
{
"code": null,
"e": 24534,
"s": 24463,
"text": "A common data structure used to implement a symbol table is HashTable."
},
{
"code": null,
"e": 24619,
"s": 24534,
"text": "Operations of Symbol table – The basic operations defined on a symbol table include:"
},
{
"code": null,
"e": 24656,
"s": 24619,
"text": "Consider the following C++ function:"
},
{
"code": null,
"e": 24742,
"s": 24656,
"text": "// Define a global functionint add(int a, int b){int sum = 0;sum = a + b;return sum;}"
},
{
"code": null,
"e": 24771,
"s": 24742,
"text": "Symbol Table for above code:"
},
{
"code": null,
"e": 24872,
"s": 24771,
"text": "Below is the C++ implementation of Symbol Table using the concept of Hashing with separate chaining:"
},
{
"code": "// C++ program to implement Symbol Table#include <iostream>using namespace std; const int MAX = 100; class Node { string identifier, scope, type; int lineNo; Node* next; public: Node() { next = NULL; } Node(string key, string value, string type, int lineNo) { this->identifier = key; this->scope = value; this->type = type; this->lineNo = lineNo; next = NULL; } void print() { cout << \"Identifier's Name:\" << identifier << \"\\nType:\" << type << \"\\nScope: \" << scope << \"\\nLine Number: \" << lineNo << endl; } friend class SymbolTable;}; class SymbolTable { Node* head[MAX]; public: SymbolTable() { for (int i = 0; i < MAX; i++) head[i] = NULL; } int hashf(string id); // hash function bool insert(string id, string scope, string Type, int lineno); string find(string id); bool deleteRecord(string id); bool modify(string id, string scope, string Type, int lineno);}; // Function to modify an identifierbool SymbolTable::modify(string id, string s, string t, int l){ int index = hashf(id); Node* start = head[index]; if (start == NULL) return \"-1\"; while (start != NULL) { if (start->identifier == id) { start->scope = s; start->type = t; start->lineNo = l; return true; } start = start->next; } return false; // id not found} // Function to delete an identifierbool SymbolTable::deleteRecord(string id){ int index = hashf(id); Node* tmp = head[index]; Node* par = head[index]; // no identifier is present at that index if (tmp == NULL) { return false; } // only one identifier is present if (tmp->identifier == id && tmp->next == NULL) { tmp->next = NULL; delete tmp; return true; } while (tmp->identifier != id && tmp->next != NULL) { par = tmp; tmp = tmp->next; } if (tmp->identifier == id && tmp->next != NULL) { par->next = tmp->next; tmp->next = NULL; delete tmp; return true; } // delete at the end else { par->next = NULL; tmp->next = NULL; delete tmp; return true; } return false;} // Function to find an identifierstring SymbolTable::find(string id){ int index = hashf(id); Node* start = head[index]; if (start == NULL) return \"-1\"; while (start != NULL) { if (start->identifier == id) { start->print(); return start->scope; } start = start->next; } return \"-1\"; // not found} // Function to insert an identifierbool SymbolTable::insert(string id, string scope, string Type, int lineno){ int index = hashf(id); Node* p = new Node(id, scope, Type, lineno); if (head[index] == NULL) { head[index] = p; cout << \"\\n\" << id << \" inserted\"; return true; } else { Node* start = head[index]; while (start->next != NULL) start = start->next; start->next = p; cout << \"\\n\" << id << \" inserted\"; return true; } return false;} int SymbolTable::hashf(string id){ int asciiSum = 0; for (int i = 0; i < id.length(); i++) { asciiSum = asciiSum + id[i]; } return (asciiSum % 100);} // Driver codeint main(){ SymbolTable st; string check; cout << \"**** SYMBOL_TABLE ****\\n\"; // insert 'if' if (st.insert(\"if\", \"local\", \"keyword\", 4)) cout << \" -successfully\"; else cout << \"\\nFailed to insert.\\n\"; // insert 'number' if (st.insert(\"number\", \"global\", \"variable\", 2)) cout << \" -successfully\\n\\n\"; else cout << \"\\nFailed to insert\\n\"; // find 'if' check = st.find(\"if\"); if (check != \"-1\") cout << \"Identifier Is present\\n\"; else cout << \"\\nIdentifier Not Present\\n\"; // delete 'if' if (st.deleteRecord(\"if\")) cout << \"if Identifier is deleted\\n\"; else cout << \"\\nFailed to delete\\n\"; // modify 'number' if (st.modify(\"number\", \"global\", \"variable\", 3)) cout << \"\\nNumber Identifier updated\\n\"; // find and print 'number' check = st.find(\"number\"); if (check != \"-1\") cout << \"Identifier Is present\\n\"; else cout << \"\\nIdentifier Not Present\"; return 0;}",
"e": 29423,
"s": 24872,
"text": null
},
{
"code": null,
"e": 29733,
"s": 29423,
"text": "**** SYMBOL_TABLE ****\n\nif inserted -successfully\nnumber inserted -successfully\n\nIdentifier's Name:if\nType:keyword\nScope: local\nLine Number: 4\nIdentifier Is present\n\nif Identifier is deleted\n\nnumber Identifier updated\n\nIdentifier's Name:number\nType:variable\nScope: global\nLine Number: 3\nIdentifier Is present\n"
},
{
"code": null,
"e": 29754,
"s": 29733,
"text": "Data Structures-Hash"
},
{
"code": null,
"e": 29778,
"s": 29754,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 29791,
"s": 29778,
"text": "C++ Programs"
},
{
"code": null,
"e": 29807,
"s": 29791,
"text": "Compiler Design"
},
{
"code": null,
"e": 29905,
"s": 29807,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29914,
"s": 29905,
"text": "Comments"
},
{
"code": null,
"e": 29927,
"s": 29914,
"text": "Old Comments"
},
{
"code": null,
"e": 29954,
"s": 29927,
"text": "Insert Operation in B-Tree"
},
{
"code": null,
"e": 29997,
"s": 29954,
"text": "How to design a tiny URL or URL shortener?"
},
{
"code": null,
"e": 30017,
"s": 29997,
"text": "Design a Chess Game"
},
{
"code": null,
"e": 30031,
"s": 30017,
"text": "Binomial Heap"
},
{
"code": null,
"e": 30063,
"s": 30031,
"text": "Red-Black Tree | Set 3 (Delete)"
},
{
"code": null,
"e": 30098,
"s": 30063,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 30124,
"s": 30098,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 30183,
"s": 30124,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 30227,
"s": 30183,
"text": "Program to print ASCII Value of a character"
}
]
|
Print all possible words from phone digits - GeeksforGeeks | 09 Feb, 2022
Before the advent of QWERTY keyboards, texts and numbers were placed on the same key. For example, 2 has “ABC” if we wanted to write anything starting with ‘A’ we need to type key 2 once. If we wanted to type ‘B’, press key 2 twice and thrice for typing ‘C’. Below is a picture of such a keypad.
Given a keypad as shown in the diagram, and an n digit number, list all words which are possible by pressing these numbers.
Example:
Input number: 234
Output:
adg adh adi aeg aeh aei afg afh
afi bdg bdh bdi beg beh bei bfg
bfh bfi cdg cdh cdi ceg ceh cei
cfg cfh cfi
Explanation: All possible words which can be
formed are (Alphabetical order):
adg adh adi aeg aeh aei afg afh
afi bdg bdh bdi beg beh bei bfg
bfh bfi cdg cdh cdi ceg ceh cei
cfg cfh cfi
If 2 is pressed then the alphabet
can be a, b, c,
Similarly, for 3, it can be
d, e, f, and for 4 can be g, h, i.
Input number: 5
Output: j k l
Explanation: All possible words which can be
formed are (Alphabetical order):
j, k, l, only these three alphabets
can be written with j, k, l.
Approach: It can be observed that each digit can represent 3 to 4 different alphabets (apart from 0 and 1). So the idea is to form a recursive function. Then map the number with its string of probable alphabets, i.e 2 with “abc”, 3 with “def” etc. Now the recursive function will try all the alphabets, mapped to the current digit in alphabetic order, and again call the recursive function for the next digit and will pass on the current output string.
Example:
If the number is 23,
Then for 2, the alphabets are a, b, c
So 3 recursive function will be called
with output string as a, b, c respectively
and for 3 there are 3 alphabets d, e, f
So, the output will be ad, ae and af for
the recursive function with output string.
Similarly, for b and c, the output will be:
bd, be, bf and cd, ce, cf respectively.
Algorithm:
Map the number with its string of probable alphabets, i.e 2 with “abc”, 3 with “def” etc.Create a recursive function which takes the following parameters, output string, number array, current index, and length of number arrayIf the current index is equal to the length of the number array then print the output string.Extract the string at digit[current_index] from the Map, where the digit is the input number array.Run a loop to traverse the string from start to endFor every index again call the recursive function with the output string concatenated with the ith character of the string and the current_index + 1.
Map the number with its string of probable alphabets, i.e 2 with “abc”, 3 with “def” etc.
Create a recursive function which takes the following parameters, output string, number array, current index, and length of number array
If the current index is equal to the length of the number array then print the output string.
Extract the string at digit[current_index] from the Map, where the digit is the input number array.
Run a loop to traverse the string from start to end
For every index again call the recursive function with the output string concatenated with the ith character of the string and the current_index + 1.
Implementation: Note that the input number is represented as an array to simplify the code.
C++
C
Java
Python3
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find all possible combinations by// replacing key's digits with characters of the// corresponding listvoid findCombinations(vector<char> keypad[], int input[], string res, int index, int n){ // If processed every digit of key, print result if (index == n) { cout << res << " "; return; } // Stores current digit int digit = input[index]; // Size of the list corresponding to current digit int len = keypad[digit].size(); // One by one replace the digit with each character in the // corresponding list and recur for next digit for (int i = 0; i < len; i++) { findCombinations(keypad, input, res + keypad[digit][i], index + 1, n); }} // Driver Codeint main(){ // Given mobile keypad vector<char> keypad[] = { {}, {}, // 0 and 1 digit don't have any characters associated { 'a', 'b', 'c' }, { 'd', 'e', 'f' }, { 'g', 'h', 'i' }, { 'j', 'k', 'l' }, { 'm', 'n', 'o' }, { 'p', 'q', 'r', 's'}, { 't', 'u', 'v' }, { 'w', 'x', 'y', 'z'} }; // Given input array int input[] = { 2, 3, 4 }; // Size of the array int n = sizeof(input)/sizeof(input[0]); // Function call to find all combinations findCombinations(keypad, input, string(""), 0, n ); return 0;}
#include <stdio.h>#include <string.h> // hashTable[i] stores all characters that correspond to// digit i in phoneconst char hashTable[10][5] = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" }; // A recursive function to print all possible words that can// be obtained by input number[] of size n. The output// words are one by one stored in output[]void printWordsUtil(int number[], int curr_digit, char output[], int n){ // Base case, if current output word is prepared int i; if (curr_digit == n) { printf("%s ", output); return; } // Try all 3 possible characters for current digit in // number[] and recur for remaining digits for (i = 0; i < strlen(hashTable[number[curr_digit]]); i++) { output[curr_digit] = hashTable[number[curr_digit]][i]; printWordsUtil(number, curr_digit + 1, output, n); if (number[curr_digit] == 0 || number[curr_digit] == 1) return; }} // A wrapper over printWordsUtil(). It creates an output// array and calls printWordsUtil()void printWords(int number[], int n){ char result[n + 1]; result[n] = '\0'; printWordsUtil(number, 0, result, n);} // Driver programint main(void){ int number[] = { 2, 3, 4 }; int n = sizeof(number) / sizeof(number[0]); printWords(number, n); return 0;}
// Java program to implement the// above approachimport java.util.*;import java.lang.*;import java.io.*;class NumberPadString{ static Character[][] numberToCharMap; private static List<String> printWords(int[] numbers, int len, int numIndex, String s){ if(len == numIndex) { return new ArrayList<>(Collections.singleton(s)); } List<String> stringList = new ArrayList<>(); for(int i = 0; i < numberToCharMap[numbers[numIndex]].length; i++) { String sCopy = String.copyValueOf(s.toCharArray()); sCopy = sCopy.concat( numberToCharMap[numbers[numIndex]][i].toString()); stringList.addAll(printWords(numbers, len, numIndex + 1, sCopy)); } return stringList;} private static void printWords(int[] numbers){ generateNumberToCharMap(); List<String> stringList = printWords(numbers, numbers.length, 0, ""); stringList.stream().forEach(System.out :: println);} private static void generateNumberToCharMap(){ numberToCharMap = new Character[10][5]; numberToCharMap[0] = new Character[]{'\0'}; numberToCharMap[1] = new Character[]{'\0'}; numberToCharMap[2] = new Character[]{'a','b','c'}; numberToCharMap[3] = new Character[]{'d','e','f'}; numberToCharMap[4] = new Character[]{'g','h','i'}; numberToCharMap[5] = new Character[]{'j','k','l'}; numberToCharMap[6] = new Character[]{'m','n','o'}; numberToCharMap[7] = new Character[]{'p','q','r','s'}; numberToCharMap[8] = new Character[]{'t','u','v'}; numberToCharMap[9] = new Character[]{'w','x','y','z'};} // Driver code public static void main(String[] args){ int number[] = {2, 3, 4}; printWords(number);}} // This code is contributed by ankit pachori 1
# hashTable[i] stores all characters# that correspond to digit i in phonehashTable = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"] # A recursive function to print all# possible words that can be obtained# by input number[] of size n. The# output words are one by one stored# in output[] def printWordsUtil(number, curr, output, n): if(curr == n): print(output) return # Try all 3 possible characters # for current digit in number[] # and recur for remaining digits for i in range(len(hashTable[number[curr]])): output.append(hashTable[number[curr]][i]) printWordsUtil(number, curr + 1, output, n) output.pop() if(number[curr] == 0 or number[curr] == 1): return # A wrapper over printWordsUtil().# It creates an output array and# calls printWordsUtil() def printWords(number, n): printWordsUtil(number, 0, [], n) # Driver functionif __name__ == '__main__': number = [2, 3, 4] n = len(number) printWords(number, n) # This code is contributed by prajmsidc
<script> // Javascript program to implement the// above approachlet hashTable = [ "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" ]; // A recursive function to print all possible// words that can be obtained by input number[]// of size n. The output words are one by one// stored in output[]function printWordsUtil(number, curr, output, n){ // Base case, if current output // word is prepared if (curr == n) { document.write(output.join("") + "<br>") return; } // Try all 3 possible characters for current // digit in number[] and recur for remaining digits for(let i = 0; i < hashTable[number[curr]].length; i++) { output.push(hashTable[number[curr]][i]); printWordsUtil(number, curr + 1, output, n); output.pop(); if(number[curr] == 0 || number[curr] == 1) return }} // A wrapper over printWordsUtil(). It creates// an output array and calls printWordsUtil()function printWords(numbers, n){ printWordsUtil(number, 0, [], n);} // Driver codelet number = [ 2, 3, 4 ];let n = number.length; printWords(number, n); // This code is contributed by avanitrachhadiya2155 </script>
Output:
adg adh adi aeg aeh aei afg afh afi bdg
bdh bdi beg beh bei bfg bfh bfi cdg cdh
cdi ceg ceh cei cfg cfh cfi
Process returned 0 (0x0) execution time : 0.025 s
Press any key to continue.
Complexity Analysis:
Time Complexity: O(4n), where n is a number of digits in the input number. Each digit of a number has 3 or 4 alphabets, so it can be said that each digit has 4 alphabets as options. If there are n digits then there are 4 options for the first digit and for each alphabet of the first digit there are 4 options in the second digit, i.e for every recursion 4 more recursions are called (if it does not match the base case). So the time complexity is O(4n).
Space Complexity:O(1). As no extra space is needed.
Reference: Buy Programming Interviews Exposed: Secrets to Landing Your Next Job 3rd Edition from Flipkart.comThis article is contributed by Jitendra Sangar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
ABHISHEKSINGH15BCE1009
prajmsidc
andrew1234
ankit pachori 1
pawki
avanitrachhadiya2155
vinod0808
simmytarika5
Accolite
Amazon
Flipkart
OYO Rooms
phone-keypad
Samsung
Snapdeal
Zoho
Arrays
Mathematical
Recursion
Strings
Zoho
Flipkart
Accolite
Amazon
OYO Rooms
Samsung
Snapdeal
Arrays
Strings
Mathematical
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
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": 24665,
"s": 24637,
"text": "\n09 Feb, 2022"
},
{
"code": null,
"e": 24962,
"s": 24665,
"text": "Before the advent of QWERTY keyboards, texts and numbers were placed on the same key. For example, 2 has “ABC” if we wanted to write anything starting with ‘A’ we need to type key 2 once. If we wanted to type ‘B’, press key 2 twice and thrice for typing ‘C’. Below is a picture of such a keypad. "
},
{
"code": null,
"e": 25086,
"s": 24962,
"text": "Given a keypad as shown in the diagram, and an n digit number, list all words which are possible by pressing these numbers."
},
{
"code": null,
"e": 25096,
"s": 25086,
"text": "Example: "
},
{
"code": null,
"e": 25715,
"s": 25096,
"text": "Input number: 234\nOutput:\nadg adh adi aeg aeh aei afg afh \nafi bdg bdh bdi beg beh bei bfg \nbfh bfi cdg cdh cdi ceg ceh cei \ncfg cfh cfi\nExplanation: All possible words which can be \nformed are (Alphabetical order):\nadg adh adi aeg aeh aei afg afh \nafi bdg bdh bdi beg beh bei bfg \nbfh bfi cdg cdh cdi ceg ceh cei \ncfg cfh cfi\nIf 2 is pressed then the alphabet\ncan be a, b, c, \nSimilarly, for 3, it can be \nd, e, f, and for 4 can be g, h, i. \n\nInput number: 5\nOutput: j k l\nExplanation: All possible words which can be \nformed are (Alphabetical order):\nj, k, l, only these three alphabets \ncan be written with j, k, l."
},
{
"code": null,
"e": 26168,
"s": 25715,
"text": "Approach: It can be observed that each digit can represent 3 to 4 different alphabets (apart from 0 and 1). So the idea is to form a recursive function. Then map the number with its string of probable alphabets, i.e 2 with “abc”, 3 with “def” etc. Now the recursive function will try all the alphabets, mapped to the current digit in alphabetic order, and again call the recursive function for the next digit and will pass on the current output string."
},
{
"code": null,
"e": 26178,
"s": 26168,
"text": "Example: "
},
{
"code": null,
"e": 26532,
"s": 26178,
"text": "If the number is 23,\n\nThen for 2, the alphabets are a, b, c\nSo 3 recursive function will be called \nwith output string as a, b, c respectively \nand for 3 there are 3 alphabets d, e, f\nSo, the output will be ad, ae and af for \nthe recursive function with output string.\nSimilarly, for b and c, the output will be: \nbd, be, bf and cd, ce, cf respectively."
},
{
"code": null,
"e": 26545,
"s": 26532,
"text": "Algorithm: "
},
{
"code": null,
"e": 27163,
"s": 26545,
"text": "Map the number with its string of probable alphabets, i.e 2 with “abc”, 3 with “def” etc.Create a recursive function which takes the following parameters, output string, number array, current index, and length of number arrayIf the current index is equal to the length of the number array then print the output string.Extract the string at digit[current_index] from the Map, where the digit is the input number array.Run a loop to traverse the string from start to endFor every index again call the recursive function with the output string concatenated with the ith character of the string and the current_index + 1."
},
{
"code": null,
"e": 27253,
"s": 27163,
"text": "Map the number with its string of probable alphabets, i.e 2 with “abc”, 3 with “def” etc."
},
{
"code": null,
"e": 27390,
"s": 27253,
"text": "Create a recursive function which takes the following parameters, output string, number array, current index, and length of number array"
},
{
"code": null,
"e": 27484,
"s": 27390,
"text": "If the current index is equal to the length of the number array then print the output string."
},
{
"code": null,
"e": 27584,
"s": 27484,
"text": "Extract the string at digit[current_index] from the Map, where the digit is the input number array."
},
{
"code": null,
"e": 27636,
"s": 27584,
"text": "Run a loop to traverse the string from start to end"
},
{
"code": null,
"e": 27786,
"s": 27636,
"text": "For every index again call the recursive function with the output string concatenated with the ith character of the string and the current_index + 1."
},
{
"code": null,
"e": 27879,
"s": 27786,
"text": "Implementation: Note that the input number is represented as an array to simplify the code. "
},
{
"code": null,
"e": 27883,
"s": 27879,
"text": "C++"
},
{
"code": null,
"e": 27885,
"s": 27883,
"text": "C"
},
{
"code": null,
"e": 27890,
"s": 27885,
"text": "Java"
},
{
"code": null,
"e": 27898,
"s": 27890,
"text": "Python3"
},
{
"code": null,
"e": 27909,
"s": 27898,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find all possible combinations by// replacing key's digits with characters of the// corresponding listvoid findCombinations(vector<char> keypad[], int input[], string res, int index, int n){ // If processed every digit of key, print result if (index == n) { cout << res << \" \"; return; } // Stores current digit int digit = input[index]; // Size of the list corresponding to current digit int len = keypad[digit].size(); // One by one replace the digit with each character in the // corresponding list and recur for next digit for (int i = 0; i < len; i++) { findCombinations(keypad, input, res + keypad[digit][i], index + 1, n); }} // Driver Codeint main(){ // Given mobile keypad vector<char> keypad[] = { {}, {}, // 0 and 1 digit don't have any characters associated { 'a', 'b', 'c' }, { 'd', 'e', 'f' }, { 'g', 'h', 'i' }, { 'j', 'k', 'l' }, { 'm', 'n', 'o' }, { 'p', 'q', 'r', 's'}, { 't', 'u', 'v' }, { 'w', 'x', 'y', 'z'} }; // Given input array int input[] = { 2, 3, 4 }; // Size of the array int n = sizeof(input)/sizeof(input[0]); // Function call to find all combinations findCombinations(keypad, input, string(\"\"), 0, n ); return 0;}",
"e": 29340,
"s": 27909,
"text": null
},
{
"code": "#include <stdio.h>#include <string.h> // hashTable[i] stores all characters that correspond to// digit i in phoneconst char hashTable[10][5] = { \"\", \"\", \"abc\", \"def\", \"ghi\", \"jkl\", \"mno\", \"pqrs\", \"tuv\", \"wxyz\" }; // A recursive function to print all possible words that can// be obtained by input number[] of size n. The output// words are one by one stored in output[]void printWordsUtil(int number[], int curr_digit, char output[], int n){ // Base case, if current output word is prepared int i; if (curr_digit == n) { printf(\"%s \", output); return; } // Try all 3 possible characters for current digit in // number[] and recur for remaining digits for (i = 0; i < strlen(hashTable[number[curr_digit]]); i++) { output[curr_digit] = hashTable[number[curr_digit]][i]; printWordsUtil(number, curr_digit + 1, output, n); if (number[curr_digit] == 0 || number[curr_digit] == 1) return; }} // A wrapper over printWordsUtil(). It creates an output// array and calls printWordsUtil()void printWords(int number[], int n){ char result[n + 1]; result[n] = '\\0'; printWordsUtil(number, 0, result, n);} // Driver programint main(void){ int number[] = { 2, 3, 4 }; int n = sizeof(number) / sizeof(number[0]); printWords(number, n); return 0;}",
"e": 30731,
"s": 29340,
"text": null
},
{
"code": "// Java program to implement the// above approachimport java.util.*;import java.lang.*;import java.io.*;class NumberPadString{ static Character[][] numberToCharMap; private static List<String> printWords(int[] numbers, int len, int numIndex, String s){ if(len == numIndex) { return new ArrayList<>(Collections.singleton(s)); } List<String> stringList = new ArrayList<>(); for(int i = 0; i < numberToCharMap[numbers[numIndex]].length; i++) { String sCopy = String.copyValueOf(s.toCharArray()); sCopy = sCopy.concat( numberToCharMap[numbers[numIndex]][i].toString()); stringList.addAll(printWords(numbers, len, numIndex + 1, sCopy)); } return stringList;} private static void printWords(int[] numbers){ generateNumberToCharMap(); List<String> stringList = printWords(numbers, numbers.length, 0, \"\"); stringList.stream().forEach(System.out :: println);} private static void generateNumberToCharMap(){ numberToCharMap = new Character[10][5]; numberToCharMap[0] = new Character[]{'\\0'}; numberToCharMap[1] = new Character[]{'\\0'}; numberToCharMap[2] = new Character[]{'a','b','c'}; numberToCharMap[3] = new Character[]{'d','e','f'}; numberToCharMap[4] = new Character[]{'g','h','i'}; numberToCharMap[5] = new Character[]{'j','k','l'}; numberToCharMap[6] = new Character[]{'m','n','o'}; numberToCharMap[7] = new Character[]{'p','q','r','s'}; numberToCharMap[8] = new Character[]{'t','u','v'}; numberToCharMap[9] = new Character[]{'w','x','y','z'};} // Driver code public static void main(String[] args){ int number[] = {2, 3, 4}; printWords(number);}} // This code is contributed by ankit pachori 1",
"e": 32589,
"s": 30731,
"text": null
},
{
"code": "# hashTable[i] stores all characters# that correspond to digit i in phonehashTable = [\"\", \"\", \"abc\", \"def\", \"ghi\", \"jkl\", \"mno\", \"pqrs\", \"tuv\", \"wxyz\"] # A recursive function to print all# possible words that can be obtained# by input number[] of size n. The# output words are one by one stored# in output[] def printWordsUtil(number, curr, output, n): if(curr == n): print(output) return # Try all 3 possible characters # for current digit in number[] # and recur for remaining digits for i in range(len(hashTable[number[curr]])): output.append(hashTable[number[curr]][i]) printWordsUtil(number, curr + 1, output, n) output.pop() if(number[curr] == 0 or number[curr] == 1): return # A wrapper over printWordsUtil().# It creates an output array and# calls printWordsUtil() def printWords(number, n): printWordsUtil(number, 0, [], n) # Driver functionif __name__ == '__main__': number = [2, 3, 4] n = len(number) printWords(number, n) # This code is contributed by prajmsidc",
"e": 33659,
"s": 32589,
"text": null
},
{
"code": "<script> // Javascript program to implement the// above approachlet hashTable = [ \"\", \"\", \"abc\", \"def\", \"ghi\", \"jkl\", \"mno\", \"pqrs\", \"tuv\", \"wxyz\" ]; // A recursive function to print all possible// words that can be obtained by input number[]// of size n. The output words are one by one// stored in output[]function printWordsUtil(number, curr, output, n){ // Base case, if current output // word is prepared if (curr == n) { document.write(output.join(\"\") + \"<br>\") return; } // Try all 3 possible characters for current // digit in number[] and recur for remaining digits for(let i = 0; i < hashTable[number[curr]].length; i++) { output.push(hashTable[number[curr]][i]); printWordsUtil(number, curr + 1, output, n); output.pop(); if(number[curr] == 0 || number[curr] == 1) return }} // A wrapper over printWordsUtil(). It creates// an output array and calls printWordsUtil()function printWords(numbers, n){ printWordsUtil(number, 0, [], n);} // Driver codelet number = [ 2, 3, 4 ];let n = number.length; printWords(number, n); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 34932,
"s": 33659,
"text": null
},
{
"code": null,
"e": 34941,
"s": 34932,
"text": "Output: "
},
{
"code": null,
"e": 35130,
"s": 34941,
"text": "adg adh adi aeg aeh aei afg afh afi bdg \nbdh bdi beg beh bei bfg bfh bfi cdg cdh \ncdi ceg ceh cei cfg cfh cfi\nProcess returned 0 (0x0) execution time : 0.025 s\nPress any key to continue."
},
{
"code": null,
"e": 35153,
"s": 35130,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 35608,
"s": 35153,
"text": "Time Complexity: O(4n), where n is a number of digits in the input number. Each digit of a number has 3 or 4 alphabets, so it can be said that each digit has 4 alphabets as options. If there are n digits then there are 4 options for the first digit and for each alphabet of the first digit there are 4 options in the second digit, i.e for every recursion 4 more recursions are called (if it does not match the base case). So the time complexity is O(4n)."
},
{
"code": null,
"e": 35660,
"s": 35608,
"text": "Space Complexity:O(1). As no extra space is needed."
},
{
"code": null,
"e": 35942,
"s": 35660,
"text": "Reference: Buy Programming Interviews Exposed: Secrets to Landing Your Next Job 3rd Edition from Flipkart.comThis article is contributed by Jitendra Sangar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 35965,
"s": 35942,
"text": "ABHISHEKSINGH15BCE1009"
},
{
"code": null,
"e": 35975,
"s": 35965,
"text": "prajmsidc"
},
{
"code": null,
"e": 35986,
"s": 35975,
"text": "andrew1234"
},
{
"code": null,
"e": 36002,
"s": 35986,
"text": "ankit pachori 1"
},
{
"code": null,
"e": 36008,
"s": 36002,
"text": "pawki"
},
{
"code": null,
"e": 36029,
"s": 36008,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 36039,
"s": 36029,
"text": "vinod0808"
},
{
"code": null,
"e": 36052,
"s": 36039,
"text": "simmytarika5"
},
{
"code": null,
"e": 36061,
"s": 36052,
"text": "Accolite"
},
{
"code": null,
"e": 36068,
"s": 36061,
"text": "Amazon"
},
{
"code": null,
"e": 36077,
"s": 36068,
"text": "Flipkart"
},
{
"code": null,
"e": 36087,
"s": 36077,
"text": "OYO Rooms"
},
{
"code": null,
"e": 36100,
"s": 36087,
"text": "phone-keypad"
},
{
"code": null,
"e": 36108,
"s": 36100,
"text": "Samsung"
},
{
"code": null,
"e": 36117,
"s": 36108,
"text": "Snapdeal"
},
{
"code": null,
"e": 36122,
"s": 36117,
"text": "Zoho"
},
{
"code": null,
"e": 36129,
"s": 36122,
"text": "Arrays"
},
{
"code": null,
"e": 36142,
"s": 36129,
"text": "Mathematical"
},
{
"code": null,
"e": 36152,
"s": 36142,
"text": "Recursion"
},
{
"code": null,
"e": 36160,
"s": 36152,
"text": "Strings"
},
{
"code": null,
"e": 36165,
"s": 36160,
"text": "Zoho"
},
{
"code": null,
"e": 36174,
"s": 36165,
"text": "Flipkart"
},
{
"code": null,
"e": 36183,
"s": 36174,
"text": "Accolite"
},
{
"code": null,
"e": 36190,
"s": 36183,
"text": "Amazon"
},
{
"code": null,
"e": 36200,
"s": 36190,
"text": "OYO Rooms"
},
{
"code": null,
"e": 36208,
"s": 36200,
"text": "Samsung"
},
{
"code": null,
"e": 36217,
"s": 36208,
"text": "Snapdeal"
},
{
"code": null,
"e": 36224,
"s": 36217,
"text": "Arrays"
},
{
"code": null,
"e": 36232,
"s": 36224,
"text": "Strings"
},
{
"code": null,
"e": 36245,
"s": 36232,
"text": "Mathematical"
},
{
"code": null,
"e": 36255,
"s": 36245,
"text": "Recursion"
},
{
"code": null,
"e": 36353,
"s": 36255,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36362,
"s": 36353,
"text": "Comments"
},
{
"code": null,
"e": 36375,
"s": 36362,
"text": "Old Comments"
},
{
"code": null,
"e": 36423,
"s": 36375,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 36467,
"s": 36423,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 36490,
"s": 36467,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 36522,
"s": 36490,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 36536,
"s": 36522,
"text": "Linear Search"
},
{
"code": null,
"e": 36566,
"s": 36536,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 36626,
"s": 36566,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 36641,
"s": 36626,
"text": "C++ Data Types"
},
{
"code": null,
"e": 36684,
"s": 36641,
"text": "Set in C++ Standard Template Library (STL)"
}
]
|
Analysis of Algorithms (Recurrences) - GeeksforGeeks | 21 May, 2019
T(n) = T(n/4) + T(n/2) + cn2
T(1) = c
T(0) = 0
cn^2
/ \
T(n/4) T(n/2)
cn^2
/ \
c (n^2)/16 c(n^2)/4
/ \ / \
T(n/16) T(n/8) T(n/8) T(n/4)
cn^2
/ \
c(n^2)/16 c(n^2)/4
/ \ / \
c(n^2)/256 c(n^2)/64 c(n^2)/64 c(n^2)/16
/ \ / \ / \ / \
C1
/ \
T(n-1) T(n-1)
C1
/ \
C1 C1
/ \ / \
T(n-2) T(n-2) T(n-2) T(n-2)
C1
/ \
C1 C1
/ \ / \
C1 C1 C1 C1
/ \ / \ / \ / \
If we sum the above tree level by level, we get the following series
T(n) = C1 + 2C1 + 4C1 + 8C1 + ...
The above series is Geometrical progression and there will be n terms in it.
So T(n) = O(2^n)
Let n = 2^m
T(2^m) = T(2^(m/2)) + 1
Let T(2^m) = S(m)
S(m) = 2S(m/2) + 1
S(m) = (m)
= (logn) /* Since n = 2^m */
T(n) = T(2^m) = S(m)
= (Logn)
if n <= 3 then T(n) = n
else T(n) = T(n/3) + cn
T(n) = cn + T(n/3)
= cn + cn/3 + T(n/9)
= cn + cn/3 + cn/9 + T(n/27)
Taking the sum of infinite GP series. The value of T(n) will
be less than this sum.
T(n) <= cn(1/(1-1/3))
<= 3cn/2
or we can say
cn <= T(n) <= 3cn/2
Therefore T(n) = (n)
Procedure A(n)
If n <= 2 return(1) else return A();
What is the time complexity of the following recursive function:
c
(A) (n) (B) (nlogn)(C) (logn)(D) (loglogn)
C
D
B
A
Recursive relation for the DoSomething() is
T(n) = T() + C1 if n > 2
We have ignored the floor() part as it doesn't matter here if it's a floor or ceiling.
Let n = 2^m, T(n) = T(2^m)
Let T(2^m) = S(m)
From the above two, T(n) = S(m)
S(m) = S(m/2) + C1 /* This is simply binary search recursion*/
S(m) = O(logm)
= O(loglogn) /* Since n = 2^m */
Now, let us go back to the original recursive function T(n)
T(n) = S(m)
= O(LogLogn)
T(n) = 2T(n-1) + c
T(1) = c1.
T(n) = 2(2T(n-2) + c) + c = 4T(n-2) + 3c
T(n) = 8T(n-3) + 6c + c = 8T(n-3) + 7c
T(n) = 16T(n-4) + 14c + c = 16T(n-4) + 15c
............................................................
.............................................................
T(n) = (2^(n-1))T(1) + (2^(n-1) - 1)c
T(n) = O(2^n)
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Comments
Old Comments
Difference between sh and bash
What is "network ID" and "host ID" in IP Addresses?
Primer CSS Flexbox Flex Direction
Converting an image to a Torch Tensor in Python
Prime CSS Marketing Buttons Animated Arrow Symbol
How to Calculate Cosine Similarity in Python?
Python Program for Breadth First Search or BFS for a Graph
10 Best C and C++ Books For Beginners & Advanced Programmers
Show all columns of Pandas DataFrame in Jupyter Notebook
How to split a Dataset into Train and Test Sets using Python | [
{
"code": null,
"e": 34412,
"s": 34384,
"text": "\n21 May, 2019"
},
{
"code": null,
"e": 34460,
"s": 34412,
"text": "\nT(n) = T(n/4) + T(n/2) + cn2\nT(1) = c\nT(0) = 0"
},
{
"code": null,
"e": 34518,
"s": 34460,
"text": " cn^2\n / \\\n T(n/4) T(n/2)\n"
},
{
"code": null,
"e": 34675,
"s": 34518,
"text": " cn^2\n / \\ \n c (n^2)/16 c(n^2)/4\n / \\ / \\\n T(n/16) T(n/8) T(n/8) T(n/4) \n"
},
{
"code": null,
"e": 34902,
"s": 34675,
"text": " cn^2\n / \\ \n c(n^2)/16 c(n^2)/4\n / \\ / \\\nc(n^2)/256 c(n^2)/64 c(n^2)/64 c(n^2)/16\n / \\ / \\ / \\ / \\ \n \n\n"
},
{
"code": null,
"e": 35503,
"s": 34902,
"text": " C1\n / \\\n T(n-1) T(n-1) \n\n\n C1\n / \\\n C1 C1\n / \\ / \\\n T(n-2) T(n-2) T(n-2) T(n-2)\n\n C1\n / \\\n C1 C1\n / \\ / \\\n C1 C1 C1 C1\n / \\ / \\ / \\ / \\\n\n \nIf we sum the above tree level by level, we get the following series\nT(n) = C1 + 2C1 + 4C1 + 8C1 + ...\nThe above series is Geometrical progression and there will be n terms in it.\nSo T(n) = O(2^n) \n"
},
{
"code": null,
"e": 35589,
"s": 35503,
"text": " Let n = 2^m\n T(2^m) = T(2^(m/2)) + 1\n Let T(2^m) = S(m)\n S(m) = 2S(m/2) + 1 \n"
},
{
"code": null,
"e": 35640,
"s": 35589,
"text": "S(m) = (m) \n = (logn) /* Since n = 2^m */\n"
},
{
"code": null,
"e": 35691,
"s": 35640,
"text": " T(n) = T(2^m) = S(m)\n = (Logn)\n"
},
{
"code": null,
"e": 35752,
"s": 35691,
"text": " if n <= 3 then T(n) = n\n else T(n) = T(n/3) + cn\n"
},
{
"code": null,
"e": 36009,
"s": 35752,
"text": "T(n) = cn + T(n/3)\n = cn + cn/3 + T(n/9)\n = cn + cn/3 + cn/9 + T(n/27)\nTaking the sum of infinite GP series. The value of T(n) will\nbe less than this sum.\nT(n) <= cn(1/(1-1/3))\n <= 3cn/2\n\nor we can say \ncn <= T(n) <= 3cn/2\nTherefore T(n) = (n)\n"
},
{
"code": null,
"e": 36068,
"s": 36009,
"text": " Procedure A(n) \n If n <= 2 return(1) else return A();\n"
},
{
"code": null,
"e": 36135,
"s": 36068,
"text": "What is the time complexity of the following recursive function: "
},
{
"code": null,
"e": 36137,
"s": 36135,
"text": "c"
},
{
"code": null,
"e": 36181,
"s": 36137,
"text": "(A) (n) (B) (nlogn)(C) (logn)(D) (loglogn) "
},
{
"code": null,
"e": 36183,
"s": 36181,
"text": "C"
},
{
"code": null,
"e": 36185,
"s": 36183,
"text": "D"
},
{
"code": null,
"e": 36187,
"s": 36185,
"text": "B"
},
{
"code": null,
"e": 36189,
"s": 36187,
"text": "A"
},
{
"code": null,
"e": 36235,
"s": 36189,
"text": "Recursive relation for the DoSomething() is "
},
{
"code": null,
"e": 36265,
"s": 36235,
"text": " T(n) = T() + C1 if n > 2 "
},
{
"code": null,
"e": 36354,
"s": 36265,
"text": "We have ignored the floor() part as it doesn't matter here if it's a floor or ceiling. "
},
{
"code": null,
"e": 36680,
"s": 36354,
"text": " Let n = 2^m, T(n) = T(2^m)\n Let T(2^m) = S(m)\n\n From the above two, T(n) = S(m)\n\n S(m) = S(m/2) + C1 /* This is simply binary search recursion*/\n S(m) = O(logm) \n = O(loglogn) /* Since n = 2^m */\n \n Now, let us go back to the original recursive function T(n) \n T(n) = S(m) \n = O(LogLogn)"
},
{
"code": null,
"e": 36716,
"s": 36682,
"text": " T(n) = 2T(n-1) + c\n T(1) = c1."
},
{
"code": null,
"e": 37055,
"s": 36716,
"text": " T(n) = 2(2T(n-2) + c) + c = 4T(n-2) + 3c\n T(n) = 8T(n-3) + 6c + c = 8T(n-3) + 7c\n T(n) = 16T(n-4) + 14c + c = 16T(n-4) + 15c\n ............................................................\n .............................................................\n T(n) = (2^(n-1))T(1) + (2^(n-1) - 1)c\n\n T(n) = O(2^n)"
},
{
"code": null,
"e": 37153,
"s": 37055,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 37162,
"s": 37153,
"text": "Comments"
},
{
"code": null,
"e": 37175,
"s": 37162,
"text": "Old Comments"
},
{
"code": null,
"e": 37206,
"s": 37175,
"text": "Difference between sh and bash"
},
{
"code": null,
"e": 37258,
"s": 37206,
"text": "What is \"network ID\" and \"host ID\" in IP Addresses?"
},
{
"code": null,
"e": 37292,
"s": 37258,
"text": "Primer CSS Flexbox Flex Direction"
},
{
"code": null,
"e": 37340,
"s": 37292,
"text": "Converting an image to a Torch Tensor in Python"
},
{
"code": null,
"e": 37390,
"s": 37340,
"text": "Prime CSS Marketing Buttons Animated Arrow Symbol"
},
{
"code": null,
"e": 37436,
"s": 37390,
"text": "How to Calculate Cosine Similarity in Python?"
},
{
"code": null,
"e": 37495,
"s": 37436,
"text": "Python Program for Breadth First Search or BFS for a Graph"
},
{
"code": null,
"e": 37556,
"s": 37495,
"text": "10 Best C and C++ Books For Beginners & Advanced Programmers"
},
{
"code": null,
"e": 37613,
"s": 37556,
"text": "Show all columns of Pandas DataFrame in Jupyter Notebook"
}
]
|
Count the Number of Binary Search Trees present in a Binary Tree in C++ | We are given a binary tree as input. The goal is to find the number of binary search trees (BSTs) present as subtrees inside it. A BST is a binary tree with left child less than root and right child more than the root.
For Example
The tree which will be created after inputting the values is given below −
Count the Number of Binary Search Trees present in a Binary Tree are: 2
we are given with an array of integer values that is used to form a binary tree and we will check whether there is a binary search tree present in it. Every root node represents the binary search tree so in the given binary tree we can see that there is no other binary search tree present therefore the count is 2 which is the total number of leaf nodes in a binary tree.
The tree which will be created after inputting the values is given below −
Count the Number of Binary Search Trees present in a Binary Tree are: 6
we are given with an array of integer values that is used to form a binary
tree and we will check whether there is a binary search tree present in it. Every root
node represents the binary search tree so in the given binary tree we can see that there
are 4 leaf nodes and two subtrees which are forming the BST therefore the count is 6.
Approach used in the below program is as follows −
In this approach we will find the largest value of the node in the left subtree of node N and check if it is less than N. Also, we will find the smallest value in the right subtree of node N and check if it is more than N. If true, then it is a BST.
Traverse the binary tree in bottom up manner and check above conditions and
increment count of BSTs
The node of every node_data contains the information like number of BSTs
present, maximum value in that tree, minimum value, boolean true if that subtree
is a BST.
The node of every node_data contains the information like number of BSTs
present, maximum value in that tree, minimum value, boolean true if that subtree
is a BST.
Function BST_present(struct tree_node* parent) finds the count of BSTs present
inside the binary tree rooted at parent.
Function BST_present(struct tree_node* parent) finds the count of BSTs present
inside the binary tree rooted at parent.
If the parent is NULL then return { 0, min, max, true } where min is INT-MIN and
max is INT_MAX.
If the parent is NULL then return { 0, min, max, true } where min is INT-MIN and
max is INT_MAX.
If left and right childs are null then return { 1, parent−>data, parent−>data, true }
If left and right childs are null then return { 1, parent−>data, parent−>data, true }
Set node_data Left = BST_present(parent−>left); and node_data Right =
BST_present(parent−>right);
Set node_data Left = BST_present(parent−>left); and node_data Right =
BST_present(parent−>right);
Take node n1 and set n1.lowest = min(parent−>data, (min(Left.lowest,
Right.lowest))) as lowest in its right subtree.
Take node n1 and set n1.lowest = min(parent−>data, (min(Left.lowest,
Right.lowest))) as lowest in its right subtree.
Set n1.highest = max(parent−>data, (max(Left.highest, Right.highest))); as highest in its left subtree.
Set n1.highest = max(parent−>data, (max(Left.highest, Right.highest))); as highest in its left subtree.
if(Left.check && Right.check && parent−>data > Left.highest && parent−>data <Right.lowest) returns true then set n1.check = true as it is a BST.
if(Left.check && Right.check && parent−>data > Left.highest && parent−>data <Right.lowest) returns true then set n1.check = true as it is a BST.
Increase count of bsts as n1.total_bst = 1 + Left.total_bst + Right.total_bst;
Increase count of bsts as n1.total_bst = 1 + Left.total_bst + Right.total_bst;
Otherwise set n1.check = false and count as n1.total_bst = Left.total_bst +
Right.total_bst.
Otherwise set n1.check = false and count as n1.total_bst = Left.total_bst +
Right.total_bst.
At the end return n1.
At the end return n1.
Live Demo
#include <bits/stdc++.h>
using namespace std;
struct tree_node{
struct tree_node* left;
struct tree_node* right;
int data;
tree_node(int data){
this−>data = data;
this−>left = NULL;
this−>right = NULL;
}
};
struct node_data{
int total_bst;
int highest, lowest;
bool check;
};
node_data BST_present(struct tree_node* parent){
if(parent == NULL){
int max = INT_MAX;
int min = INT_MIN;
return { 0, min, max, true };
}
if(parent−>left == NULL){
if(parent−>right == NULL){
return { 1, parent−>data, parent−>data, true };
}
}
node_data Left = BST_present(parent−>left);
node_data Right = BST_present(parent−>right);
node_data n1;
n1.lowest = min(parent−>data, (min(Left.lowest, Right.lowest)));
n1.highest = max(parent−>data, (max(Left.highest, Right.highest)));
if(Left.check && Right.check && parent−>data > Left.highest && parent−>data < Right.lowest){
n1.check = true;
n1.total_bst = 1 + Left.total_bst + Right.total_bst;
} else{
n1.check = false;
n1.total_bst = Left.total_bst + Right.total_bst;
}
return n1;
}
int main(){
struct tree_node* root = new tree_node(3);
root−>left = new tree_node(7);
root−>right = new tree_node(4);
root−>left−>left = new tree_node(5);
root−>right−>right = new tree_node(1);
root−>left−>left−>left = new tree_node(10);
cout<<"Count the Number of Binary Search Trees present in a Binary Tree are: "<<BST_present(root).total_bst;
return 0;
}
If we run the above code it will generate the following output −
Count the Number of Binary Search Trees present in a Binary Tree are: 2 | [
{
"code": null,
"e": 1281,
"s": 1062,
"text": "We are given a binary tree as input. The goal is to find the number of binary search trees (BSTs) present as subtrees inside it. A BST is a binary tree with left child less than root and right child more than the root."
},
{
"code": null,
"e": 1293,
"s": 1281,
"text": "For Example"
},
{
"code": null,
"e": 1368,
"s": 1293,
"text": "The tree which will be created after inputting the values is given below −"
},
{
"code": null,
"e": 1440,
"s": 1368,
"text": "Count the Number of Binary Search Trees present in a Binary Tree are: 2"
},
{
"code": null,
"e": 1813,
"s": 1440,
"text": "we are given with an array of integer values that is used to form a binary tree and we will check whether there is a binary search tree present in it. Every root node represents the binary search tree so in the given binary tree we can see that there is no other binary search tree present therefore the count is 2 which is the total number of leaf nodes in a binary tree."
},
{
"code": null,
"e": 1888,
"s": 1813,
"text": "The tree which will be created after inputting the values is given below −"
},
{
"code": null,
"e": 1960,
"s": 1888,
"text": "Count the Number of Binary Search Trees present in a Binary Tree are: 6"
},
{
"code": null,
"e": 2297,
"s": 1960,
"text": "we are given with an array of integer values that is used to form a binary\ntree and we will check whether there is a binary search tree present in it. Every root\nnode represents the binary search tree so in the given binary tree we can see that there\nare 4 leaf nodes and two subtrees which are forming the BST therefore the count is 6."
},
{
"code": null,
"e": 2348,
"s": 2297,
"text": "Approach used in the below program is as follows −"
},
{
"code": null,
"e": 2698,
"s": 2348,
"text": "In this approach we will find the largest value of the node in the left subtree of node N and check if it is less than N. Also, we will find the smallest value in the right subtree of node N and check if it is more than N. If true, then it is a BST.\nTraverse the binary tree in bottom up manner and check above conditions and\nincrement count of BSTs"
},
{
"code": null,
"e": 2862,
"s": 2698,
"text": "The node of every node_data contains the information like number of BSTs\npresent, maximum value in that tree, minimum value, boolean true if that subtree\nis a BST."
},
{
"code": null,
"e": 3026,
"s": 2862,
"text": "The node of every node_data contains the information like number of BSTs\npresent, maximum value in that tree, minimum value, boolean true if that subtree\nis a BST."
},
{
"code": null,
"e": 3146,
"s": 3026,
"text": "Function BST_present(struct tree_node* parent) finds the count of BSTs present\ninside the binary tree rooted at parent."
},
{
"code": null,
"e": 3266,
"s": 3146,
"text": "Function BST_present(struct tree_node* parent) finds the count of BSTs present\ninside the binary tree rooted at parent."
},
{
"code": null,
"e": 3363,
"s": 3266,
"text": "If the parent is NULL then return { 0, min, max, true } where min is INT-MIN and\nmax is INT_MAX."
},
{
"code": null,
"e": 3460,
"s": 3363,
"text": "If the parent is NULL then return { 0, min, max, true } where min is INT-MIN and\nmax is INT_MAX."
},
{
"code": null,
"e": 3546,
"s": 3460,
"text": "If left and right childs are null then return { 1, parent−>data, parent−>data, true }"
},
{
"code": null,
"e": 3632,
"s": 3546,
"text": "If left and right childs are null then return { 1, parent−>data, parent−>data, true }"
},
{
"code": null,
"e": 3730,
"s": 3632,
"text": "Set node_data Left = BST_present(parent−>left); and node_data Right =\nBST_present(parent−>right);"
},
{
"code": null,
"e": 3828,
"s": 3730,
"text": "Set node_data Left = BST_present(parent−>left); and node_data Right =\nBST_present(parent−>right);"
},
{
"code": null,
"e": 3945,
"s": 3828,
"text": "Take node n1 and set n1.lowest = min(parent−>data, (min(Left.lowest,\nRight.lowest))) as lowest in its right subtree."
},
{
"code": null,
"e": 4062,
"s": 3945,
"text": "Take node n1 and set n1.lowest = min(parent−>data, (min(Left.lowest,\nRight.lowest))) as lowest in its right subtree."
},
{
"code": null,
"e": 4166,
"s": 4062,
"text": "Set n1.highest = max(parent−>data, (max(Left.highest, Right.highest))); as highest in its left subtree."
},
{
"code": null,
"e": 4270,
"s": 4166,
"text": "Set n1.highest = max(parent−>data, (max(Left.highest, Right.highest))); as highest in its left subtree."
},
{
"code": null,
"e": 4415,
"s": 4270,
"text": "if(Left.check && Right.check && parent−>data > Left.highest && parent−>data <Right.lowest) returns true then set n1.check = true as it is a BST."
},
{
"code": null,
"e": 4560,
"s": 4415,
"text": "if(Left.check && Right.check && parent−>data > Left.highest && parent−>data <Right.lowest) returns true then set n1.check = true as it is a BST."
},
{
"code": null,
"e": 4639,
"s": 4560,
"text": "Increase count of bsts as n1.total_bst = 1 + Left.total_bst + Right.total_bst;"
},
{
"code": null,
"e": 4718,
"s": 4639,
"text": "Increase count of bsts as n1.total_bst = 1 + Left.total_bst + Right.total_bst;"
},
{
"code": null,
"e": 4811,
"s": 4718,
"text": "Otherwise set n1.check = false and count as n1.total_bst = Left.total_bst +\nRight.total_bst."
},
{
"code": null,
"e": 4904,
"s": 4811,
"text": "Otherwise set n1.check = false and count as n1.total_bst = Left.total_bst +\nRight.total_bst."
},
{
"code": null,
"e": 4926,
"s": 4904,
"text": "At the end return n1."
},
{
"code": null,
"e": 4948,
"s": 4926,
"text": "At the end return n1."
},
{
"code": null,
"e": 4959,
"s": 4948,
"text": " Live Demo"
},
{
"code": null,
"e": 6496,
"s": 4959,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nstruct tree_node{\n struct tree_node* left;\n struct tree_node* right;\n int data;\n tree_node(int data){\n this−>data = data;\n this−>left = NULL;\n this−>right = NULL;\n }\n};\nstruct node_data{\n int total_bst;\n int highest, lowest;\n bool check;\n};\nnode_data BST_present(struct tree_node* parent){\n if(parent == NULL){\n int max = INT_MAX;\n int min = INT_MIN;\n return { 0, min, max, true };\n }\n if(parent−>left == NULL){\n if(parent−>right == NULL){\n return { 1, parent−>data, parent−>data, true };\n }\n }\n node_data Left = BST_present(parent−>left);\n node_data Right = BST_present(parent−>right);\n node_data n1;\n n1.lowest = min(parent−>data, (min(Left.lowest, Right.lowest)));\n n1.highest = max(parent−>data, (max(Left.highest, Right.highest)));\n if(Left.check && Right.check && parent−>data > Left.highest && parent−>data < Right.lowest){\n n1.check = true;\n n1.total_bst = 1 + Left.total_bst + Right.total_bst;\n } else{\n n1.check = false;\n n1.total_bst = Left.total_bst + Right.total_bst;\n }\n return n1;\n}\nint main(){\n struct tree_node* root = new tree_node(3);\n root−>left = new tree_node(7);\n root−>right = new tree_node(4);\n root−>left−>left = new tree_node(5);\n root−>right−>right = new tree_node(1);\n root−>left−>left−>left = new tree_node(10);\n cout<<\"Count the Number of Binary Search Trees present in a Binary Tree are: \"<<BST_present(root).total_bst;\n return 0;\n}"
},
{
"code": null,
"e": 6561,
"s": 6496,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 6633,
"s": 6561,
"text": "Count the Number of Binary Search Trees present in a Binary Tree are: 2"
}
]
|
Automatically Detect COVID-19 Misinformation | by Susan Li | Towards Data Science | It’s not easy for ordinary citizens to identify fake news. And fake coronavirus news is no exception.
As part of an effort to combat misinformation about coronavirus, I tried and collected training data and trained a ML model to detect fake news on coronavirus.
My training data is not perfect, but I hope it will be useful to help us understand whether fake news differs systematically from real news in style and language use. So, let’s find out.
As mentioned in the previous article, I collected over 1,100 news articles and social network posts on COVID-19 from a variety of new sources, then labeled them. The data set can be found here.
I decided to created several dozens of new features based on news titles and news article bodies. Let me explain them one by one.
Count the number of capital letters in each title.
Compute the percentage of capital letters in each article body rather than simply counting the number, because the length of the articles are very different.
On average, fake news have way more words that appear in capital letters in the title.This makes me to think that fake news is targeting audiences who are likely to be influenced by titles.
Count the number of stop words in each title.
Compute the percentage of stop words in each article body rather than simply counting the number, because the length of the articles are very different.
Fake news titles have fewer stop-words than those of real news.
Count number of proper nouns (NNP) in each title.
Fake news titles have more proper nouns. Apparently the use of proper nouns in titles are very significant in differentiating fake from real.
Overall, these results suggest that the writers of fake news are attempting to attracting attention by using all capitalized words in titles, and squeeze as much substance into the titles as possible by skipping stop-words and increase proper nouns. We will find out whether these apply to article bodies as well shortly.
Here is an example of fake news title vs. real news title.
Fake news title: “FULL TRANSCRIPT OF “SMOKING GUN” BOMBSHELL INTERVIEW: PROF. FRANCES BOYLE EXPOSES THE BIOWEAPONS ORIGINS OF THE COVID-19 CORONAVIRUS”
Real news title: “Why outbreaks like coronavirus spread exponentially, and how to ‘flatten the curve’”
To study fake and real news articles, we compute many content based features on the article bodies. They are:
Use part-of-speech tagger and keep a count of how many times each tag appears in the article.
Number of negations, interrogatives in the article body.
Use a Python library — textstat to calculate statistics from text to determine readability, complexity and grade level of any article. The explanation of each statistical feature value can be found here.
Type-Token Ratio (TTR), is the total number of unique words (types) divided by the total number of words (tokens) in a given segment of language. Using a Python library — lexicalrichness.
Number of power words, casual words, tentative words, emotion words in the article body.
Capital Letters in Article Body
On average, fake news have more words that appear in capital letters in the article body than those of real news.
Stop Words in Article Body
It seems there isn’t a significant difference on the percentage of stop words in article text between fake news and real news.
NNP (Proper noun, singular) in Article Body
Similar with the titles, fake news pack more proper nouns in the article bodies as well.
Negation Words in Article Bodies
On average, fake news have a little more negation words than the real ones.
Bracket
For some reason, in my data, fake news pack more brackets in the article bodies.
Type-Token Ratio (TTR)
There does not seem to be a significant difference between fake news and real news in terms of TTR.
I did not explore all the numeric features, feel free to do yourself. However, from what I have explored, I found that fake news articles differ much more in their titles than in their text bodies.
Remember, Natural News is a far-right conspiracy theory and fake news website. All the news articles I collected from there are labeled as fake news.
Within the expectation, Natural News articles use a lot less stop words than Harvard Health Publishing.
TTR is meant to capture the lexical diversity of the vocabulary in a document. A low TTR means a document has more word redundancy and a high TTR means a document has more word diversity. Its clear that there is a big difference between Harvard Health Publish and Natural News in terms of TTR.
We will not use “source” as a feature due to the bias of my data collection, for example, I only collected fake posts from Facebook and Twitter. While in reality, most of posts in Facebook or Twitter are real.
I am sure you have noticed that we have created a large number of numeric features. For the first attempt, I decided to use all of them to fit a a Support Vector Machine (SVM) model with a linear kernel and 10-fold cross-validation to prevent overfitting.
print(scores.mean())
When 10-fold cross validation is done we can see 10 different score in each iteration, and then we compute the mean score.
Take all the values of C parameter and check out the accuracy score.
From the above plot we can see that accuracy is close to 84.2% for C=1 and then it drops around 83.8% and remains constant.
We will look into more details of what is the exact value of C parameter that is giving us a good accuracy score.
The above plot shows that accuracy score is the highest for C=0.7.
Remember I created several dozens of new numeric features, for the purpose of learning and exploring, and I used all of them to fit the classification model. I would suggest you to use a hypothesis testing method to select top 8 or top 10 features, then run a linear SVM model and 10-fold cross-validation.
The hypothesis testing can’t say anything about predicting classes in the data, however, these test can illustrate which features are more significant than the others.
Jupyter notebook can be found on Github. Have a great weekend! | [
{
"code": null,
"e": 274,
"s": 172,
"text": "It’s not easy for ordinary citizens to identify fake news. And fake coronavirus news is no exception."
},
{
"code": null,
"e": 434,
"s": 274,
"text": "As part of an effort to combat misinformation about coronavirus, I tried and collected training data and trained a ML model to detect fake news on coronavirus."
},
{
"code": null,
"e": 621,
"s": 434,
"text": "My training data is not perfect, but I hope it will be useful to help us understand whether fake news differs systematically from real news in style and language use. So, let’s find out."
},
{
"code": null,
"e": 815,
"s": 621,
"text": "As mentioned in the previous article, I collected over 1,100 news articles and social network posts on COVID-19 from a variety of new sources, then labeled them. The data set can be found here."
},
{
"code": null,
"e": 945,
"s": 815,
"text": "I decided to created several dozens of new features based on news titles and news article bodies. Let me explain them one by one."
},
{
"code": null,
"e": 996,
"s": 945,
"text": "Count the number of capital letters in each title."
},
{
"code": null,
"e": 1154,
"s": 996,
"text": "Compute the percentage of capital letters in each article body rather than simply counting the number, because the length of the articles are very different."
},
{
"code": null,
"e": 1344,
"s": 1154,
"text": "On average, fake news have way more words that appear in capital letters in the title.This makes me to think that fake news is targeting audiences who are likely to be influenced by titles."
},
{
"code": null,
"e": 1390,
"s": 1344,
"text": "Count the number of stop words in each title."
},
{
"code": null,
"e": 1543,
"s": 1390,
"text": "Compute the percentage of stop words in each article body rather than simply counting the number, because the length of the articles are very different."
},
{
"code": null,
"e": 1607,
"s": 1543,
"text": "Fake news titles have fewer stop-words than those of real news."
},
{
"code": null,
"e": 1657,
"s": 1607,
"text": "Count number of proper nouns (NNP) in each title."
},
{
"code": null,
"e": 1799,
"s": 1657,
"text": "Fake news titles have more proper nouns. Apparently the use of proper nouns in titles are very significant in differentiating fake from real."
},
{
"code": null,
"e": 2121,
"s": 1799,
"text": "Overall, these results suggest that the writers of fake news are attempting to attracting attention by using all capitalized words in titles, and squeeze as much substance into the titles as possible by skipping stop-words and increase proper nouns. We will find out whether these apply to article bodies as well shortly."
},
{
"code": null,
"e": 2180,
"s": 2121,
"text": "Here is an example of fake news title vs. real news title."
},
{
"code": null,
"e": 2332,
"s": 2180,
"text": "Fake news title: “FULL TRANSCRIPT OF “SMOKING GUN” BOMBSHELL INTERVIEW: PROF. FRANCES BOYLE EXPOSES THE BIOWEAPONS ORIGINS OF THE COVID-19 CORONAVIRUS”"
},
{
"code": null,
"e": 2435,
"s": 2332,
"text": "Real news title: “Why outbreaks like coronavirus spread exponentially, and how to ‘flatten the curve’”"
},
{
"code": null,
"e": 2545,
"s": 2435,
"text": "To study fake and real news articles, we compute many content based features on the article bodies. They are:"
},
{
"code": null,
"e": 2639,
"s": 2545,
"text": "Use part-of-speech tagger and keep a count of how many times each tag appears in the article."
},
{
"code": null,
"e": 2696,
"s": 2639,
"text": "Number of negations, interrogatives in the article body."
},
{
"code": null,
"e": 2900,
"s": 2696,
"text": "Use a Python library — textstat to calculate statistics from text to determine readability, complexity and grade level of any article. The explanation of each statistical feature value can be found here."
},
{
"code": null,
"e": 3088,
"s": 2900,
"text": "Type-Token Ratio (TTR), is the total number of unique words (types) divided by the total number of words (tokens) in a given segment of language. Using a Python library — lexicalrichness."
},
{
"code": null,
"e": 3177,
"s": 3088,
"text": "Number of power words, casual words, tentative words, emotion words in the article body."
},
{
"code": null,
"e": 3209,
"s": 3177,
"text": "Capital Letters in Article Body"
},
{
"code": null,
"e": 3323,
"s": 3209,
"text": "On average, fake news have more words that appear in capital letters in the article body than those of real news."
},
{
"code": null,
"e": 3350,
"s": 3323,
"text": "Stop Words in Article Body"
},
{
"code": null,
"e": 3477,
"s": 3350,
"text": "It seems there isn’t a significant difference on the percentage of stop words in article text between fake news and real news."
},
{
"code": null,
"e": 3521,
"s": 3477,
"text": "NNP (Proper noun, singular) in Article Body"
},
{
"code": null,
"e": 3610,
"s": 3521,
"text": "Similar with the titles, fake news pack more proper nouns in the article bodies as well."
},
{
"code": null,
"e": 3643,
"s": 3610,
"text": "Negation Words in Article Bodies"
},
{
"code": null,
"e": 3719,
"s": 3643,
"text": "On average, fake news have a little more negation words than the real ones."
},
{
"code": null,
"e": 3727,
"s": 3719,
"text": "Bracket"
},
{
"code": null,
"e": 3808,
"s": 3727,
"text": "For some reason, in my data, fake news pack more brackets in the article bodies."
},
{
"code": null,
"e": 3831,
"s": 3808,
"text": "Type-Token Ratio (TTR)"
},
{
"code": null,
"e": 3931,
"s": 3831,
"text": "There does not seem to be a significant difference between fake news and real news in terms of TTR."
},
{
"code": null,
"e": 4129,
"s": 3931,
"text": "I did not explore all the numeric features, feel free to do yourself. However, from what I have explored, I found that fake news articles differ much more in their titles than in their text bodies."
},
{
"code": null,
"e": 4279,
"s": 4129,
"text": "Remember, Natural News is a far-right conspiracy theory and fake news website. All the news articles I collected from there are labeled as fake news."
},
{
"code": null,
"e": 4383,
"s": 4279,
"text": "Within the expectation, Natural News articles use a lot less stop words than Harvard Health Publishing."
},
{
"code": null,
"e": 4677,
"s": 4383,
"text": "TTR is meant to capture the lexical diversity of the vocabulary in a document. A low TTR means a document has more word redundancy and a high TTR means a document has more word diversity. Its clear that there is a big difference between Harvard Health Publish and Natural News in terms of TTR."
},
{
"code": null,
"e": 4887,
"s": 4677,
"text": "We will not use “source” as a feature due to the bias of my data collection, for example, I only collected fake posts from Facebook and Twitter. While in reality, most of posts in Facebook or Twitter are real."
},
{
"code": null,
"e": 5143,
"s": 4887,
"text": "I am sure you have noticed that we have created a large number of numeric features. For the first attempt, I decided to use all of them to fit a a Support Vector Machine (SVM) model with a linear kernel and 10-fold cross-validation to prevent overfitting."
},
{
"code": null,
"e": 5164,
"s": 5143,
"text": "print(scores.mean())"
},
{
"code": null,
"e": 5287,
"s": 5164,
"text": "When 10-fold cross validation is done we can see 10 different score in each iteration, and then we compute the mean score."
},
{
"code": null,
"e": 5356,
"s": 5287,
"text": "Take all the values of C parameter and check out the accuracy score."
},
{
"code": null,
"e": 5480,
"s": 5356,
"text": "From the above plot we can see that accuracy is close to 84.2% for C=1 and then it drops around 83.8% and remains constant."
},
{
"code": null,
"e": 5594,
"s": 5480,
"text": "We will look into more details of what is the exact value of C parameter that is giving us a good accuracy score."
},
{
"code": null,
"e": 5661,
"s": 5594,
"text": "The above plot shows that accuracy score is the highest for C=0.7."
},
{
"code": null,
"e": 5968,
"s": 5661,
"text": "Remember I created several dozens of new numeric features, for the purpose of learning and exploring, and I used all of them to fit the classification model. I would suggest you to use a hypothesis testing method to select top 8 or top 10 features, then run a linear SVM model and 10-fold cross-validation."
},
{
"code": null,
"e": 6136,
"s": 5968,
"text": "The hypothesis testing can’t say anything about predicting classes in the data, however, these test can illustrate which features are more significant than the others."
}
]
|
Converting image to Grayscale without using any methods Java OpenCV. | To convert the colored image to grayscale.
Get the red green blue values of each pixel
Get the red green blue values of each pixel
Get the average of these 3 colors.
Get the average of these 3 colors.
Replace the RGB values with the average.
Replace the RGB values with the average.
Create a new pixel value from the modified colors.
Create a new pixel value from the modified colors.
Set the new value to the pixel.
Set the new value to the pixel.
import java.io.File;
import java.io.IOException;
import java.awt.Color;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class Color2Grey {
public static void main(String args[])throws IOException {
//Reading the image
File file= new File("D:\\Images\\car.jpg");
BufferedImage img = ImageIO.read(file);
for (int y = 0; y < img.getHeight(); y++) {
for (int x = 0; x < img.getWidth(); x++) {
//Retrieving the values of a pixel
int pixel = img.getRGB(x,y);
//Creating a Color object from pixel value
Color color = new Color(pixel, true);
//Retrieving the R G B values
int red = color.getRed();
int green = color.getGreen();
int blue = color.getBlue();
//Finding the average of the red green blue values
int average = (red+green+blue)/3;
//Creating new Color object
color = new Color(average, average, average);
//Setting new Color object to the image
img.setRGB(x, y, color.getRGB());
}
}
//Saving the modified image
file = new File("D:\\Images\\grey_image.jpg");
ImageIO.write(img, "jpg", file);
System.out.println("Done...");
}
} | [
{
"code": null,
"e": 1105,
"s": 1062,
"text": "To convert the colored image to grayscale."
},
{
"code": null,
"e": 1149,
"s": 1105,
"text": "Get the red green blue values of each pixel"
},
{
"code": null,
"e": 1193,
"s": 1149,
"text": "Get the red green blue values of each pixel"
},
{
"code": null,
"e": 1228,
"s": 1193,
"text": "Get the average of these 3 colors."
},
{
"code": null,
"e": 1263,
"s": 1228,
"text": "Get the average of these 3 colors."
},
{
"code": null,
"e": 1304,
"s": 1263,
"text": "Replace the RGB values with the average."
},
{
"code": null,
"e": 1345,
"s": 1304,
"text": "Replace the RGB values with the average."
},
{
"code": null,
"e": 1396,
"s": 1345,
"text": "Create a new pixel value from the modified colors."
},
{
"code": null,
"e": 1447,
"s": 1396,
"text": "Create a new pixel value from the modified colors."
},
{
"code": null,
"e": 1479,
"s": 1447,
"text": "Set the new value to the pixel."
},
{
"code": null,
"e": 1511,
"s": 1479,
"text": "Set the new value to the pixel."
},
{
"code": null,
"e": 2811,
"s": 1511,
"text": "import java.io.File;\nimport java.io.IOException;\nimport java.awt.Color;\nimport java.awt.image.BufferedImage;\nimport javax.imageio.ImageIO;\npublic class Color2Grey {\n public static void main(String args[])throws IOException {\n //Reading the image\n File file= new File(\"D:\\\\Images\\\\car.jpg\");\n BufferedImage img = ImageIO.read(file);\n for (int y = 0; y < img.getHeight(); y++) {\n for (int x = 0; x < img.getWidth(); x++) {\n //Retrieving the values of a pixel\n int pixel = img.getRGB(x,y);\n //Creating a Color object from pixel value\n Color color = new Color(pixel, true);\n //Retrieving the R G B values\n int red = color.getRed();\n int green = color.getGreen();\n int blue = color.getBlue();\n //Finding the average of the red green blue values\n int average = (red+green+blue)/3;\n //Creating new Color object\n color = new Color(average, average, average);\n //Setting new Color object to the image\n img.setRGB(x, y, color.getRGB());\n }\n }\n //Saving the modified image\n file = new File(\"D:\\\\Images\\\\grey_image.jpg\");\n ImageIO.write(img, \"jpg\", file);\n System.out.println(\"Done...\");\n }\n}"
}
]
|
Check if a destination is reachable from source with two movements allowed | Set 2 - GeeksforGeeks | 07 May, 2021
Given a pair of coordinates (X1, Y1)(source) and (X2, Y2)(destination), the task is to check if it is possible to reach the destination form the source by the following movements from any cell (X, Y):
(X + Y, Y)(X, Y + X)
(X + Y, Y)
(X, Y + X)
Note: All coordinates are positive and can be as large as 1018.
Examples:
Input: X1 = 2, Y1 = 10, X2 = 26, Y2 = 12 Output: Yes
Explanation: Possible path: (2, 10) → (2, 12) ⇾ (14, 12) → (26, 12)Therefore, a path exists between source and destination.
Input: X1 = 20, Y1 = 10, X2 = 6, Y2 = 12 Output: No
Naive Approach: The simplest approach to solve the problem is by using recursion. Refer to the article check if a destination is reachable from source with two movements allowed for the recursive approach.
Efficient Approach: The main idea is to check if a path from the destination coordinates (X2, Y2) to the source (X1, Y1) exists or not.
Follow the steps below to solve the problem:
Keep subtracting the smallest of (X2, Y2) from the largest of (X2, Y2) and stop if X2 becomes less than X1 or Y2 becomes less than Y1.
Now, compare (X1, Y1) and modified (X2, Y2). If X1 is equal to X2 and Y1 is equal to Y2, then print “Yes“.
If X1 is not equal to X2 or Y1 is equal, not Y2, then print “No“.
To optimize the complexity of the subtraction operation, the modulus operation can be used instead. Simply perform x2 = x2 % y2 and y2 = y2 % x2 and check for the necessary condition mentioned above.
C++
Python3
Java
C#
Javascript
// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Check if (x2, y2) can be reached// from (x1, y1)bool isReachable(long long x1, long long y1, long long x2, long long y2){ while (x2 > x1 && y2 > y1) { // Reduce x2 by y2 until it is // less than or equal to x1 if (x2 > y2) x2 %= y2; // Reduce y2 by x2 until it is // less than or equal to y1 else y2 %= x2; } // If x2 is reduced to x1 if (x2 == x1) // Check if y2 can be // reduced to y1 or not return (y2 - y1) >= 0 && (y2 - y1) % x1 == 0; // If y2 is reduced to y1 else if (y2 == y1) // Check if x2 can be // reduced to x1 or not return (x2 - x1) >= 0 && (x2 - x1) % y1 == 0; else return 0;} // Driver Codeint main(){ long long source_x = 2, source_y = 10; long long dest_x = 26, dest_y = 12; if (isReachable(source_x, source_y, dest_x, dest_y)) cout << "Yes"; else cout << "No"; return 0;}
# Python3 program to implement# the above approach # Check if (x2, y2) can be reached# from (x1, y1)def isReachable(x1, y1, x2, y2): while(x2 > x1 and y2 > y1): # Reduce x2 by y2 until it is # less than or equal to x1 if(x2 > y2): x2 %= y2 # Reduce y2 by x2 until it is # less than or equal to y1 else: y2 %= x2 # If x2 is reduced to x1 if(x2 == x1): # Check if y2 can be # reduced to y1 or not return (y2 - y1) >= 0 and ( y2 - y1) % x1 == 0 # If y2 is reduced to y1 elif(y2 == y1): # Check if x2 can be # reduced to x1 or not return (x2 - x1) >= 0 and ( x2 - x1) % y1 == 0 else: return 0 # Driver Codesource_x = 2source_y = 10dest_x = 26dest_y = 12 # Function callif(isReachable(source_x, source_y, dest_x, dest_y)): print("Yes")else: print("No") # This code is contributed by Shivam Singh
// Java program to implement// the above approachclass GFG{ // Check if (x2, y2) can be reached// from (x1, y1)static boolean isReachable(long x1, long y1, long x2, long y2){ while (x2 > x1 && y2 > y1) { // Reduce x2 by y2 until it is // less than or equal to x1 if (x2 > y2) x2 %= y2; // Reduce y2 by x2 until it is // less than or equal to y1 else y2 %= x2; } // If x2 is reduced to x1 if (x2 == x1) // Check if y2 can be // reduced to y1 or not return (y2 - y1) >= 0 && (y2 - y1) % x1 == 0; // If y2 is reduced to y1 else if (y2 == y1) // Check if x2 can be // reduced to x1 or not return (x2 - x1) >= 0 && (x2 - x1) % y1 == 0; else return false;} // Driver Codepublic static void main(String[] args){ long source_x = 2, source_y = 10; long dest_x = 26, dest_y = 12; if (isReachable(source_x, source_y, dest_x, dest_y)) System.out.print("Yes"); else System.out.print("No");}} // This code is contributed by shikhasingrajput
// C# program to implement// the above approachusing System;class GFG{ // Check if (x2, y2) can be reached// from (x1, y1)static bool isReachable(long x1, long y1, long x2, long y2){ while (x2 > x1 && y2 > y1) { // Reduce x2 by y2 // until it is less // than or equal to x1 if (x2 > y2) x2 %= y2; // Reduce y2 by x2 // until it is less // than or equal to y1 else y2 %= x2; } // If x2 is reduced to x1 if (x2 == x1) // Check if y2 can be // reduced to y1 or not return (y2 - y1) >= 0 && (y2 - y1) % x1 == 0; // If y2 is reduced to y1 else if (y2 == y1) // Check if x2 can be // reduced to x1 or not return (x2 - x1) >= 0 && (x2 - x1) % y1 == 0; else return false;} // Driver Codepublic static void Main(String[] args){ long source_x = 2, source_y = 10; long dest_x = 26, dest_y = 12; if (isReachable(source_x, source_y, dest_x, dest_y)) Console.Write("Yes"); else Console.Write("No");}} // This code is contributed by shikhasingrajput
<script> // JavaScript program for//the above approach // Check if (x2, y2) can be reached// from (x1, y1)function isReachable(x1, y1, x2, y2){ while (x2 > x1 && y2 > y1) { // Reduce x2 by y2 until it is // less than or equal to x1 if (x2 > y2) x2 %= y2; // Reduce y2 by x2 until it is // less than or equal to y1 else y2 %= x2; } // If x2 is reduced to x1 if (x2 == x1) // Check if y2 can be // reduced to y1 or not return (y2 - y1) >= 0 && (y2 - y1) % x1 == 0; // If y2 is reduced to y1 else if (y2 == y1) // Check if x2 can be // reduced to x1 or not return (x2 - x1) >= 0 && (x2 - x1) % y1 == 0; else return false;} // Driver Code let source_x = 2, source_y = 10; let dest_x = 26, dest_y = 12; if (isReachable(source_x, source_y, dest_x, dest_y)) document.write("Yes"); else document.write("No"); </script>
Yes
Time Complexity: O(1) Auxiliary Space: O(1)
SHIVAMSINGH67
shikhasingrajput
souravghosh0416
interview-preparation
MakeMyTrip
Modular Arithmetic
Greedy
Mathematical
MakeMyTrip
Greedy
Mathematical
Modular Arithmetic
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
Activity Selection Problem | Greedy Algo-1
Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)
Program for Fibonacci numbers
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
Merge two sorted arrays | [
{
"code": null,
"e": 26825,
"s": 26797,
"text": "\n07 May, 2021"
},
{
"code": null,
"e": 27026,
"s": 26825,
"text": "Given a pair of coordinates (X1, Y1)(source) and (X2, Y2)(destination), the task is to check if it is possible to reach the destination form the source by the following movements from any cell (X, Y):"
},
{
"code": null,
"e": 27047,
"s": 27026,
"text": "(X + Y, Y)(X, Y + X)"
},
{
"code": null,
"e": 27058,
"s": 27047,
"text": "(X + Y, Y)"
},
{
"code": null,
"e": 27069,
"s": 27058,
"text": "(X, Y + X)"
},
{
"code": null,
"e": 27133,
"s": 27069,
"text": "Note: All coordinates are positive and can be as large as 1018."
},
{
"code": null,
"e": 27143,
"s": 27133,
"text": "Examples:"
},
{
"code": null,
"e": 27196,
"s": 27143,
"text": "Input: X1 = 2, Y1 = 10, X2 = 26, Y2 = 12 Output: Yes"
},
{
"code": null,
"e": 27320,
"s": 27196,
"text": "Explanation: Possible path: (2, 10) → (2, 12) ⇾ (14, 12) → (26, 12)Therefore, a path exists between source and destination."
},
{
"code": null,
"e": 27372,
"s": 27320,
"text": "Input: X1 = 20, Y1 = 10, X2 = 6, Y2 = 12 Output: No"
},
{
"code": null,
"e": 27578,
"s": 27372,
"text": "Naive Approach: The simplest approach to solve the problem is by using recursion. Refer to the article check if a destination is reachable from source with two movements allowed for the recursive approach."
},
{
"code": null,
"e": 27714,
"s": 27578,
"text": "Efficient Approach: The main idea is to check if a path from the destination coordinates (X2, Y2) to the source (X1, Y1) exists or not."
},
{
"code": null,
"e": 27759,
"s": 27714,
"text": "Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 27894,
"s": 27759,
"text": "Keep subtracting the smallest of (X2, Y2) from the largest of (X2, Y2) and stop if X2 becomes less than X1 or Y2 becomes less than Y1."
},
{
"code": null,
"e": 28001,
"s": 27894,
"text": "Now, compare (X1, Y1) and modified (X2, Y2). If X1 is equal to X2 and Y1 is equal to Y2, then print “Yes“."
},
{
"code": null,
"e": 28067,
"s": 28001,
"text": "If X1 is not equal to X2 or Y1 is equal, not Y2, then print “No“."
},
{
"code": null,
"e": 28267,
"s": 28067,
"text": "To optimize the complexity of the subtraction operation, the modulus operation can be used instead. Simply perform x2 = x2 % y2 and y2 = y2 % x2 and check for the necessary condition mentioned above."
},
{
"code": null,
"e": 28271,
"s": 28267,
"text": "C++"
},
{
"code": null,
"e": 28279,
"s": 28271,
"text": "Python3"
},
{
"code": null,
"e": 28284,
"s": 28279,
"text": "Java"
},
{
"code": null,
"e": 28287,
"s": 28284,
"text": "C#"
},
{
"code": null,
"e": 28298,
"s": 28287,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Check if (x2, y2) can be reached// from (x1, y1)bool isReachable(long long x1, long long y1, long long x2, long long y2){ while (x2 > x1 && y2 > y1) { // Reduce x2 by y2 until it is // less than or equal to x1 if (x2 > y2) x2 %= y2; // Reduce y2 by x2 until it is // less than or equal to y1 else y2 %= x2; } // If x2 is reduced to x1 if (x2 == x1) // Check if y2 can be // reduced to y1 or not return (y2 - y1) >= 0 && (y2 - y1) % x1 == 0; // If y2 is reduced to y1 else if (y2 == y1) // Check if x2 can be // reduced to x1 or not return (x2 - x1) >= 0 && (x2 - x1) % y1 == 0; else return 0;} // Driver Codeint main(){ long long source_x = 2, source_y = 10; long long dest_x = 26, dest_y = 12; if (isReachable(source_x, source_y, dest_x, dest_y)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 29421,
"s": 28298,
"text": null
},
{
"code": "# Python3 program to implement# the above approach # Check if (x2, y2) can be reached# from (x1, y1)def isReachable(x1, y1, x2, y2): while(x2 > x1 and y2 > y1): # Reduce x2 by y2 until it is # less than or equal to x1 if(x2 > y2): x2 %= y2 # Reduce y2 by x2 until it is # less than or equal to y1 else: y2 %= x2 # If x2 is reduced to x1 if(x2 == x1): # Check if y2 can be # reduced to y1 or not return (y2 - y1) >= 0 and ( y2 - y1) % x1 == 0 # If y2 is reduced to y1 elif(y2 == y1): # Check if x2 can be # reduced to x1 or not return (x2 - x1) >= 0 and ( x2 - x1) % y1 == 0 else: return 0 # Driver Codesource_x = 2source_y = 10dest_x = 26dest_y = 12 # Function callif(isReachable(source_x, source_y, dest_x, dest_y)): print(\"Yes\")else: print(\"No\") # This code is contributed by Shivam Singh",
"e": 30402,
"s": 29421,
"text": null
},
{
"code": "// Java program to implement// the above approachclass GFG{ // Check if (x2, y2) can be reached// from (x1, y1)static boolean isReachable(long x1, long y1, long x2, long y2){ while (x2 > x1 && y2 > y1) { // Reduce x2 by y2 until it is // less than or equal to x1 if (x2 > y2) x2 %= y2; // Reduce y2 by x2 until it is // less than or equal to y1 else y2 %= x2; } // If x2 is reduced to x1 if (x2 == x1) // Check if y2 can be // reduced to y1 or not return (y2 - y1) >= 0 && (y2 - y1) % x1 == 0; // If y2 is reduced to y1 else if (y2 == y1) // Check if x2 can be // reduced to x1 or not return (x2 - x1) >= 0 && (x2 - x1) % y1 == 0; else return false;} // Driver Codepublic static void main(String[] args){ long source_x = 2, source_y = 10; long dest_x = 26, dest_y = 12; if (isReachable(source_x, source_y, dest_x, dest_y)) System.out.print(\"Yes\"); else System.out.print(\"No\");}} // This code is contributed by shikhasingrajput",
"e": 31571,
"s": 30402,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;class GFG{ // Check if (x2, y2) can be reached// from (x1, y1)static bool isReachable(long x1, long y1, long x2, long y2){ while (x2 > x1 && y2 > y1) { // Reduce x2 by y2 // until it is less // than or equal to x1 if (x2 > y2) x2 %= y2; // Reduce y2 by x2 // until it is less // than or equal to y1 else y2 %= x2; } // If x2 is reduced to x1 if (x2 == x1) // Check if y2 can be // reduced to y1 or not return (y2 - y1) >= 0 && (y2 - y1) % x1 == 0; // If y2 is reduced to y1 else if (y2 == y1) // Check if x2 can be // reduced to x1 or not return (x2 - x1) >= 0 && (x2 - x1) % y1 == 0; else return false;} // Driver Codepublic static void Main(String[] args){ long source_x = 2, source_y = 10; long dest_x = 26, dest_y = 12; if (isReachable(source_x, source_y, dest_x, dest_y)) Console.Write(\"Yes\"); else Console.Write(\"No\");}} // This code is contributed by shikhasingrajput",
"e": 32653,
"s": 31571,
"text": null
},
{
"code": "<script> // JavaScript program for//the above approach // Check if (x2, y2) can be reached// from (x1, y1)function isReachable(x1, y1, x2, y2){ while (x2 > x1 && y2 > y1) { // Reduce x2 by y2 until it is // less than or equal to x1 if (x2 > y2) x2 %= y2; // Reduce y2 by x2 until it is // less than or equal to y1 else y2 %= x2; } // If x2 is reduced to x1 if (x2 == x1) // Check if y2 can be // reduced to y1 or not return (y2 - y1) >= 0 && (y2 - y1) % x1 == 0; // If y2 is reduced to y1 else if (y2 == y1) // Check if x2 can be // reduced to x1 or not return (x2 - x1) >= 0 && (x2 - x1) % y1 == 0; else return false;} // Driver Code let source_x = 2, source_y = 10; let dest_x = 26, dest_y = 12; if (isReachable(source_x, source_y, dest_x, dest_y)) document.write(\"Yes\"); else document.write(\"No\"); </script>",
"e": 33690,
"s": 32653,
"text": null
},
{
"code": null,
"e": 33694,
"s": 33690,
"text": "Yes"
},
{
"code": null,
"e": 33739,
"s": 33694,
"text": "Time Complexity: O(1) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 33753,
"s": 33739,
"text": "SHIVAMSINGH67"
},
{
"code": null,
"e": 33770,
"s": 33753,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 33786,
"s": 33770,
"text": "souravghosh0416"
},
{
"code": null,
"e": 33808,
"s": 33786,
"text": "interview-preparation"
},
{
"code": null,
"e": 33819,
"s": 33808,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 33838,
"s": 33819,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 33845,
"s": 33838,
"text": "Greedy"
},
{
"code": null,
"e": 33858,
"s": 33845,
"text": "Mathematical"
},
{
"code": null,
"e": 33869,
"s": 33858,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 33876,
"s": 33869,
"text": "Greedy"
},
{
"code": null,
"e": 33889,
"s": 33876,
"text": "Mathematical"
},
{
"code": null,
"e": 33908,
"s": 33889,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 34006,
"s": 33908,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34037,
"s": 34006,
"text": "Huffman Coding | Greedy Algo-3"
},
{
"code": null,
"e": 34056,
"s": 34037,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 34084,
"s": 34056,
"text": "Fractional Knapsack Problem"
},
{
"code": null,
"e": 34127,
"s": 34084,
"text": "Activity Selection Problem | Greedy Algo-1"
},
{
"code": null,
"e": 34208,
"s": 34127,
"text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)"
},
{
"code": null,
"e": 34238,
"s": 34208,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 34253,
"s": 34238,
"text": "C++ Data Types"
},
{
"code": null,
"e": 34296,
"s": 34253,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 34315,
"s": 34296,
"text": "Coin Change | DP-7"
}
]
|
How to loop through collections with a cursor in MongoDB? | Following is the syntax to loop through collections with cursor
var anyVariableName1;
var anyVariableName2= db.yourCollectionName.find();
while(yourVariableName2.hasNext()) {
yourVariableName1= yourVariableName2.next(); printjson(yourVariableName1);
};
Let us create a collection with documents. Following is the query
> db.loopThroughCollectionDemo.insertOne({"StudentName":"John","StudentAge":23});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9ca81f2d6669774125247f")
}
> db.loopThroughCollectionDemo.insertOne({"StudentName":"Larry","StudentAge":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9ca8272d66697741252480")
}
> db.loopThroughCollectionDemo.insertOne({"StudentName":"Chris","StudentAge":25});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9ca8462d66697741252481")
}
> db.loopThroughCollectionDemo.insertOne({"StudentName":"Robert","StudentAge":24});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9ca8632d66697741252482")
}
Following is the query to display all documents from a collection with the help of find() method
> db.loopThroughCollectionDemo.find().pretty();
This will produce the following output
{
"_id" : ObjectId("5c9ca81f2d6669774125247f"),
"StudentName" : "John",
"StudentAge" : 23
}
{
"_id" : ObjectId("5c9ca8272d66697741252480"),
"StudentName" : "Larry",
"StudentAge" : 21
}
{
"_id" : ObjectId("5c9ca8462d66697741252481"),
"StudentName" : "Chris",
"StudentAge" : 25
}
{
"_id" : ObjectId("5c9ca8632d66697741252482"),
"StudentName" : "Robert",
"StudentAge" : 24
}
Following is the query to loop through collections with cursor
> var allDocumentValue;
> var collectionName=db.loopThroughCollectionDemo.find();
> while(collectionName.hasNext()){allDocumentValue= collectionName.next();printjson(allDocumentValue);
... }
This will produce the following output
{
"_id" : ObjectId("5c9ca81f2d6669774125247f"),
"StudentName" : "John",
"StudentAge" : 23
}
{
"_id" : ObjectId("5c9ca8272d66697741252480"),
"StudentName" : "Larry",
"StudentAge" : 21
}
{
"_id" : ObjectId("5c9ca8462d66697741252481"),
"StudentName" : "Chris",
"StudentAge" : 25
}
{
"_id" : ObjectId("5c9ca8632d66697741252482"),
"StudentName" : "Robert",
"StudentAge" : 24
} | [
{
"code": null,
"e": 1126,
"s": 1062,
"text": "Following is the syntax to loop through collections with cursor"
},
{
"code": null,
"e": 1318,
"s": 1126,
"text": "var anyVariableName1;\nvar anyVariableName2= db.yourCollectionName.find();\nwhile(yourVariableName2.hasNext()) {\n yourVariableName1= yourVariableName2.next(); printjson(yourVariableName1);\n};"
},
{
"code": null,
"e": 1384,
"s": 1318,
"text": "Let us create a collection with documents. Following is the query"
},
{
"code": null,
"e": 2056,
"s": 1384,
"text": "> db.loopThroughCollectionDemo.insertOne({\"StudentName\":\"John\",\"StudentAge\":23});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9ca81f2d6669774125247f\")\n}\n> db.loopThroughCollectionDemo.insertOne({\"StudentName\":\"Larry\",\"StudentAge\":21});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9ca8272d66697741252480\")\n}\n> db.loopThroughCollectionDemo.insertOne({\"StudentName\":\"Chris\",\"StudentAge\":25});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9ca8462d66697741252481\")\n}\n> db.loopThroughCollectionDemo.insertOne({\"StudentName\":\"Robert\",\"StudentAge\":24});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9ca8632d66697741252482\")\n}"
},
{
"code": null,
"e": 2153,
"s": 2056,
"text": "Following is the query to display all documents from a collection with the help of find() method"
},
{
"code": null,
"e": 2201,
"s": 2153,
"text": "> db.loopThroughCollectionDemo.find().pretty();"
},
{
"code": null,
"e": 2240,
"s": 2201,
"text": "This will produce the following output"
},
{
"code": null,
"e": 2648,
"s": 2240,
"text": "{\n \"_id\" : ObjectId(\"5c9ca81f2d6669774125247f\"),\n \"StudentName\" : \"John\",\n \"StudentAge\" : 23\n}\n{\n \"_id\" : ObjectId(\"5c9ca8272d66697741252480\"),\n \"StudentName\" : \"Larry\",\n \"StudentAge\" : 21\n}\n{\n \"_id\" : ObjectId(\"5c9ca8462d66697741252481\"),\n \"StudentName\" : \"Chris\",\n \"StudentAge\" : 25\n}\n{\n \"_id\" : ObjectId(\"5c9ca8632d66697741252482\"),\n \"StudentName\" : \"Robert\",\n \"StudentAge\" : 24\n}"
},
{
"code": null,
"e": 2711,
"s": 2648,
"text": "Following is the query to loop through collections with cursor"
},
{
"code": null,
"e": 2902,
"s": 2711,
"text": "> var allDocumentValue;\n> var collectionName=db.loopThroughCollectionDemo.find();\n> while(collectionName.hasNext()){allDocumentValue= collectionName.next();printjson(allDocumentValue);\n... }"
},
{
"code": null,
"e": 2941,
"s": 2902,
"text": "This will produce the following output"
},
{
"code": null,
"e": 3349,
"s": 2941,
"text": "{\n \"_id\" : ObjectId(\"5c9ca81f2d6669774125247f\"),\n \"StudentName\" : \"John\",\n \"StudentAge\" : 23\n}\n{\n \"_id\" : ObjectId(\"5c9ca8272d66697741252480\"),\n \"StudentName\" : \"Larry\",\n \"StudentAge\" : 21\n}\n{\n \"_id\" : ObjectId(\"5c9ca8462d66697741252481\"),\n \"StudentName\" : \"Chris\",\n \"StudentAge\" : 25\n}\n{\n \"_id\" : ObjectId(\"5c9ca8632d66697741252482\"),\n \"StudentName\" : \"Robert\",\n \"StudentAge\" : 24\n}"
}
]
|
Insert() Method in C# | The Insert() method in C# is used to return a new string in which a specified string is inserted at a specified index position in this instance.
The syntax is as follows −
public string Insert (int begnIndex, string val);
Above, the parameter begnIndex is the zero-based index position of the insertion, whereas val is the string to insert.
Let us now see an example −
Live Demo
using System;
public class Demo{
public static void Main(){
String str = "JohnWick";
Console.WriteLine("Initial string = "+str);
String res = str.Insert(5, " ");
Console.WriteLine("Updated = "+res);
}
}
This will produce the following output −
Initial string = JohnWick
Updated = JohnW ick
Let us now see another example
Live Demo
using System;
public class Demo{
public static void Main(){
String str = "WelcomeJacob";
Console.WriteLine("Initial string = "+str);
String res = str.Insert(7, " here, ");
Console.WriteLine("Updated = "+res);
}
}
This will produce the following output −
Initial string = WelcomeJacob
Updated = Welcome here, Jacob | [
{
"code": null,
"e": 1207,
"s": 1062,
"text": "The Insert() method in C# is used to return a new string in which a specified string is inserted at a specified index position in this instance."
},
{
"code": null,
"e": 1234,
"s": 1207,
"text": "The syntax is as follows −"
},
{
"code": null,
"e": 1284,
"s": 1234,
"text": "public string Insert (int begnIndex, string val);"
},
{
"code": null,
"e": 1403,
"s": 1284,
"text": "Above, the parameter begnIndex is the zero-based index position of the insertion, whereas val is the string to insert."
},
{
"code": null,
"e": 1431,
"s": 1403,
"text": "Let us now see an example −"
},
{
"code": null,
"e": 1442,
"s": 1431,
"text": " Live Demo"
},
{
"code": null,
"e": 1675,
"s": 1442,
"text": "using System;\npublic class Demo{\n public static void Main(){\n String str = \"JohnWick\";\n Console.WriteLine(\"Initial string = \"+str);\n String res = str.Insert(5, \" \");\n Console.WriteLine(\"Updated = \"+res);\n }\n}"
},
{
"code": null,
"e": 1716,
"s": 1675,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1762,
"s": 1716,
"text": "Initial string = JohnWick\nUpdated = JohnW ick"
},
{
"code": null,
"e": 1793,
"s": 1762,
"text": "Let us now see another example"
},
{
"code": null,
"e": 1804,
"s": 1793,
"text": " Live Demo"
},
{
"code": null,
"e": 2047,
"s": 1804,
"text": "using System;\npublic class Demo{\n public static void Main(){\n String str = \"WelcomeJacob\";\n Console.WriteLine(\"Initial string = \"+str);\n String res = str.Insert(7, \" here, \");\n Console.WriteLine(\"Updated = \"+res);\n }\n}"
},
{
"code": null,
"e": 2088,
"s": 2047,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2148,
"s": 2088,
"text": "Initial string = WelcomeJacob\nUpdated = Welcome here, Jacob"
}
]
|
Python Program to Print Numbers in an Interval | In this article, we will learn about the solution and approach to solve the given problem statement.
Given the starting and ending range of an interval. We need to print all the numbers in the interval given.
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
There are two for loops, first for loop is for getting the numbers in the interval and second loop for the checking whether the number is prime or not.
Now let’s see the implementation.
Live Demo
start = 10
end = 29
for val in range(start, end + 1):
# If num is divisible by any number is not prime
if val > 1:
for n in range(2, val):
if (val % n) == 0:
break
else:
print(val)
11
13
17
19
23
29
All variables and functions are declared in the global scope as shown in the figure below.
In this article, we learned about the approach to print numbers in a given interval. | [
{
"code": null,
"e": 1163,
"s": 1062,
"text": "In this article, we will learn about the solution and approach to solve the given problem statement."
},
{
"code": null,
"e": 1271,
"s": 1163,
"text": "Given the starting and ending range of an interval. We need to print all the numbers in the interval given."
},
{
"code": null,
"e": 1376,
"s": 1271,
"text": "A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself."
},
{
"code": null,
"e": 1528,
"s": 1376,
"text": "There are two for loops, first for loop is for getting the numbers in the interval and second loop for the checking whether the number is prime or not."
},
{
"code": null,
"e": 1562,
"s": 1528,
"text": "Now let’s see the implementation."
},
{
"code": null,
"e": 1573,
"s": 1562,
"text": " Live Demo"
},
{
"code": null,
"e": 1799,
"s": 1573,
"text": "start = 10\nend = 29\nfor val in range(start, end + 1):\n# If num is divisible by any number is not prime\n if val > 1:\n for n in range(2, val):\n if (val % n) == 0:\n break\n else:\n print(val)"
},
{
"code": null,
"e": 1817,
"s": 1799,
"text": "11\n13\n17\n19\n23\n29"
},
{
"code": null,
"e": 1908,
"s": 1817,
"text": "All variables and functions are declared in the global scope as shown in the figure below."
},
{
"code": null,
"e": 1993,
"s": 1908,
"text": "In this article, we learned about the approach to print numbers in a given interval."
}
]
|
Heatmap Basics with Seaborn. A guide for how to create heatmaps with... | by Thiago Carvalho | Towards Data Science | The idea is straightforward, replace numbers with colors.
Now, this visualization style has come a long way from simple color-coded tables. It became widely used with geospatial data. Its commonly applied for describing the density or intensity of variables, visualize patterns, variance, and even anomalies.
With so many applications, this elementary method deserves some attention. This article will go through the basics of heatmaps and see how to create them using Matplotlib and Seaborn.
We’ll use Pandas and Numpy to help us with data wrangling.
import pandas as pdimport matplotlib.pyplot as pltimport seaborn as sbimport numpy as np
The dataset for this example is a time series of foreign exchange rates per U.S. dollar.
Instead of the usual line chart to represent the values over time, I want to visualize this data with a color-coded table, having the months as columns and the years as rows.
I’ll try sketching both the line chart and the heatmap to understand how this will look.
Line charts would be more effective in displaying the data; it’s easier to compare how higher a point is in the line than to distinguish colors.
Heatmaps will have a higher impact as they are not the conventional way of displaying this sort of data. They’ll lose some accuracy, especially in this case, since we’ll need to aggregate the values in months. But overall, they would still be able to display patterns and summarize the periods in our data.
Let’s read the dataset and rearrange the data according to the sketch.
# read filedf = pd.read_csv('data/Foreign_Exchange_Rates.csv', usecols=[1,7], names=['DATE', 'CAD_USD'], skiprows=1, index_col=0, parse_dates=[0])
For this example, we’ll use the columns 1 and 7, which are the ‘Time Serie’ and ‘CANADA — CANADIAN DOLLAR/US$’.
Let’s rename those columns to ‘DATE’ and ‘CAD_USD’, and since we’re passing our headers, we also need to skip the first row.
We also need to parse the first column, so the values are in a DateTime format, and we’ll define the date as our index.
Let’s make sure all our values are numbers, and remove the empty rows as well.
df['CAD_USD'] = pd.to_numeric(df.CAD_USD, errors='coerce')df.dropna(inplace=True)
We need to aggregate those values by month. Let’s create separate columns for month and year, then we group the new columns and get the mean.
# create a copy of the dataframe, and add columns for month and yeardf_m = df.copy()df_m['month'] = [i.month for i in df_m.index]df_m['year'] = [i.year for i in df_m.index]# group by month and year, get the averagedf_m = df_m.groupby(['month', 'year']).mean()
All that’s left to do is unstack the indexes, and we’ll have our table.
df_m = df_m.unstack(level=0)
Everything is in place. Now we can use Seaborn’s .heatmap and plot our first chart.
fig, ax = plt.subplots(figsize=(11, 9))sb.heatmap(df_m)plt.show()
Alright, there’s lots to do before this visualization is ready.
The colors are the most critical part of our chart, and the colormap is a bit overcomplicated. We don’t need that; instead, we could use a sequential cmap with only two colors.
We can also make the limits of the colormap explicit by defining vmin and vmax. Pandas .min and .max can help us figure out what are the best values for those.
fig, ax = plt.subplots(figsize=(11, 9))# plot heatmapsb.heatmap(df_m, cmap="Blues", vmin= 0.9, vmax=1.65, linewidth=0.3, cbar_kws={"shrink": .8})plt.show()
There are lots of other arguments to be explored with .heatmap.
For example linewidth defines the size of the line between the boxes, and we can even pass arguments directly to the color bar with cbar_kws.
The colors look good, and now we can move our attention to the ticks. I don’t think CAD_USD-1 is the right name for January. Let’s replace them with some friendlier text.
Moving the ticks to the top of the chart would improve the visualization and make it look more like a table. We can also eliminate the x and y labels since the values in our axis are pretty self-explaining, and the title would also make them redundant.
# figurefig, ax = plt.subplots(figsize=(11, 9))# plot heatmapsb.heatmap(df_m, cmap="Blues", vmin= 0.9, vmax=1.65, square=True, linewidth=0.3, cbar_kws={"shrink": .8})# xticksax.xaxis.tick_top()xticks_labels = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']plt.xticks(np.arange(12) + .5, labels=xticks_labels)# axis labelsplt.xlabel('')plt.ylabel('')# titletitle = 'monthly Average exchange rate\nValue of one USD in CAD\n'.upper()plt.title(title, loc='left')plt.show()
There’s one last argument I passed to the heatmap, which is square. That will make the cells of our matrix in a square shape regardless of the size of the figure.
Overall, it looks good. We can see that the U.S. dollar was almost 50% higher than the Canadian in the early 2000s, which started changing around 2003. This lower dollar was sustained until late 2014, with some variation during the financial crisis of 2008.
By 2015 it had stabilized around 1.20~1.40, with relatively slight variation in the monthly averages until 2019, the end of our records.
For the following example, I’ll go through a correlation matrix to see some more functions of Seaborn’s heatmap.
The dataset is a sample of 80 different kinds of cereal, and I want to look at their compositions.
To build the correlation matrix, we can use Pandas .corr().
# read datasetdf = pd.read_csv('data/cereal.csv')# get correlationsdf_corr = df.corr()# irrelevant fieldsfields = ['rating', 'shelf', 'cups', 'weight']# drop rowsdf_corr.drop(fields, inplace=True)# drop colsdf_corr.drop(fields, axis=1, inplace=True)
There’s lots of redundancy in a correlation matrix; the upper triangle of the table has the same information as the lower.
Luckily we can use masks with Seaborn’s heatmap, and Numpy has the functions to build one.
np.ones_like(df_corr, dtype=np.bool)
Numpy .ones_like can create a matrix of booleans with the same shape as our data frame, while .triu will return only the upper triangle of that matrix.
mask = np.triu(np.ones_like(df_corr, dtype=np.bool))
The mask can help, but there are still two empty cells in our matrix.
There’s nothing wrong with it. Those values can add to the symmetry of our plot — That is to say, it’s easier to know two lists are the same if they start and end with the same values.
If like me, you’re bothered with that, you can filter those out when plotting.
fig, ax = plt.subplots(figsize=(10, 8))# maskmask = np.triu(np.ones_like(df_corr, dtype=np.bool))# adjust mask and dfmask = mask[1:, :-1]corr = df_corr.iloc[1:,:-1].copy()# plot heatmapsb.heatmap(corr, mask=mask, annot=True, fmt=".2f", cmap='Blues', vmin=-1, vmax=1, cbar_kws={"shrink": .8})# yticksplt.yticks(rotation=0)plt.show()
Cool, the only thing not mentioned was the annotations. We can set those with the parameter annot and we can pass a formatting function to it with fmt.
We still need a title, and the ticks would look better with an upper case, but that’s not the priority yet.
Correlations range from -1 to 1, so they have two directions, and in this case, a diverging palette works better than a sequential one.
Seaborn has an efficient method for that, called .diverging_palette, it serves to build the colormaps we need with one color on each side, converging to another color in the center.
That method uses HUSL colors, so you need hue, saturation, and lightness. I used hsluv.org to select the colors of this chart.
fig, ax = plt.subplots(figsize=(12, 10))# maskmask = np.triu(np.ones_like(df_corr, dtype=np.bool))# adjust mask and dfmask = mask[1:, :-1]corr = df_corr.iloc[1:,:-1].copy()# color mapcmap = sb.diverging_palette(0, 230, 90, 60, as_cmap=True)# plot heatmapsb.heatmap(corr, mask=mask, annot=True, fmt=".2f", linewidths=5, cmap=cmap, vmin=-1, vmax=1, cbar_kws={"shrink": .8}, square=True)# ticksyticks = [i.upper() for i in corr.index]xticks = [i.upper() for i in corr.columns]plt.yticks(plt.yticks()[0], labels=yticks, rotation=0)plt.xticks(plt.xticks()[0], labels=xticks)# titletitle = 'CORRELATION MATRIX\nSAMPLED CEREALS COMPOSITION\n'plt.title(title, loc='left', fontsize=18)plt.show()
Pretty cool, we built a beautiful visualization for the correlation matrix. Now it’s easier to see the most significant correlation coefficients, like Fiber and Potassium, for example.
Usually, after a correlation matrix, we get a better look at the variables with a strong relationship.
In this case, we don’t have too much data to look into, so a scatter plot would be enough to start investigating those variables.
The problem with scatter plots is that they tend to become hard to read with too much data, as the points start to overlap. That’s when heatmaps get back in the scene to visualize density.
fig, ax = plt.subplots(1, figsize=(12,8))sb.kdeplot(df.potass, df.fiber, cmap='Blues', shade=True, shade_lowest=False, clip=(-1,300))plt.scatter(df.potass, df.fiber, color='orangered')
If you’re interested in learning more about KDE, I suggest you get a look at Matthew Conlen’s article about this topic.
Well, we explored most of the basics in heatmaps and looked at how they can increase complexity with color maps, bars, masks, and density estimations.
Thanks for reading my article. I hope you enjoyed it.
Here you can find more tutorials on DataViz with Python.
Resources:Seaborn Example — Correlation Matrix;Seaborn Choosing Color Palletes;Seaborn Diverging Palette;Seaborn Kernel Density Estimation Plot; | [
{
"code": null,
"e": 230,
"s": 172,
"text": "The idea is straightforward, replace numbers with colors."
},
{
"code": null,
"e": 481,
"s": 230,
"text": "Now, this visualization style has come a long way from simple color-coded tables. It became widely used with geospatial data. Its commonly applied for describing the density or intensity of variables, visualize patterns, variance, and even anomalies."
},
{
"code": null,
"e": 665,
"s": 481,
"text": "With so many applications, this elementary method deserves some attention. This article will go through the basics of heatmaps and see how to create them using Matplotlib and Seaborn."
},
{
"code": null,
"e": 724,
"s": 665,
"text": "We’ll use Pandas and Numpy to help us with data wrangling."
},
{
"code": null,
"e": 813,
"s": 724,
"text": "import pandas as pdimport matplotlib.pyplot as pltimport seaborn as sbimport numpy as np"
},
{
"code": null,
"e": 902,
"s": 813,
"text": "The dataset for this example is a time series of foreign exchange rates per U.S. dollar."
},
{
"code": null,
"e": 1077,
"s": 902,
"text": "Instead of the usual line chart to represent the values over time, I want to visualize this data with a color-coded table, having the months as columns and the years as rows."
},
{
"code": null,
"e": 1166,
"s": 1077,
"text": "I’ll try sketching both the line chart and the heatmap to understand how this will look."
},
{
"code": null,
"e": 1311,
"s": 1166,
"text": "Line charts would be more effective in displaying the data; it’s easier to compare how higher a point is in the line than to distinguish colors."
},
{
"code": null,
"e": 1618,
"s": 1311,
"text": "Heatmaps will have a higher impact as they are not the conventional way of displaying this sort of data. They’ll lose some accuracy, especially in this case, since we’ll need to aggregate the values in months. But overall, they would still be able to display patterns and summarize the periods in our data."
},
{
"code": null,
"e": 1689,
"s": 1618,
"text": "Let’s read the dataset and rearrange the data according to the sketch."
},
{
"code": null,
"e": 1870,
"s": 1689,
"text": "# read filedf = pd.read_csv('data/Foreign_Exchange_Rates.csv', usecols=[1,7], names=['DATE', 'CAD_USD'], skiprows=1, index_col=0, parse_dates=[0])"
},
{
"code": null,
"e": 1982,
"s": 1870,
"text": "For this example, we’ll use the columns 1 and 7, which are the ‘Time Serie’ and ‘CANADA — CANADIAN DOLLAR/US$’."
},
{
"code": null,
"e": 2107,
"s": 1982,
"text": "Let’s rename those columns to ‘DATE’ and ‘CAD_USD’, and since we’re passing our headers, we also need to skip the first row."
},
{
"code": null,
"e": 2227,
"s": 2107,
"text": "We also need to parse the first column, so the values are in a DateTime format, and we’ll define the date as our index."
},
{
"code": null,
"e": 2306,
"s": 2227,
"text": "Let’s make sure all our values are numbers, and remove the empty rows as well."
},
{
"code": null,
"e": 2388,
"s": 2306,
"text": "df['CAD_USD'] = pd.to_numeric(df.CAD_USD, errors='coerce')df.dropna(inplace=True)"
},
{
"code": null,
"e": 2530,
"s": 2388,
"text": "We need to aggregate those values by month. Let’s create separate columns for month and year, then we group the new columns and get the mean."
},
{
"code": null,
"e": 2790,
"s": 2530,
"text": "# create a copy of the dataframe, and add columns for month and yeardf_m = df.copy()df_m['month'] = [i.month for i in df_m.index]df_m['year'] = [i.year for i in df_m.index]# group by month and year, get the averagedf_m = df_m.groupby(['month', 'year']).mean()"
},
{
"code": null,
"e": 2862,
"s": 2790,
"text": "All that’s left to do is unstack the indexes, and we’ll have our table."
},
{
"code": null,
"e": 2891,
"s": 2862,
"text": "df_m = df_m.unstack(level=0)"
},
{
"code": null,
"e": 2975,
"s": 2891,
"text": "Everything is in place. Now we can use Seaborn’s .heatmap and plot our first chart."
},
{
"code": null,
"e": 3041,
"s": 2975,
"text": "fig, ax = plt.subplots(figsize=(11, 9))sb.heatmap(df_m)plt.show()"
},
{
"code": null,
"e": 3105,
"s": 3041,
"text": "Alright, there’s lots to do before this visualization is ready."
},
{
"code": null,
"e": 3282,
"s": 3105,
"text": "The colors are the most critical part of our chart, and the colormap is a bit overcomplicated. We don’t need that; instead, we could use a sequential cmap with only two colors."
},
{
"code": null,
"e": 3442,
"s": 3282,
"text": "We can also make the limits of the colormap explicit by defining vmin and vmax. Pandas .min and .max can help us figure out what are the best values for those."
},
{
"code": null,
"e": 3608,
"s": 3442,
"text": "fig, ax = plt.subplots(figsize=(11, 9))# plot heatmapsb.heatmap(df_m, cmap=\"Blues\", vmin= 0.9, vmax=1.65, linewidth=0.3, cbar_kws={\"shrink\": .8})plt.show()"
},
{
"code": null,
"e": 3672,
"s": 3608,
"text": "There are lots of other arguments to be explored with .heatmap."
},
{
"code": null,
"e": 3814,
"s": 3672,
"text": "For example linewidth defines the size of the line between the boxes, and we can even pass arguments directly to the color bar with cbar_kws."
},
{
"code": null,
"e": 3985,
"s": 3814,
"text": "The colors look good, and now we can move our attention to the ticks. I don’t think CAD_USD-1 is the right name for January. Let’s replace them with some friendlier text."
},
{
"code": null,
"e": 4238,
"s": 3985,
"text": "Moving the ticks to the top of the chart would improve the visualization and make it look more like a table. We can also eliminate the x and y labels since the values in our axis are pretty self-explaining, and the title would also make them redundant."
},
{
"code": null,
"e": 4769,
"s": 4238,
"text": "# figurefig, ax = plt.subplots(figsize=(11, 9))# plot heatmapsb.heatmap(df_m, cmap=\"Blues\", vmin= 0.9, vmax=1.65, square=True, linewidth=0.3, cbar_kws={\"shrink\": .8})# xticksax.xaxis.tick_top()xticks_labels = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']plt.xticks(np.arange(12) + .5, labels=xticks_labels)# axis labelsplt.xlabel('')plt.ylabel('')# titletitle = 'monthly Average exchange rate\\nValue of one USD in CAD\\n'.upper()plt.title(title, loc='left')plt.show()"
},
{
"code": null,
"e": 4932,
"s": 4769,
"text": "There’s one last argument I passed to the heatmap, which is square. That will make the cells of our matrix in a square shape regardless of the size of the figure."
},
{
"code": null,
"e": 5190,
"s": 4932,
"text": "Overall, it looks good. We can see that the U.S. dollar was almost 50% higher than the Canadian in the early 2000s, which started changing around 2003. This lower dollar was sustained until late 2014, with some variation during the financial crisis of 2008."
},
{
"code": null,
"e": 5327,
"s": 5190,
"text": "By 2015 it had stabilized around 1.20~1.40, with relatively slight variation in the monthly averages until 2019, the end of our records."
},
{
"code": null,
"e": 5440,
"s": 5327,
"text": "For the following example, I’ll go through a correlation matrix to see some more functions of Seaborn’s heatmap."
},
{
"code": null,
"e": 5539,
"s": 5440,
"text": "The dataset is a sample of 80 different kinds of cereal, and I want to look at their compositions."
},
{
"code": null,
"e": 5599,
"s": 5539,
"text": "To build the correlation matrix, we can use Pandas .corr()."
},
{
"code": null,
"e": 5849,
"s": 5599,
"text": "# read datasetdf = pd.read_csv('data/cereal.csv')# get correlationsdf_corr = df.corr()# irrelevant fieldsfields = ['rating', 'shelf', 'cups', 'weight']# drop rowsdf_corr.drop(fields, inplace=True)# drop colsdf_corr.drop(fields, axis=1, inplace=True)"
},
{
"code": null,
"e": 5972,
"s": 5849,
"text": "There’s lots of redundancy in a correlation matrix; the upper triangle of the table has the same information as the lower."
},
{
"code": null,
"e": 6063,
"s": 5972,
"text": "Luckily we can use masks with Seaborn’s heatmap, and Numpy has the functions to build one."
},
{
"code": null,
"e": 6100,
"s": 6063,
"text": "np.ones_like(df_corr, dtype=np.bool)"
},
{
"code": null,
"e": 6252,
"s": 6100,
"text": "Numpy .ones_like can create a matrix of booleans with the same shape as our data frame, while .triu will return only the upper triangle of that matrix."
},
{
"code": null,
"e": 6305,
"s": 6252,
"text": "mask = np.triu(np.ones_like(df_corr, dtype=np.bool))"
},
{
"code": null,
"e": 6375,
"s": 6305,
"text": "The mask can help, but there are still two empty cells in our matrix."
},
{
"code": null,
"e": 6560,
"s": 6375,
"text": "There’s nothing wrong with it. Those values can add to the symmetry of our plot — That is to say, it’s easier to know two lists are the same if they start and end with the same values."
},
{
"code": null,
"e": 6639,
"s": 6560,
"text": "If like me, you’re bothered with that, you can filter those out when plotting."
},
{
"code": null,
"e": 6981,
"s": 6639,
"text": "fig, ax = plt.subplots(figsize=(10, 8))# maskmask = np.triu(np.ones_like(df_corr, dtype=np.bool))# adjust mask and dfmask = mask[1:, :-1]corr = df_corr.iloc[1:,:-1].copy()# plot heatmapsb.heatmap(corr, mask=mask, annot=True, fmt=\".2f\", cmap='Blues', vmin=-1, vmax=1, cbar_kws={\"shrink\": .8})# yticksplt.yticks(rotation=0)plt.show()"
},
{
"code": null,
"e": 7133,
"s": 6981,
"text": "Cool, the only thing not mentioned was the annotations. We can set those with the parameter annot and we can pass a formatting function to it with fmt."
},
{
"code": null,
"e": 7241,
"s": 7133,
"text": "We still need a title, and the ticks would look better with an upper case, but that’s not the priority yet."
},
{
"code": null,
"e": 7377,
"s": 7241,
"text": "Correlations range from -1 to 1, so they have two directions, and in this case, a diverging palette works better than a sequential one."
},
{
"code": null,
"e": 7559,
"s": 7377,
"text": "Seaborn has an efficient method for that, called .diverging_palette, it serves to build the colormaps we need with one color on each side, converging to another color in the center."
},
{
"code": null,
"e": 7686,
"s": 7559,
"text": "That method uses HUSL colors, so you need hue, saturation, and lightness. I used hsluv.org to select the colors of this chart."
},
{
"code": null,
"e": 8395,
"s": 7686,
"text": "fig, ax = plt.subplots(figsize=(12, 10))# maskmask = np.triu(np.ones_like(df_corr, dtype=np.bool))# adjust mask and dfmask = mask[1:, :-1]corr = df_corr.iloc[1:,:-1].copy()# color mapcmap = sb.diverging_palette(0, 230, 90, 60, as_cmap=True)# plot heatmapsb.heatmap(corr, mask=mask, annot=True, fmt=\".2f\", linewidths=5, cmap=cmap, vmin=-1, vmax=1, cbar_kws={\"shrink\": .8}, square=True)# ticksyticks = [i.upper() for i in corr.index]xticks = [i.upper() for i in corr.columns]plt.yticks(plt.yticks()[0], labels=yticks, rotation=0)plt.xticks(plt.xticks()[0], labels=xticks)# titletitle = 'CORRELATION MATRIX\\nSAMPLED CEREALS COMPOSITION\\n'plt.title(title, loc='left', fontsize=18)plt.show()"
},
{
"code": null,
"e": 8580,
"s": 8395,
"text": "Pretty cool, we built a beautiful visualization for the correlation matrix. Now it’s easier to see the most significant correlation coefficients, like Fiber and Potassium, for example."
},
{
"code": null,
"e": 8683,
"s": 8580,
"text": "Usually, after a correlation matrix, we get a better look at the variables with a strong relationship."
},
{
"code": null,
"e": 8813,
"s": 8683,
"text": "In this case, we don’t have too much data to look into, so a scatter plot would be enough to start investigating those variables."
},
{
"code": null,
"e": 9002,
"s": 8813,
"text": "The problem with scatter plots is that they tend to become hard to read with too much data, as the points start to overlap. That’s when heatmaps get back in the scene to visualize density."
},
{
"code": null,
"e": 9197,
"s": 9002,
"text": "fig, ax = plt.subplots(1, figsize=(12,8))sb.kdeplot(df.potass, df.fiber, cmap='Blues', shade=True, shade_lowest=False, clip=(-1,300))plt.scatter(df.potass, df.fiber, color='orangered')"
},
{
"code": null,
"e": 9317,
"s": 9197,
"text": "If you’re interested in learning more about KDE, I suggest you get a look at Matthew Conlen’s article about this topic."
},
{
"code": null,
"e": 9468,
"s": 9317,
"text": "Well, we explored most of the basics in heatmaps and looked at how they can increase complexity with color maps, bars, masks, and density estimations."
},
{
"code": null,
"e": 9522,
"s": 9468,
"text": "Thanks for reading my article. I hope you enjoyed it."
},
{
"code": null,
"e": 9579,
"s": 9522,
"text": "Here you can find more tutorials on DataViz with Python."
}
]
|
Check if MongoDB database exists? | There are two possibilities to check if MongoDB database exists.
Case 1: The first possibility is that the MongoDB database exists i.e. it returns particular index.
Case 2: The second possibility is that the MongoDB database does not exist i.e. it returns index -1.
NOTE: An index starts from 0 and ends with (N-1) like an array.
The syntax is as follows to check if MongoDB database exists.
db.getMongo().getDBNames().indexOf("yourDatabaseName");
Case 1: Let us implement the above syntax to check if MongoDB database exists. Following is the query
db.getMongo().getDBNames().indexOf("test");
This will produce the following output
6
Look at the above sample output, we are getting 6 that means the database “test” exists and it is present at index 6.
Let us check all the databases now. Following is the query
> show dbs;
This will produce the following output
admin 0.001GB
config 0.000GB
local 0.000GB
sample 0.001GB
sampleDemo 0.000GB
studentSearch 0.000GB
test 0.009GB
Look at the above sample output, the database “test” exists and at index 6.
Case 2: If MongoDB database does not exist
> db.getMongo().getDBNames().indexOf("education");
The following is the output displaying -1 since the database “education” does not exist
-1 | [
{
"code": null,
"e": 1127,
"s": 1062,
"text": "There are two possibilities to check if MongoDB database exists."
},
{
"code": null,
"e": 1227,
"s": 1127,
"text": "Case 1: The first possibility is that the MongoDB database exists i.e. it returns particular index."
},
{
"code": null,
"e": 1328,
"s": 1227,
"text": "Case 2: The second possibility is that the MongoDB database does not exist i.e. it returns index -1."
},
{
"code": null,
"e": 1392,
"s": 1328,
"text": "NOTE: An index starts from 0 and ends with (N-1) like an array."
},
{
"code": null,
"e": 1454,
"s": 1392,
"text": "The syntax is as follows to check if MongoDB database exists."
},
{
"code": null,
"e": 1510,
"s": 1454,
"text": "db.getMongo().getDBNames().indexOf(\"yourDatabaseName\");"
},
{
"code": null,
"e": 1612,
"s": 1510,
"text": "Case 1: Let us implement the above syntax to check if MongoDB database exists. Following is the query"
},
{
"code": null,
"e": 1656,
"s": 1612,
"text": "db.getMongo().getDBNames().indexOf(\"test\");"
},
{
"code": null,
"e": 1695,
"s": 1656,
"text": "This will produce the following output"
},
{
"code": null,
"e": 1697,
"s": 1695,
"text": "6"
},
{
"code": null,
"e": 1815,
"s": 1697,
"text": "Look at the above sample output, we are getting 6 that means the database “test” exists and it is present at index 6."
},
{
"code": null,
"e": 1874,
"s": 1815,
"text": "Let us check all the databases now. Following is the query"
},
{
"code": null,
"e": 1886,
"s": 1874,
"text": "> show dbs;"
},
{
"code": null,
"e": 1925,
"s": 1886,
"text": "This will produce the following output"
},
{
"code": null,
"e": 2107,
"s": 1925,
"text": "admin 0.001GB\nconfig 0.000GB\nlocal 0.000GB\nsample 0.001GB\nsampleDemo 0.000GB\nstudentSearch 0.000GB\ntest 0.009GB"
},
{
"code": null,
"e": 2183,
"s": 2107,
"text": "Look at the above sample output, the database “test” exists and at index 6."
},
{
"code": null,
"e": 2226,
"s": 2183,
"text": "Case 2: If MongoDB database does not exist"
},
{
"code": null,
"e": 2277,
"s": 2226,
"text": "> db.getMongo().getDBNames().indexOf(\"education\");"
},
{
"code": null,
"e": 2365,
"s": 2277,
"text": "The following is the output displaying -1 since the database “education” does not exist"
},
{
"code": null,
"e": 2368,
"s": 2365,
"text": "-1"
}
]
|
What is strstr() Function in C language? | The C library function char *strstr(const char *haystack, const char *needle) function finds the first occurrence of the substring needle in the string haystack. The terminating '\0' characters are not compared.
An array of characters is called a string.
The syntax for declaring an array is as follows −
char stringname [size];
For example − char string[50]; string of length 50 characters
Using single character constant −
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}
Using string constants −
char string[10] = "Hello":;
Accessing − There is a control string "%s" used for accessing the string till it encounters ‘\0’.
It is used to search whether a substring is present in the main string or not.
It is used to search whether a substring is present in the main string or not.
It returns pointer to first occurrence of s2 in s1.
It returns pointer to first occurrence of s2 in s1.
The syntax for strstr() function is as follows −
strstr(mainsring,substring);
The following program shows the usage of strstr() function.
Live Demo
#include<stdio.h>
void main(){
char a[30],b[30];
char *found;
printf("Enter a string:\n");
gets(a);
printf("Enter the string to be searched for:\n");
gets(b);
found=strstr(a,b);
if(found)
printf("%s is found in %s in %d position",a,b,found-a);
else
printf("-1 since the string is not found");
}
When the above program is executed, it produces the following result −
Enter a string: how are you
Enter the string to be searched for: you
you is found in 8 position
Let’s see another program on strstr() function.
Given below is a C program to find, if a string is present in another string as substring by using strstr library function −
Live Demo
#include<stdio.h>
#include<string.h>
void main(){
//Declaring two strings//
char mainstring[50],substring[50];
char *exists;
//Reading strings//
printf("Enter the main string : \n ");
gets(mainstring);
printf("Enter the sub string you would want to check if exists in main string :");
gets(substring);
//Searching for sub string in main string using library function//
exists = strstr(mainstring,substring);
//Conditions//
if(exists){
printf("%s exists in %s ",substring,mainstring);
} else {
printf("'%s' is not present in '%s'",substring,mainstring);
}
}
When the above program is executed, it produces the following result −
Enter the main string : TutorialsPoint c Programming
Enter the sub string you would want to check if exists in main string :Programming
Programming exists in TutorialsPoint c Programming | [
{
"code": null,
"e": 1274,
"s": 1062,
"text": "The C library function char *strstr(const char *haystack, const char *needle) function finds the first occurrence of the substring needle in the string haystack. The terminating '\\0' characters are not compared."
},
{
"code": null,
"e": 1317,
"s": 1274,
"text": "An array of characters is called a string."
},
{
"code": null,
"e": 1367,
"s": 1317,
"text": "The syntax for declaring an array is as follows −"
},
{
"code": null,
"e": 1391,
"s": 1367,
"text": "char stringname [size];"
},
{
"code": null,
"e": 1453,
"s": 1391,
"text": "For example − char string[50]; string of length 50 characters"
},
{
"code": null,
"e": 1487,
"s": 1453,
"text": "Using single character constant −"
},
{
"code": null,
"e": 1538,
"s": 1487,
"text": "char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\\0’}"
},
{
"code": null,
"e": 1563,
"s": 1538,
"text": "Using string constants −"
},
{
"code": null,
"e": 1591,
"s": 1563,
"text": "char string[10] = \"Hello\":;"
},
{
"code": null,
"e": 1689,
"s": 1591,
"text": "Accessing − There is a control string \"%s\" used for accessing the string till it encounters ‘\\0’."
},
{
"code": null,
"e": 1768,
"s": 1689,
"text": "It is used to search whether a substring is present in the main string or not."
},
{
"code": null,
"e": 1847,
"s": 1768,
"text": "It is used to search whether a substring is present in the main string or not."
},
{
"code": null,
"e": 1899,
"s": 1847,
"text": "It returns pointer to first occurrence of s2 in s1."
},
{
"code": null,
"e": 1951,
"s": 1899,
"text": "It returns pointer to first occurrence of s2 in s1."
},
{
"code": null,
"e": 2000,
"s": 1951,
"text": "The syntax for strstr() function is as follows −"
},
{
"code": null,
"e": 2029,
"s": 2000,
"text": "strstr(mainsring,substring);"
},
{
"code": null,
"e": 2089,
"s": 2029,
"text": "The following program shows the usage of strstr() function."
},
{
"code": null,
"e": 2100,
"s": 2089,
"text": " Live Demo"
},
{
"code": null,
"e": 2434,
"s": 2100,
"text": "#include<stdio.h>\nvoid main(){\n char a[30],b[30];\n char *found;\n printf(\"Enter a string:\\n\");\n gets(a);\n printf(\"Enter the string to be searched for:\\n\");\n gets(b);\n found=strstr(a,b);\n if(found)\n printf(\"%s is found in %s in %d position\",a,b,found-a);\n else\n printf(\"-1 since the string is not found\");\n}"
},
{
"code": null,
"e": 2505,
"s": 2434,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 2601,
"s": 2505,
"text": "Enter a string: how are you\nEnter the string to be searched for: you\nyou is found in 8 position"
},
{
"code": null,
"e": 2649,
"s": 2601,
"text": "Let’s see another program on strstr() function."
},
{
"code": null,
"e": 2774,
"s": 2649,
"text": "Given below is a C program to find, if a string is present in another string as substring by using strstr library function −"
},
{
"code": null,
"e": 2785,
"s": 2774,
"text": " Live Demo"
},
{
"code": null,
"e": 3396,
"s": 2785,
"text": "#include<stdio.h>\n#include<string.h>\nvoid main(){\n //Declaring two strings//\n char mainstring[50],substring[50];\n char *exists;\n //Reading strings//\n printf(\"Enter the main string : \\n \");\n gets(mainstring);\n printf(\"Enter the sub string you would want to check if exists in main string :\");\n gets(substring);\n //Searching for sub string in main string using library function//\n exists = strstr(mainstring,substring);\n //Conditions//\n if(exists){\n printf(\"%s exists in %s \",substring,mainstring);\n } else {\n printf(\"'%s' is not present in '%s'\",substring,mainstring);\n }\n}"
},
{
"code": null,
"e": 3467,
"s": 3396,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 3654,
"s": 3467,
"text": "Enter the main string : TutorialsPoint c Programming\nEnter the sub string you would want to check if exists in main string :Programming\nProgramming exists in TutorialsPoint c Programming"
}
]
|
Sort an array of 0s, 1s and 2s | Practice | GeeksforGeeks | Given an array of size N containing only 0s, 1s, and 2s; sort the array in ascending order.
Example 1:
Input:
N = 5
arr[]= {0 2 1 2 0}
Output:
0 0 1 2 2
Explanation:
0s 1s and 2s are segregated
into ascending order.
Example 2:
Input:
N = 3
arr[] = {0 1 0}
Output:
0 0 1
Explanation:
0s 1s and 2s are segregated
into ascending order.
Your Task:
You don't need to read input or print anything. Your task is to complete the function sort012() that takes an array arr and N as input parameters and sorts the array in-place.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1 <= N <= 10^6
0 <= A[i] <= 2
0
ashutosh998 hours ago
Can anyone tell why its failing for large array size.
def sort012(self,arr,n): # code here c = 0; d = n-1; for i in range(n-1): if(arr[i]==0): temp = arr[i]; arr[i]=arr[c]; arr[c]=temp; c +=1; if(arr[i]==2): temp = arr[i]; arr[i]= arr[d]; arr[d]= temp; d -= 1; return arr;
0
hunger4codes14 hours ago
class Solution
{
public static void sort012(int a[], int n)
{
int lo=0,mid=0;int hi=n-1;
while(mid<=hi){
if(a[mid]==0){
swap(a,mid,lo);
lo++;mid++;
}
else if(a[mid]==1)
mid++;
else{
swap(a,mid,hi);
hi--;
}
}
}
private static void swap(int[] a, int mid, int lo) {
int temp=a[lo];
a[lo]=a[mid];
a[mid]=temp;
}
}
-2
madhavendradey1 day ago
//Java Solution
class Solution{ public static void sort012(int a[], int n) { Arrays.sort(a); }}
+1
98ankit471 day ago
int count0=0,count1=0,count2=0; for(int i=0;i<n;i++) { if(a[i]==0) { ++count0; } if(a[i]==1) { ++count1; } if(a[i]==2) { ++count2; } } for(int i=0;i<n;i++) { if(i<count0) { a[i]=0; } else if(i>=count0 && i<count0+count1) { a[i]=1; } else if(i>=count0+count1 &&i<count0+count1+count2) { a[i]=2; } } }
0
sagarsgghule2 days ago
public static void sort012(int a[], int n) { // code here int zero = 0; int one = 0; for(int i =0; i<n; i++) { if(a[i] == 0) zero++; else if(a[i] == 1) one++; } for(int i=0; i<n; i++) { if(zero != 0) { a[i] = 0; zero--; } else if(one != 0) { a[i] = 1; one--; } else a[i] = 2; } }
+1
rohitkumar010919972 days ago
void sort012(int a[], int n) { // code here int count0=0, count1=0,count2=0; for(int i=0;i<n;i++){ if(a[i]==0) count0++; else if(a[i]==1) count1++; else count2++; } for(int i=0; i<count0; i++){ a[i] = 0; } for(int i=count0; i<(count0+count1); i++){ a[i] = 1; } for(int i=(count0+count1); i<n; i++){ a[i]=2; } }
0
srijan786mohinesh3 days ago
plss koi batao what is problem in this int x=-1; int l=0; for (int i = 0; i < 3; i++) { x++; for (int j = 0; j < n; j++) { if (a[j]==x) { a[l]=x; l++; } } }
0
deepeshdhaundiyal4 days ago
int count0 = 0; int count1 = 0; int count2 = 0; for(int i =0; i<n; i++) { if(a[i] == 0) { count0++; } else if(a[i]==1) { count1++; } else if(a[i]==2) { count2++; } } for(int i =0; i<n; i++) { if(count0 != 0) { a[i]=0; count0--; } else if(count1 != 0) { a[i]=1; count1--; } else if(count2 != 0) { a[i]=2; count2--; } }
-2
kalaiabster4 days ago
JAVA SOLUTION :
public static void sort012(int a[], int n) { Arrays.sort(a); }
0
torq12845 days ago
void sort012(int a[], int n)
{
// coode here
int l=0,m=0,h=n-1;
while(m<=h)
{
if(a[m]==0)
{
swap(a[m],a[l]);
l++;
m++;
}
else if(a[m]==1)
m++;
else if(a[m]==2)
{
swap(a[m],a[h]);
h--;
}
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 330,
"s": 238,
"text": "Given an array of size N containing only 0s, 1s, and 2s; sort the array in ascending order."
},
{
"code": null,
"e": 342,
"s": 330,
"text": "\nExample 1:"
},
{
"code": null,
"e": 457,
"s": 342,
"text": "Input: \nN = 5\narr[]= {0 2 1 2 0}\nOutput:\n0 0 1 2 2\nExplanation:\n0s 1s and 2s are segregated \ninto ascending order."
},
{
"code": null,
"e": 468,
"s": 457,
"text": "Example 2:"
},
{
"code": null,
"e": 576,
"s": 468,
"text": "Input: \nN = 3\narr[] = {0 1 0}\nOutput:\n0 0 1\nExplanation:\n0s 1s and 2s are segregated \ninto ascending order."
},
{
"code": null,
"e": 765,
"s": 576,
"text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function sort012() that takes an array arr and N as input parameters and sorts the array in-place. "
},
{
"code": null,
"e": 828,
"s": 765,
"text": "\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 872,
"s": 828,
"text": "\nConstraints:\n1 <= N <= 10^6\n0 <= A[i] <= 2"
},
{
"code": null,
"e": 874,
"s": 872,
"text": "0"
},
{
"code": null,
"e": 896,
"s": 874,
"text": "ashutosh998 hours ago"
},
{
"code": null,
"e": 950,
"s": 896,
"text": "Can anyone tell why its failing for large array size."
},
{
"code": null,
"e": 1334,
"s": 952,
"text": "def sort012(self,arr,n): # code here c = 0; d = n-1; for i in range(n-1): if(arr[i]==0): temp = arr[i]; arr[i]=arr[c]; arr[c]=temp; c +=1; if(arr[i]==2): temp = arr[i]; arr[i]= arr[d]; arr[d]= temp; d -= 1; return arr; "
},
{
"code": null,
"e": 1336,
"s": 1334,
"text": "0"
},
{
"code": null,
"e": 1361,
"s": 1336,
"text": "hunger4codes14 hours ago"
},
{
"code": null,
"e": 1844,
"s": 1361,
"text": "class Solution\n{\n public static void sort012(int a[], int n)\n {\n int lo=0,mid=0;int hi=n-1;\n while(mid<=hi){\n if(a[mid]==0){\n swap(a,mid,lo);\n lo++;mid++;\n }\n else if(a[mid]==1)\n mid++;\n else{\n swap(a,mid,hi);\n hi--;\n }\n }\n }\n private static void swap(int[] a, int mid, int lo) {\n int temp=a[lo];\n a[lo]=a[mid];\n a[mid]=temp;\n }"
},
{
"code": null,
"e": 1847,
"s": 1844,
"text": "} "
},
{
"code": null,
"e": 1850,
"s": 1847,
"text": "-2"
},
{
"code": null,
"e": 1874,
"s": 1850,
"text": "madhavendradey1 day ago"
},
{
"code": null,
"e": 1890,
"s": 1874,
"text": "//Java Solution"
},
{
"code": null,
"e": 1984,
"s": 1892,
"text": "class Solution{ public static void sort012(int a[], int n) { Arrays.sort(a); }}"
},
{
"code": null,
"e": 1987,
"s": 1984,
"text": "+1"
},
{
"code": null,
"e": 2006,
"s": 1987,
"text": "98ankit471 day ago"
},
{
"code": null,
"e": 2608,
"s": 2006,
"text": "int count0=0,count1=0,count2=0; for(int i=0;i<n;i++) { if(a[i]==0) { ++count0; } if(a[i]==1) { ++count1; } if(a[i]==2) { ++count2; } } for(int i=0;i<n;i++) { if(i<count0) { a[i]=0; } else if(i>=count0 && i<count0+count1) { a[i]=1; } else if(i>=count0+count1 &&i<count0+count1+count2) { a[i]=2; } } }"
},
{
"code": null,
"e": 2610,
"s": 2608,
"text": "0"
},
{
"code": null,
"e": 2633,
"s": 2610,
"text": "sagarsgghule2 days ago"
},
{
"code": null,
"e": 3174,
"s": 2633,
"text": "public static void sort012(int a[], int n) { // code here int zero = 0; int one = 0; for(int i =0; i<n; i++) { if(a[i] == 0) zero++; else if(a[i] == 1) one++; } for(int i=0; i<n; i++) { if(zero != 0) { a[i] = 0; zero--; } else if(one != 0) { a[i] = 1; one--; } else a[i] = 2; } }"
},
{
"code": null,
"e": 3177,
"s": 3174,
"text": "+1"
},
{
"code": null,
"e": 3206,
"s": 3177,
"text": "rohitkumar010919972 days ago"
},
{
"code": null,
"e": 3642,
"s": 3206,
"text": "void sort012(int a[], int n) { // code here int count0=0, count1=0,count2=0; for(int i=0;i<n;i++){ if(a[i]==0) count0++; else if(a[i]==1) count1++; else count2++; } for(int i=0; i<count0; i++){ a[i] = 0; } for(int i=count0; i<(count0+count1); i++){ a[i] = 1; } for(int i=(count0+count1); i<n; i++){ a[i]=2; } }"
},
{
"code": null,
"e": 3644,
"s": 3642,
"text": "0"
},
{
"code": null,
"e": 3672,
"s": 3644,
"text": "srijan786mohinesh3 days ago"
},
{
"code": null,
"e": 3928,
"s": 3672,
"text": "plss koi batao what is problem in this int x=-1; int l=0; for (int i = 0; i < 3; i++) { x++; for (int j = 0; j < n; j++) { if (a[j]==x) { a[l]=x; l++; } } }"
},
{
"code": null,
"e": 3930,
"s": 3928,
"text": "0"
},
{
"code": null,
"e": 3958,
"s": 3930,
"text": "deepeshdhaundiyal4 days ago"
},
{
"code": null,
"e": 4652,
"s": 3958,
"text": " int count0 = 0; int count1 = 0; int count2 = 0; for(int i =0; i<n; i++) { if(a[i] == 0) { count0++; } else if(a[i]==1) { count1++; } else if(a[i]==2) { count2++; } } for(int i =0; i<n; i++) { if(count0 != 0) { a[i]=0; count0--; } else if(count1 != 0) { a[i]=1; count1--; } else if(count2 != 0) { a[i]=2; count2--; } }"
},
{
"code": null,
"e": 4655,
"s": 4652,
"text": "-2"
},
{
"code": null,
"e": 4677,
"s": 4655,
"text": "kalaiabster4 days ago"
},
{
"code": null,
"e": 4693,
"s": 4677,
"text": "JAVA SOLUTION :"
},
{
"code": null,
"e": 4767,
"s": 4693,
"text": " public static void sort012(int a[], int n) { Arrays.sort(a); }"
},
{
"code": null,
"e": 4769,
"s": 4767,
"text": "0"
},
{
"code": null,
"e": 4788,
"s": 4769,
"text": "torq12845 days ago"
},
{
"code": null,
"e": 5198,
"s": 4788,
"text": " void sort012(int a[], int n)\n {\n // coode here \n int l=0,m=0,h=n-1;\n while(m<=h)\n {\n if(a[m]==0)\n {\n swap(a[m],a[l]);\n l++;\n m++;\n }\n else if(a[m]==1)\n m++;\n else if(a[m]==2)\n {\n swap(a[m],a[h]);\n h--;\n }\n }"
},
{
"code": null,
"e": 5344,
"s": 5198,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 5380,
"s": 5344,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5390,
"s": 5380,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5400,
"s": 5390,
"text": "\nContest\n"
},
{
"code": null,
"e": 5463,
"s": 5400,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5611,
"s": 5463,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 5819,
"s": 5611,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 5925,
"s": 5819,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
]
|
DynamoDB - Update Items | Updating an item in DynamoDB mainly consists of specifying the full primary key and table name for the item. It requires a new value for each attribute you modify. The operation uses UpdateItem, which modifies the existing items or creates them on discovery of a missing item.
In updates, you might want to track the changes by displaying the original and new values, before and after the operations. UpdateItem uses the ReturnValues parameter to achieve this.
Note − The operation does not report capacity unit consumption, but you can use the ReturnConsumedCapacity parameter.
Use the GUI console, Java, or any other tool to perform this task.
Navigate to the console. In the navigation pane on the left side, select Tables. Choose the table needed, and then select the Items tab.
Choose the item desired for an update, and select Actions | Edit.
Modify any attributes or values necessary in the Edit Item window.
Using Java in the item update operations requires creating a Table class instance, and calling its updateItem method. Then you specify the item's primary key, and provide an UpdateExpression detailing attribute modifications.
The Following is an example of the same −
DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient(
new ProfileCredentialsProvider()));
Table table = dynamoDB.getTable("ProductList");
Map<String, String> expressionAttributeNames = new HashMap<String, String>();
expressionAttributeNames.put("#M", "Make");
expressionAttributeNames.put("#P", "Price
expressionAttributeNames.put("#N", "ID");
Map<String, Object> expressionAttributeValues = new HashMap<String, Object>();
expressionAttributeValues.put(":val1",
new HashSet<String>(Arrays.asList("Make1","Make2")));
expressionAttributeValues.put(":val2", 1); //Price
UpdateItemOutcome outcome = table.updateItem(
"internalID", // key attribute name
111, // key attribute value
"add #M :val1 set #P = #P - :val2 remove #N", // UpdateExpression
expressionAttributeNames,
expressionAttributeValues);
The updateItem method also allows for specifying conditions, which can be seen in the following example −
Table table = dynamoDB.getTable("ProductList");
Map<String, String> expressionAttributeNames = new HashMap<String, String>();
expressionAttributeNames.put("#P", "Price");
Map<String, Object> expressionAttributeValues = new HashMap<String, Object>();
expressionAttributeValues.put(":val1", 44); // change Price to 44
expressionAttributeValues.put(":val2", 15); // only if currently 15
UpdateItemOutcome outcome = table.updateItem (new PrimaryKey("internalID",111),
"set #P = :val1", // Update
"#P = :val2", // Condition
expressionAttributeNames,
expressionAttributeValues);
DynamoDB allows atomic counters, which means using UpdateItem to increment/decrement attribute values without impacting other requests; furthermore, the counters always update.
The following is an example that explains how it can be done.
Note − The following sample may assume a previously created data source. Before attempting to execute, acquire supporting libraries and create necessary data sources (tables with required characteristics, or other referenced sources).
This sample also uses Eclipse IDE, an AWS credentials file, and the AWS Toolkit within an Eclipse AWS Java Project.
package com.amazonaws.codesamples.document;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.document.DeleteItemOutcome;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.dynamodbv2.document.UpdateItemOutcome;
import com.amazonaws.services.dynamodbv2.document.spec.DeleteItemSpec;
import com.amazonaws.services.dynamodbv2.document.spec.UpdateItemSpec;
import com.amazonaws.services.dynamodbv2.document.utils.NameMap;
import com.amazonaws.services.dynamodbv2.document.utils.ValueMap;
import com.amazonaws.services.dynamodbv2.model.ReturnValue;
public class UpdateItemOpSample {
static DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient(
new ProfileCredentialsProvider()));
static String tblName = "ProductList";
public static void main(String[] args) throws IOException {
createItems();
retrieveItem();
// Execute updates
updateMultipleAttributes();
updateAddNewAttribute();
updateExistingAttributeConditionally();
// Item deletion
deleteItem();
}
private static void createItems() {
Table table = dynamoDB.getTable(tblName);
try {
Item item = new Item()
.withPrimaryKey("ID", 303)
.withString("Nomenclature", "Polymer Blaster 4000")
.withStringSet( "Manufacturers",
new HashSet<String>(Arrays.asList("XYZ Inc.", "LMNOP Inc.")))
.withNumber("Price", 50000)
.withBoolean("InProduction", true)
.withString("Category", "Laser Cutter");
table.putItem(item);
item = new Item()
.withPrimaryKey("ID", 313)
.withString("Nomenclature", "Agitatatron 2000")
.withStringSet( "Manufacturers",
new HashSet<String>(Arrays.asList("XYZ Inc,", "CDE Inc.")))
.withNumber("Price", 40000)
.withBoolean("InProduction", true)
.withString("Category", "Agitator");
table.putItem(item);
} catch (Exception e) {
System.err.println("Cannot create items.");
System.err.println(e.getMessage());
}
}
private static void updateAddNewAttribute() {
Table table = dynamoDB.getTable(tableName);
try {
Map<String, String> expressionAttributeNames = new HashMap<String, String>();
expressionAttributeNames.put("#na", "NewAttribute");
UpdateItemSpec updateItemSpec = new UpdateItemSpec()
.withPrimaryKey("ID", 303)
.withUpdateExpression("set #na = :val1")
.withNameMap(new NameMap()
.with("#na", "NewAttribute"))
.withValueMap(new ValueMap()
.withString(":val1", "A value"))
.withReturnValues(ReturnValue.ALL_NEW);
UpdateItemOutcome outcome = table.updateItem(updateItemSpec);
// Confirm
System.out.println("Displaying updated item...");
System.out.println(outcome.getItem().toJSONPretty());
} catch (Exception e) {
System.err.println("Cannot add an attribute in " + tableName);
System.err.println(e.getMessage());
}
}
}
16 Lectures
1.5 hours
Harshit Srivastava
49 Lectures
3.5 hours
Niyazi Erdogan
48 Lectures
3 hours
Niyazi Erdogan
13 Lectures
1 hours
Harshit Srivastava
45 Lectures
4 hours
Pranjal Srivastava, Harshit Srivastava
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2668,
"s": 2391,
"text": "Updating an item in DynamoDB mainly consists of specifying the full primary key and table name for the item. It requires a new value for each attribute you modify. The operation uses UpdateItem, which modifies the existing items or creates them on discovery of a missing item."
},
{
"code": null,
"e": 2852,
"s": 2668,
"text": "In updates, you might want to track the changes by displaying the original and new values, before and after the operations. UpdateItem uses the ReturnValues parameter to achieve this."
},
{
"code": null,
"e": 2970,
"s": 2852,
"text": "Note − The operation does not report capacity unit consumption, but you can use the ReturnConsumedCapacity parameter."
},
{
"code": null,
"e": 3037,
"s": 2970,
"text": "Use the GUI console, Java, or any other tool to perform this task."
},
{
"code": null,
"e": 3174,
"s": 3037,
"text": "Navigate to the console. In the navigation pane on the left side, select Tables. Choose the table needed, and then select the Items tab."
},
{
"code": null,
"e": 3240,
"s": 3174,
"text": "Choose the item desired for an update, and select Actions | Edit."
},
{
"code": null,
"e": 3307,
"s": 3240,
"text": "Modify any attributes or values necessary in the Edit Item window."
},
{
"code": null,
"e": 3533,
"s": 3307,
"text": "Using Java in the item update operations requires creating a Table class instance, and calling its updateItem method. Then you specify the item's primary key, and provide an UpdateExpression detailing attribute modifications."
},
{
"code": null,
"e": 3575,
"s": 3533,
"text": "The Following is an example of the same −"
},
{
"code": null,
"e": 4485,
"s": 3575,
"text": "DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient(\n new ProfileCredentialsProvider()));\n \nTable table = dynamoDB.getTable(\"ProductList\");\n\nMap<String, String> expressionAttributeNames = new HashMap<String, String>();\nexpressionAttributeNames.put(\"#M\", \"Make\");\nexpressionAttributeNames.put(\"#P\", \"Price\nexpressionAttributeNames.put(\"#N\", \"ID\");\n\nMap<String, Object> expressionAttributeValues = new HashMap<String, Object>();\nexpressionAttributeValues.put(\":val1\",\n new HashSet<String>(Arrays.asList(\"Make1\",\"Make2\")));\nexpressionAttributeValues.put(\":val2\", 1); //Price\n\nUpdateItemOutcome outcome = table.updateItem(\n \"internalID\", // key attribute name\n 111, // key attribute value\n \"add #M :val1 set #P = #P - :val2 remove #N\", // UpdateExpression\n expressionAttributeNames,\n expressionAttributeValues);"
},
{
"code": null,
"e": 4591,
"s": 4485,
"text": "The updateItem method also allows for specifying conditions, which can be seen in the following example −"
},
{
"code": null,
"e": 5231,
"s": 4591,
"text": "Table table = dynamoDB.getTable(\"ProductList\");\nMap<String, String> expressionAttributeNames = new HashMap<String, String>();\nexpressionAttributeNames.put(\"#P\", \"Price\");\n\nMap<String, Object> expressionAttributeValues = new HashMap<String, Object>();\nexpressionAttributeValues.put(\":val1\", 44); // change Price to 44\nexpressionAttributeValues.put(\":val2\", 15); // only if currently 15\n\nUpdateItemOutcome outcome = table.updateItem (new PrimaryKey(\"internalID\",111),\n \"set #P = :val1\", // Update\n \"#P = :val2\", // Condition \n expressionAttributeNames,\n expressionAttributeValues);"
},
{
"code": null,
"e": 5408,
"s": 5231,
"text": "DynamoDB allows atomic counters, which means using UpdateItem to increment/decrement attribute values without impacting other requests; furthermore, the counters always update."
},
{
"code": null,
"e": 5470,
"s": 5408,
"text": "The following is an example that explains how it can be done."
},
{
"code": null,
"e": 5705,
"s": 5470,
"text": "Note − The following sample may assume a previously created data source. Before attempting to execute, acquire supporting libraries and create necessary data sources (tables with required characteristics, or other referenced sources)."
},
{
"code": null,
"e": 5821,
"s": 5705,
"text": "This sample also uses Eclipse IDE, an AWS credentials file, and the AWS Toolkit within an Eclipse AWS Java Project."
},
{
"code": null,
"e": 9465,
"s": 5821,
"text": "package com.amazonaws.codesamples.document;\n\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\n\nimport com.amazonaws.auth.profile.ProfileCredentialsProvider;\nimport com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;\nimport com.amazonaws.services.dynamodbv2.document.DeleteItemOutcome;\nimport com.amazonaws.services.dynamodbv2.document.DynamoDB;\nimport com.amazonaws.services.dynamodbv2.document.Item;\nimport com.amazonaws.services.dynamodbv2.document.Table;\n\nimport com.amazonaws.services.dynamodbv2.document.UpdateItemOutcome;\nimport com.amazonaws.services.dynamodbv2.document.spec.DeleteItemSpec;\nimport com.amazonaws.services.dynamodbv2.document.spec.UpdateItemSpec;\nimport com.amazonaws.services.dynamodbv2.document.utils.NameMap;\nimport com.amazonaws.services.dynamodbv2.document.utils.ValueMap;\nimport com.amazonaws.services.dynamodbv2.model.ReturnValue;\n\npublic class UpdateItemOpSample { \n static DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient( \n new ProfileCredentialsProvider())); \n static String tblName = \"ProductList\"; \n \n public static void main(String[] args) throws IOException { \n createItems(); \n retrieveItem(); \n \n // Execute updates \n updateMultipleAttributes(); \n updateAddNewAttribute();\n updateExistingAttributeConditionally(); \n \n // Item deletion \n deleteItem(); \n }\n private static void createItems() { \n Table table = dynamoDB.getTable(tblName); \n try { \n Item item = new Item() \n .withPrimaryKey(\"ID\", 303) \n .withString(\"Nomenclature\", \"Polymer Blaster 4000\") \n .withStringSet( \"Manufacturers\",\n new HashSet<String>(Arrays.asList(\"XYZ Inc.\", \"LMNOP Inc.\"))) \n .withNumber(\"Price\", 50000) \n .withBoolean(\"InProduction\", true) \n .withString(\"Category\", \"Laser Cutter\"); \n table.putItem(item); \n \n item = new Item() \n .withPrimaryKey(\"ID\", 313) \n .withString(\"Nomenclature\", \"Agitatatron 2000\") \n .withStringSet( \"Manufacturers\", \n new HashSet<String>(Arrays.asList(\"XYZ Inc,\", \"CDE Inc.\"))) \n .withNumber(\"Price\", 40000) \n .withBoolean(\"InProduction\", true) \n .withString(\"Category\", \"Agitator\"); \n table.putItem(item); \n } catch (Exception e) { \n System.err.println(\"Cannot create items.\"); \n System.err.println(e.getMessage()); \n } \n }\n private static void updateAddNewAttribute() { \n Table table = dynamoDB.getTable(tableName); \n try { \n Map<String, String> expressionAttributeNames = new HashMap<String, String>(); \n expressionAttributeNames.put(\"#na\", \"NewAttribute\"); \n UpdateItemSpec updateItemSpec = new UpdateItemSpec() \n .withPrimaryKey(\"ID\", 303) \n .withUpdateExpression(\"set #na = :val1\") \n .withNameMap(new NameMap() \n .with(\"#na\", \"NewAttribute\")) \n .withValueMap(new ValueMap() \n .withString(\":val1\", \"A value\")) \n .withReturnValues(ReturnValue.ALL_NEW); \n UpdateItemOutcome outcome = table.updateItem(updateItemSpec); \n \n // Confirm \n System.out.println(\"Displaying updated item...\"); \n System.out.println(outcome.getItem().toJSONPretty()); \n } catch (Exception e) { \n System.err.println(\"Cannot add an attribute in \" + tableName); \n System.err.println(e.getMessage()); \n } \n } \n}"
},
{
"code": null,
"e": 9500,
"s": 9465,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 9520,
"s": 9500,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 9555,
"s": 9520,
"text": "\n 49 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 9571,
"s": 9555,
"text": " Niyazi Erdogan"
},
{
"code": null,
"e": 9604,
"s": 9571,
"text": "\n 48 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 9620,
"s": 9604,
"text": " Niyazi Erdogan"
},
{
"code": null,
"e": 9653,
"s": 9620,
"text": "\n 13 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 9673,
"s": 9653,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 9706,
"s": 9673,
"text": "\n 45 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 9746,
"s": 9706,
"text": " Pranjal Srivastava, Harshit Srivastava"
},
{
"code": null,
"e": 9753,
"s": 9746,
"text": " Print"
},
{
"code": null,
"e": 9764,
"s": 9753,
"text": " Add Notes"
}
]
|
Create a Screen recorder using Python - GeeksforGeeks | 05 Sep, 2020
Python is a widely used general-purpose language. It allows performing a variety of tasks. One of them can be recording a video. It provides a module named pyautogui which can be used for the same. This module along with NumPy and OpenCV provides the way to manipulate and save the images (screenshot in this case)
Numpy: To install Numpy type the below command in the terminal.
pip install numpy
pyautogui: To install pyautogui type the below command in the terminal.
pip install pyautogui
OpenCV: To install OpenCV type the below command in the terminal.
pip install opencv-python
Below is the implementation.
First, import all the required packages.
Python3
# importing the required packagesimport pyautoguiimport cv2import numpy as np
Now, before recording the screen, we have to create a VideoWriter object. Also, we have to specify the output file name, Video codec, FPS, and video resolution. In video codec, we have to specify a 4-byte code (such as XVID, MJPG, X264, etc.). We’ll be using XVID here.
Python3
# Specify resolutionresolution = (1920, 1080) # Specify video codeccodec = cv2.VideoWriter_fourcc(*"XVID") # Specify name of Output filefilename = "Recording.avi" # Specify frames rate. We can choose # any value and experiment with itfps = 60.0 # Creating a VideoWriter objectout = cv2.VideoWriter(filename, codec, fps, resolution)
Optional: To display the recording in real-time, we have to create an Empty window and resize it.
Python3
# Create an Empty windowcv2.namedWindow("Live", cv2.WINDOW_NORMAL) # Resize this windowcv2.resizeWindow("Live", 480, 270)
Now, let’s start recording our screen. We will be running an infinite loop and in each iteration of the loop, we will take a screenshot and write it to the output file with the help of the video writer.
Python3
while True: # Take screenshot using PyAutoGUI img = pyautogui.screenshot() # Convert the screenshot to a numpy array frame = np.array(img) # Convert it from BGR(Blue, Green, Red) to # RGB(Red, Green, Blue) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # Write it to the output file out.write(frame) # Optional: Display the recording screen cv2.imshow('Live', frame) # Stop recording when we press 'q' if cv2.waitKey(1) == ord('q'): break
After everything is done, we will release the writer and destroy all windows opened by OpenCV.
Python3
# Release the Video writerout.release() # Destroy all windowscv2.destroyAllWindows()
Full Code:
Python3
# importing the required packagesimport pyautoguiimport cv2import numpy as np # Specify resolutionresolution = (1920, 1080) # Specify video codeccodec = cv2.VideoWriter_fourcc(*"XVID") # Specify name of Output filefilename = "Recording.avi" # Specify frames rate. We can choose any # value and experiment with itfps = 60.0 # Creating a VideoWriter objectout = cv2.VideoWriter(filename, codec, fps, resolution) # Create an Empty windowcv2.namedWindow("Live", cv2.WINDOW_NORMAL) # Resize this windowcv2.resizeWindow("Live", 480, 270) while True: # Take screenshot using PyAutoGUI img = pyautogui.screenshot() # Convert the screenshot to a numpy array frame = np.array(img) # Convert it from BGR(Blue, Green, Red) to # RGB(Red, Green, Blue) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # Write it to the output file out.write(frame) # Optional: Display the recording screen cv2.imshow('Live', frame) # Stop recording when we press 'q' if cv2.waitKey(1) == ord('q'): break # Release the Video writerout.release() # Destroy all windowscv2.destroyAllWindows()
Output:
Python-projects
python-utility
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
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24318,
"s": 24290,
"text": "\n05 Sep, 2020"
},
{
"code": null,
"e": 24633,
"s": 24318,
"text": "Python is a widely used general-purpose language. It allows performing a variety of tasks. One of them can be recording a video. It provides a module named pyautogui which can be used for the same. This module along with NumPy and OpenCV provides the way to manipulate and save the images (screenshot in this case)"
},
{
"code": null,
"e": 24697,
"s": 24633,
"text": "Numpy: To install Numpy type the below command in the terminal."
},
{
"code": null,
"e": 24716,
"s": 24697,
"text": "pip install numpy\n"
},
{
"code": null,
"e": 24788,
"s": 24716,
"text": "pyautogui: To install pyautogui type the below command in the terminal."
},
{
"code": null,
"e": 24811,
"s": 24788,
"text": "pip install pyautogui\n"
},
{
"code": null,
"e": 24877,
"s": 24811,
"text": "OpenCV: To install OpenCV type the below command in the terminal."
},
{
"code": null,
"e": 24903,
"s": 24877,
"text": "pip install opencv-python"
},
{
"code": null,
"e": 24932,
"s": 24903,
"text": "Below is the implementation."
},
{
"code": null,
"e": 24974,
"s": 24932,
"text": "First, import all the required packages. "
},
{
"code": null,
"e": 24982,
"s": 24974,
"text": "Python3"
},
{
"code": "# importing the required packagesimport pyautoguiimport cv2import numpy as np",
"e": 25060,
"s": 24982,
"text": null
},
{
"code": null,
"e": 25330,
"s": 25060,
"text": "Now, before recording the screen, we have to create a VideoWriter object. Also, we have to specify the output file name, Video codec, FPS, and video resolution. In video codec, we have to specify a 4-byte code (such as XVID, MJPG, X264, etc.). We’ll be using XVID here."
},
{
"code": null,
"e": 25338,
"s": 25330,
"text": "Python3"
},
{
"code": "# Specify resolutionresolution = (1920, 1080) # Specify video codeccodec = cv2.VideoWriter_fourcc(*\"XVID\") # Specify name of Output filefilename = \"Recording.avi\" # Specify frames rate. We can choose # any value and experiment with itfps = 60.0 # Creating a VideoWriter objectout = cv2.VideoWriter(filename, codec, fps, resolution)",
"e": 25674,
"s": 25338,
"text": null
},
{
"code": null,
"e": 25772,
"s": 25674,
"text": "Optional: To display the recording in real-time, we have to create an Empty window and resize it."
},
{
"code": null,
"e": 25780,
"s": 25772,
"text": "Python3"
},
{
"code": "# Create an Empty windowcv2.namedWindow(\"Live\", cv2.WINDOW_NORMAL) # Resize this windowcv2.resizeWindow(\"Live\", 480, 270)",
"e": 25903,
"s": 25780,
"text": null
},
{
"code": null,
"e": 26106,
"s": 25903,
"text": "Now, let’s start recording our screen. We will be running an infinite loop and in each iteration of the loop, we will take a screenshot and write it to the output file with the help of the video writer."
},
{
"code": null,
"e": 26114,
"s": 26106,
"text": "Python3"
},
{
"code": "while True: # Take screenshot using PyAutoGUI img = pyautogui.screenshot() # Convert the screenshot to a numpy array frame = np.array(img) # Convert it from BGR(Blue, Green, Red) to # RGB(Red, Green, Blue) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # Write it to the output file out.write(frame) # Optional: Display the recording screen cv2.imshow('Live', frame) # Stop recording when we press 'q' if cv2.waitKey(1) == ord('q'): break",
"e": 26619,
"s": 26114,
"text": null
},
{
"code": null,
"e": 26714,
"s": 26619,
"text": "After everything is done, we will release the writer and destroy all windows opened by OpenCV."
},
{
"code": null,
"e": 26722,
"s": 26714,
"text": "Python3"
},
{
"code": "# Release the Video writerout.release() # Destroy all windowscv2.destroyAllWindows()",
"e": 26808,
"s": 26722,
"text": null
},
{
"code": null,
"e": 26819,
"s": 26808,
"text": "Full Code:"
},
{
"code": null,
"e": 26827,
"s": 26819,
"text": "Python3"
},
{
"code": "# importing the required packagesimport pyautoguiimport cv2import numpy as np # Specify resolutionresolution = (1920, 1080) # Specify video codeccodec = cv2.VideoWriter_fourcc(*\"XVID\") # Specify name of Output filefilename = \"Recording.avi\" # Specify frames rate. We can choose any # value and experiment with itfps = 60.0 # Creating a VideoWriter objectout = cv2.VideoWriter(filename, codec, fps, resolution) # Create an Empty windowcv2.namedWindow(\"Live\", cv2.WINDOW_NORMAL) # Resize this windowcv2.resizeWindow(\"Live\", 480, 270) while True: # Take screenshot using PyAutoGUI img = pyautogui.screenshot() # Convert the screenshot to a numpy array frame = np.array(img) # Convert it from BGR(Blue, Green, Red) to # RGB(Red, Green, Blue) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # Write it to the output file out.write(frame) # Optional: Display the recording screen cv2.imshow('Live', frame) # Stop recording when we press 'q' if cv2.waitKey(1) == ord('q'): break # Release the Video writerout.release() # Destroy all windowscv2.destroyAllWindows()",
"e": 27959,
"s": 26827,
"text": null
},
{
"code": null,
"e": 27967,
"s": 27959,
"text": "Output:"
},
{
"code": null,
"e": 27983,
"s": 27967,
"text": "Python-projects"
},
{
"code": null,
"e": 27998,
"s": 27983,
"text": "python-utility"
},
{
"code": null,
"e": 28005,
"s": 27998,
"text": "Python"
},
{
"code": null,
"e": 28103,
"s": 28005,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28112,
"s": 28103,
"text": "Comments"
},
{
"code": null,
"e": 28125,
"s": 28112,
"text": "Old Comments"
},
{
"code": null,
"e": 28157,
"s": 28125,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28213,
"s": 28157,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28268,
"s": 28213,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 28310,
"s": 28268,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28352,
"s": 28310,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28383,
"s": 28352,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28422,
"s": 28383,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28451,
"s": 28422,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 28473,
"s": 28451,
"text": "Defaultdict in Python"
}
]
|
C library function - strrchr() | The C library function char *strrchr(const char *str, int c) searches for the last occurrence of the character c (an unsigned char) in the string pointed to, by the argument str.
Following is the declaration for strrchr() function.
char *strrchr(const char *str, int c)
str − This is the C string.
str − This is the C string.
c − This is the character to be located. It is passed as its int promotion, but it is internally converted back to char.
c − This is the character to be located. It is passed as its int promotion, but it is internally converted back to char.
This function returns a pointer to the last occurrence of character in str. If the value is not found, the function returns a null pointer.
The following example shows the usage of strrchr() function.
#include <stdio.h>
#include <string.h>
int main () {
int len;
const char str[] = "http://www.tutorialspoint.com";
const char ch = '.';
char *ret;
ret = strrchr(str, ch);
printf("String after |%c| is - |%s|\n", ch, ret);
return(0);
}
Let us compile and run the above program that will produce the following result −
String after |.| is - |.com|
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": 2186,
"s": 2007,
"text": "The C library function char *strrchr(const char *str, int c) searches for the last occurrence of the character c (an unsigned char) in the string pointed to, by the argument str."
},
{
"code": null,
"e": 2239,
"s": 2186,
"text": "Following is the declaration for strrchr() function."
},
{
"code": null,
"e": 2277,
"s": 2239,
"text": "char *strrchr(const char *str, int c)"
},
{
"code": null,
"e": 2305,
"s": 2277,
"text": "str − This is the C string."
},
{
"code": null,
"e": 2333,
"s": 2305,
"text": "str − This is the C string."
},
{
"code": null,
"e": 2454,
"s": 2333,
"text": "c − This is the character to be located. It is passed as its int promotion, but it is internally converted back to char."
},
{
"code": null,
"e": 2575,
"s": 2454,
"text": "c − This is the character to be located. It is passed as its int promotion, but it is internally converted back to char."
},
{
"code": null,
"e": 2715,
"s": 2575,
"text": "This function returns a pointer to the last occurrence of character in str. If the value is not found, the function returns a null pointer."
},
{
"code": null,
"e": 2776,
"s": 2715,
"text": "The following example shows the usage of strrchr() function."
},
{
"code": null,
"e": 3037,
"s": 2776,
"text": "#include <stdio.h>\n#include <string.h>\n\nint main () {\n int len;\n const char str[] = \"http://www.tutorialspoint.com\";\n const char ch = '.';\n char *ret;\n\n ret = strrchr(str, ch);\n\n printf(\"String after |%c| is - |%s|\\n\", ch, ret);\n \n return(0);\n}"
},
{
"code": null,
"e": 3119,
"s": 3037,
"text": "Let us compile and run the above program that will produce the following result −"
},
{
"code": null,
"e": 3149,
"s": 3119,
"text": "String after |.| is - |.com|\n"
},
{
"code": null,
"e": 3182,
"s": 3149,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3197,
"s": 3182,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3232,
"s": 3197,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3247,
"s": 3232,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3282,
"s": 3247,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3296,
"s": 3282,
"text": " Asif Hussain"
},
{
"code": null,
"e": 3329,
"s": 3296,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3347,
"s": 3329,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 3382,
"s": 3347,
"text": "\n 20 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3401,
"s": 3382,
"text": " Vandana Annavaram"
},
{
"code": null,
"e": 3434,
"s": 3401,
"text": "\n 44 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3446,
"s": 3434,
"text": " Amit Diwan"
},
{
"code": null,
"e": 3453,
"s": 3446,
"text": " Print"
},
{
"code": null,
"e": 3464,
"s": 3453,
"text": " Add Notes"
}
]
|
JavaScript: Check if array has an almost increasing sequence | Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.
The sequence a0, a1, ..., an is considered to be a strictly increasing if a0 < a1 < ... < an. Sequence containing only one element is also considered to be strictly increasing.
For sequence = [1, 3, 2, 1], the output should be −
almostIncreasingSequence(sequence) = false.
There is no one element in this array that can be removed in order to get a strictly increasing sequence.
For sequence = [1, 3, 2], the output should be −
almostIncreasingSequence(sequence) = true.
We can remove 3 from the array to get the strictly increasing sequence [1, 2]. Alternately, we can remove 2 to get the strictly increasing sequence [1, 3].
Following is the code −
const arr1 = [3, 5, 67, 98, 3];
const arr2 = [4, 3, 5, 67, 98, 3];
const almostIncreasingSequence = sequence => {
let removed = 0;
let i = 0;
let prev = -Infinity;
while(removed < 2 && i < sequence.length) {
if(sequence[i] > prev) {
prev = sequence[i];
}else{
prev = Math.min(prev, sequence[i]);
removed++;
}
i++;
}
return removed < 2;
};
console.log(almostIncreasingSequence(arr1));
console.log(almostIncreasingSequence(arr2));
This will produce the following output on console −
true
false | [
{
"code": null,
"e": 1231,
"s": 1062,
"text": "Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array."
},
{
"code": null,
"e": 1408,
"s": 1231,
"text": "The sequence a0, a1, ..., an is considered to be a strictly increasing if a0 < a1 < ... < an. Sequence containing only one element is also considered to be strictly increasing."
},
{
"code": null,
"e": 1460,
"s": 1408,
"text": "For sequence = [1, 3, 2, 1], the output should be −"
},
{
"code": null,
"e": 1504,
"s": 1460,
"text": "almostIncreasingSequence(sequence) = false."
},
{
"code": null,
"e": 1610,
"s": 1504,
"text": "There is no one element in this array that can be removed in order to get a strictly increasing sequence."
},
{
"code": null,
"e": 1659,
"s": 1610,
"text": "For sequence = [1, 3, 2], the output should be −"
},
{
"code": null,
"e": 1702,
"s": 1659,
"text": "almostIncreasingSequence(sequence) = true."
},
{
"code": null,
"e": 1858,
"s": 1702,
"text": "We can remove 3 from the array to get the strictly increasing sequence [1, 2]. Alternately, we can remove 2 to get the strictly increasing sequence [1, 3]."
},
{
"code": null,
"e": 1882,
"s": 1858,
"text": "Following is the code −"
},
{
"code": null,
"e": 2380,
"s": 1882,
"text": "const arr1 = [3, 5, 67, 98, 3];\nconst arr2 = [4, 3, 5, 67, 98, 3];\nconst almostIncreasingSequence = sequence => {\n let removed = 0;\n let i = 0;\n let prev = -Infinity;\n while(removed < 2 && i < sequence.length) {\n if(sequence[i] > prev) {\n prev = sequence[i];\n }else{\n prev = Math.min(prev, sequence[i]);\n removed++;\n }\n i++;\n }\n return removed < 2;\n};\nconsole.log(almostIncreasingSequence(arr1));\nconsole.log(almostIncreasingSequence(arr2));"
},
{
"code": null,
"e": 2432,
"s": 2380,
"text": "This will produce the following output on console −"
},
{
"code": null,
"e": 2443,
"s": 2432,
"text": "true\nfalse"
}
]
|
Jython - Event Handling | Event handling in Java swing requires that the control (like JButton or JList etc.) should be registered with the respective event listener. The event listener interface or corresponding Adapter class needs to be either implemented or subclassed with its event handling method overridden. In Jython, the event handling is very simple. We can pass any function as property of event handling function corresponding to the control.
Let us first see how a click event is handled in Java.
To begin with, we have to import the java.awt.event package. Next, the class extending JFrame must implement ActionListener interface.
public class btnclick extends JFrame implements ActionListener
Then, we have to declare the JButton object, add it to the ContentPane of frame and then register it with ActionListener by the addActionListener() method.
JButton b1 = new JButton("Click here");
getContentPane().add(b1);
b1.addActionListener(this);
Now, the actionPerformed() method of the ActionListener interface must be overridden to handle the ActionEvent.
Following is entire Java code −
import java.awt.event.*;
import javax.swing.*;
public class btnclick extends JFrame implements ActionListener {
btnclick() {
JButton b1 = new JButton("Click here");
getContentPane().add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
System.out.println("Clicked");
}
public static void main(String args[]) {
btnclick b = new btnclick();
b.setSize(300,200);
b.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b.setVisible(true);
}
}
Now, we will write the Jython code equivalent to the same code.
To start with, we do not need to import the ActionEvent or the ActionListener, since Jython’s dynamic typing allows us to avoid mentioning these classes in our code.
Secondly, there is no need to implement or subclass ActionListener. Instead, any user defined function is straightaway provided to the JButton constructor as a value of actionPerformed bean property.
button = JButton('Click here!', actionPerformed = clickhere)
The clickhere() function is defined as a regular Jython function, which handles the click event on the button.
def change_text(event):
print clicked!'
Here is the Jython equivalent code.
from javax.swing import JFrame, JButton
frame = JFrame("Hello")
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
frame.setLocation(100,100)
frame.setSize(300,200)
def clickhere(event):
print "clicked"
btn = JButton("Add", actionPerformed = clickhere)
frame.add(btn)
frame.setVisible(True)
The Output of Java and Jython code is identical. When the button is clicked, it will print the ‘clicked’ message on the console.
In the following Jython code, two JTextField objects are provided on the JFrame window to enter marks in ‘phy’ and ‘maths’. The JButton object executes the add() function when clicked.
btn = JButton("Add", actionPerformed = add)
The add() function reads the contents of two text fields by the getText() method and parses them to integers, so that, addition can be performed. The result is then put in the third text field by the setText() method.
def add(event):
print "add"
ttl = int(txt1.getText())+int(txt2.getText())
txt3.setText(str(ttl))
The complete code is given below −
from javax.swing import JFrame, JLabel, JButton, JTextField
from java.awt import Dimension
frame = JFrame("Hello")
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
frame.setLocation(100,100)
frame.setSize(300,200)
frame.setLayout(None)
def add(event):
print "add"
ttl = int(txt1.getText())+int(txt2.getText())
txt3.setText(str(ttl))
lbl1 = JLabel("Phy")
lbl1.setBounds(60,20,40,20)
txt1 = JTextField(10)
txt1.setBounds(120,20,60,20)
lbl2 = JLabel("Maths")
lbl2.setBounds(60,50,40,20)
txt2 = JTextField(10)
txt2.setBounds(120, 50, 60,20)
btn = JButton("Add", actionPerformed = add)
btn.setBounds(60,80,60,20)
lbl3 = JLabel("Total")
lbl3.setBounds(60,110,40,20)
txt3 = JTextField(10)
txt3.setBounds(120, 110, 60,20)
frame.add(lbl1)
frame.add(txt1)
frame.add(lbl2)
frame.add(txt2)
frame.add(btn)
frame.add(lbl3)
frame.add(txt3)
frame.setVisible(True)
When the above code is executed from the command prompt, the following window appears. Enter marks for ‘Phy’, Maths’, and click on the ‘Add’ button. The result will be displayed accordingly.
The JRadioButton class is defined in the javax.swing package. It creates a selectable toggle button with on or off states. If multiple radio buttons are added in a ButtonGroup, their selection is mutually exclusive.
In the following example, two objects of the JRadioButton class and two JLabels are added to a Jpanel container in a vertical BoxLayout. In the constructor of the JRadioButton objects, the OnCheck() function is set as the value of the actionPerformed property. This function is executed when the radio button is clicked to change its state.
rb1 = JRadioButton("Male", True,actionPerformed = OnCheck)
rb2 = JRadioButton("Female", actionPerformed = OnCheck)
Note that the default state of Radio Button is false (not selected). The button rb1 is created with its starting state as True (selected).
The two radio buttons are added to a radio ButtonGroup to make them mutually exclusive, so that if one is selected, other is deselected automatically.
grp = ButtonGroup()
grp.add(rb1)
grp.add(rb2)
These two radio buttons along with two labels are added to a panel object in the vertical layout with a separator area of 25 pixels in heights between rb2 and lbl2.
panel = JPanel()
panel.setLayout(BoxLayout(panel, BoxLayout.Y_AXIS))
panel.add(Box.createVerticalGlue())
panel.add(lbl)
panel.add(rb1)
panel.add(rb2)
panel.add(Box.createRigidArea(Dimension(0,25)))
panel.add(lbl1)
This panel is added to a top-level JFrame object, whose visible property is set to ‘True’ in the end.
frame = JFrame("JRadioButton Example")
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
frame.setLocation(100,100)
frame.setSize(250,200)
frame.setVisible(True)
The complete code of radio.py is given below:
from javax.swing import JFrame, JPanel, JLabel, BoxLayout, Box
from java.awt import Dimension
from javax.swing import JRadioButton,ButtonGroup
frame = JFrame("JRadioButton Example")
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
frame.setLocation(100,100)
frame.setSize(250,200)
panel = JPanel()
panel.setLayout(BoxLayout(panel, BoxLayout.Y_AXIS))
frame.add(panel)
def OnCheck(event):
lbl1.text = ""
if rb1.isSelected():
lbl1.text = lbl1.text+"Gender selection : Male"
else:
lbl1.text = lbl1.text+"Gender selection : Female "
lbl = JLabel("Select Gender")
rb1 = JRadioButton("Male", True,actionPerformed = OnCheck)
rb2 = JRadioButton("Female", actionPerformed = OnCheck)
grp = ButtonGroup()
grp.add(rb1)
grp.add(rb2)
lbl1 = JLabel("Gender Selection :")
panel.add(Box.createVerticalGlue())
panel.add(lbl)
panel.add(rb1)
panel.add(rb2)
panel.add(Box.createRigidArea(Dimension(0,25)))
panel.add(lbl1)
frame.setVisible(True)
Run the above Jython script and change the radio button selection. The selection will appear in the label at the bottom.
Like the JRadioButton, JCheckBox object is also a selectable button with a rectangular checkable box besides its caption. This is generally used to provide user opportunity to select multiple options from the list of items.
In the following example, two check boxes and a label from swing package are added to a JPanel in vertical BoxLayout. The label at bottom displays the instantaneous selection state of two check boxes.
Both checkboxes are declared with the constructor having the actionPerformed property set to the OnCheck() function.
box1 = JCheckBox("Check1", actionPerformed = OnCheck)
box2 = JCheckBox("Check2", actionPerformed = OnCheck)
The OnCheck() function verifies selection state of each check box and displays corresponding message on the label at the bottom.
def OnCheck(event):
lbl1.text = ""
if box1.isSelected():
lbl1.text = lbl1.text + "box1 selected "
else:
lbl1.text = lbl1.text + "box1 not selected "
if box2.isSelected():
lbl1.text = lbl1.text + "box2 selected"
else:
lbl1.text = lbl1.text + "box2 not selected"
These boxes and a JLabel object are added to a JPanel with a spaceholder of 50 pixels in height added between them.
panel = JPanel()
panel.setLayout(BoxLayout(panel, BoxLayout.Y_AXIS))
panel.add(Box.createVerticalGlue())
panel.add(box1)
panel.add(box2)
panel.add(Box.createRigidArea(Dimension(0,50)))
panel.add(lbl1)
The panel itself is added to a top-level JFrame window, whose visible property is set to true in the end.
frame = JFrame("JCheckBox Example")
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
frame.setLocation(100,100)
frame.setSize(250,150)
frame.add(panel)
frame.setVisible(True)
Run the above code and experiment with the selection of check boxes. The instantaneous state of both check boxes is displayed at the bottom.
The JList control in the swing package provides the user with a scrollable list of items to choose. The JComboBox provides a drop down list of items. In Java, the selection event is processed by implementing the valueChanged() method in the ListSelectionListener. In Jython, an event handler is assigned to the valueChanged property of the JList object.
In the following example, a JList object and a label are added to a JFrame in the BorderLayout. The JList is populated with a collection of items in a tuple. Its valueChanged property is set to listSelect() function.
lang = ("C", "C++", "Java", "Python", "Perl", "C#", "VB", "PHP", "Javascript", "Ruby")
lst = JList(lang, valueChanged = listSelect)
The event handler function obtains the index of the selected item and fetches the corresponding item from the JList object to be displayed on the label at the bottom.
def listSelect(event):
index = lst.selectedIndex
lbl1.text = "Hello" + lang[index]
The JList and JLabel object are added to the JFrame using BorderLayout.
The entire code is given below −
from javax.swing import JFrame, JPanel, JLabel, JList
from java.awt import BorderLayout
frame = JFrame("JList Example")
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
frame.setLocation(100,100)
frame.setSize(300,250)
frame.setLayout(BorderLayout())
def listSelect(event):
index = lst.selectedIndex
lbl1.text = "Hello" + lang[index]
lang = ("C", "C++", "Java", "Python", "Perl", "C#", "VB", "PHP", "Javascript", "Ruby")
lst = JList(lang, valueChanged = listSelect)
lbl1 = JLabel("box1 not selected box2 not selected")
frame.add(lst, BorderLayout.NORTH)
frame.add(lbl1, BorderLayout.SOUTH)
frame.setVisible(True)
The output of the following code is as follows.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2510,
"s": 2081,
"text": "Event handling in Java swing requires that the control (like JButton or JList etc.) should be registered with the respective event listener. The event listener interface or corresponding Adapter class needs to be either implemented or subclassed with its event handling method overridden. In Jython, the event handling is very simple. We can pass any function as property of event handling function corresponding to the control."
},
{
"code": null,
"e": 2565,
"s": 2510,
"text": "Let us first see how a click event is handled in Java."
},
{
"code": null,
"e": 2700,
"s": 2565,
"text": "To begin with, we have to import the java.awt.event package. Next, the class extending JFrame must implement ActionListener interface."
},
{
"code": null,
"e": 2763,
"s": 2700,
"text": "public class btnclick extends JFrame implements ActionListener"
},
{
"code": null,
"e": 2919,
"s": 2763,
"text": "Then, we have to declare the JButton object, add it to the ContentPane of frame and then register it with ActionListener by the addActionListener() method."
},
{
"code": null,
"e": 3019,
"s": 2919,
"text": "JButton b1 = new JButton(\"Click here\");\n getContentPane().add(b1);\n b1.addActionListener(this);"
},
{
"code": null,
"e": 3131,
"s": 3019,
"text": "Now, the actionPerformed() method of the ActionListener interface must be overridden to handle the ActionEvent."
},
{
"code": null,
"e": 3163,
"s": 3131,
"text": "Following is entire Java code −"
},
{
"code": null,
"e": 3700,
"s": 3163,
"text": "import java.awt.event.*;\nimport javax.swing.*;\npublic class btnclick extends JFrame implements ActionListener {\n btnclick() {\n JButton b1 = new JButton(\"Click here\");\n getContentPane().add(b1);\n b1.addActionListener(this);\n }\n \n public void actionPerformed(ActionEvent e) {\n System.out.println(\"Clicked\");\n }\n \n public static void main(String args[]) {\n btnclick b = new btnclick();\n b.setSize(300,200);\n b.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n b.setVisible(true);\n }\n}"
},
{
"code": null,
"e": 3764,
"s": 3700,
"text": "Now, we will write the Jython code equivalent to the same code."
},
{
"code": null,
"e": 3930,
"s": 3764,
"text": "To start with, we do not need to import the ActionEvent or the ActionListener, since Jython’s dynamic typing allows us to avoid mentioning these classes in our code."
},
{
"code": null,
"e": 4130,
"s": 3930,
"text": "Secondly, there is no need to implement or subclass ActionListener. Instead, any user defined function is straightaway provided to the JButton constructor as a value of actionPerformed bean property."
},
{
"code": null,
"e": 4191,
"s": 4130,
"text": "button = JButton('Click here!', actionPerformed = clickhere)"
},
{
"code": null,
"e": 4302,
"s": 4191,
"text": "The clickhere() function is defined as a regular Jython function, which handles the click event on the button."
},
{
"code": null,
"e": 4342,
"s": 4302,
"text": "def change_text(event):\nprint clicked!'"
},
{
"code": null,
"e": 4378,
"s": 4342,
"text": "Here is the Jython equivalent code."
},
{
"code": null,
"e": 4678,
"s": 4378,
"text": "from javax.swing import JFrame, JButton\n\nframe = JFrame(\"Hello\")\nframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)\nframe.setLocation(100,100)\nframe.setSize(300,200)\n\ndef clickhere(event):\n print \"clicked\"\n\nbtn = JButton(\"Add\", actionPerformed = clickhere)\nframe.add(btn)\n\nframe.setVisible(True)"
},
{
"code": null,
"e": 4807,
"s": 4678,
"text": "The Output of Java and Jython code is identical. When the button is clicked, it will print the ‘clicked’ message on the console."
},
{
"code": null,
"e": 4992,
"s": 4807,
"text": "In the following Jython code, two JTextField objects are provided on the JFrame window to enter marks in ‘phy’ and ‘maths’. The JButton object executes the add() function when clicked."
},
{
"code": null,
"e": 5036,
"s": 4992,
"text": "btn = JButton(\"Add\", actionPerformed = add)"
},
{
"code": null,
"e": 5254,
"s": 5036,
"text": "The add() function reads the contents of two text fields by the getText() method and parses them to integers, so that, addition can be performed. The result is then put in the third text field by the setText() method."
},
{
"code": null,
"e": 5360,
"s": 5254,
"text": "def add(event):\n print \"add\"\n ttl = int(txt1.getText())+int(txt2.getText())\n txt3.setText(str(ttl))"
},
{
"code": null,
"e": 5395,
"s": 5360,
"text": "The complete code is given below −"
},
{
"code": null,
"e": 6260,
"s": 5395,
"text": "from javax.swing import JFrame, JLabel, JButton, JTextField\nfrom java.awt import Dimension\n\nframe = JFrame(\"Hello\")\nframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)\nframe.setLocation(100,100)\nframe.setSize(300,200)\nframe.setLayout(None)\n\ndef add(event):\n print \"add\"\n ttl = int(txt1.getText())+int(txt2.getText())\n txt3.setText(str(ttl))\n\nlbl1 = JLabel(\"Phy\")\nlbl1.setBounds(60,20,40,20)\ntxt1 = JTextField(10)\ntxt1.setBounds(120,20,60,20)\nlbl2 = JLabel(\"Maths\")\nlbl2.setBounds(60,50,40,20)\ntxt2 = JTextField(10)\ntxt2.setBounds(120, 50, 60,20)\nbtn = JButton(\"Add\", actionPerformed = add)\nbtn.setBounds(60,80,60,20)\nlbl3 = JLabel(\"Total\")\nlbl3.setBounds(60,110,40,20)\ntxt3 = JTextField(10)\ntxt3.setBounds(120, 110, 60,20)\n\nframe.add(lbl1)\nframe.add(txt1)\nframe.add(lbl2)\nframe.add(txt2)\nframe.add(btn)\nframe.add(lbl3)\nframe.add(txt3)\nframe.setVisible(True)"
},
{
"code": null,
"e": 6451,
"s": 6260,
"text": "When the above code is executed from the command prompt, the following window appears. Enter marks for ‘Phy’, Maths’, and click on the ‘Add’ button. The result will be displayed accordingly."
},
{
"code": null,
"e": 6667,
"s": 6451,
"text": "The JRadioButton class is defined in the javax.swing package. It creates a selectable toggle button with on or off states. If multiple radio buttons are added in a ButtonGroup, their selection is mutually exclusive."
},
{
"code": null,
"e": 7008,
"s": 6667,
"text": "In the following example, two objects of the JRadioButton class and two JLabels are added to a Jpanel container in a vertical BoxLayout. In the constructor of the JRadioButton objects, the OnCheck() function is set as the value of the actionPerformed property. This function is executed when the radio button is clicked to change its state."
},
{
"code": null,
"e": 7124,
"s": 7008,
"text": "rb1 = JRadioButton(\"Male\", True,actionPerformed = OnCheck)\nrb2 = JRadioButton(\"Female\", actionPerformed = OnCheck)\n"
},
{
"code": null,
"e": 7263,
"s": 7124,
"text": "Note that the default state of Radio Button is false (not selected). The button rb1 is created with its starting state as True (selected)."
},
{
"code": null,
"e": 7414,
"s": 7263,
"text": "The two radio buttons are added to a radio ButtonGroup to make them mutually exclusive, so that if one is selected, other is deselected automatically."
},
{
"code": null,
"e": 7460,
"s": 7414,
"text": "grp = ButtonGroup()\ngrp.add(rb1)\ngrp.add(rb2)"
},
{
"code": null,
"e": 7625,
"s": 7460,
"text": "These two radio buttons along with two labels are added to a panel object in the vertical layout with a separator area of 25 pixels in heights between rb2 and lbl2."
},
{
"code": null,
"e": 7840,
"s": 7625,
"text": "panel = JPanel()\npanel.setLayout(BoxLayout(panel, BoxLayout.Y_AXIS))\n\npanel.add(Box.createVerticalGlue())\npanel.add(lbl)\npanel.add(rb1)\npanel.add(rb2)\npanel.add(Box.createRigidArea(Dimension(0,25)))\npanel.add(lbl1)"
},
{
"code": null,
"e": 7942,
"s": 7840,
"text": "This panel is added to a top-level JFrame object, whose visible property is set to ‘True’ in the end."
},
{
"code": null,
"e": 9113,
"s": 7942,
"text": "frame = JFrame(\"JRadioButton Example\")\nframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)\nframe.setLocation(100,100)\nframe.setSize(250,200)\nframe.setVisible(True)\nThe complete code of radio.py is given below:\nfrom javax.swing import JFrame, JPanel, JLabel, BoxLayout, Box\n\nfrom java.awt import Dimension\nfrom javax.swing import JRadioButton,ButtonGroup\nframe = JFrame(\"JRadioButton Example\")\nframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)\nframe.setLocation(100,100)\nframe.setSize(250,200)\npanel = JPanel()\npanel.setLayout(BoxLayout(panel, BoxLayout.Y_AXIS))\nframe.add(panel)\n\ndef OnCheck(event):\n lbl1.text = \"\"\n if rb1.isSelected():\n lbl1.text = lbl1.text+\"Gender selection : Male\"\n else:\n lbl1.text = lbl1.text+\"Gender selection : Female \"\n lbl = JLabel(\"Select Gender\")\n\nrb1 = JRadioButton(\"Male\", True,actionPerformed = OnCheck)\nrb2 = JRadioButton(\"Female\", actionPerformed = OnCheck)\ngrp = ButtonGroup()\ngrp.add(rb1)\ngrp.add(rb2)\n\nlbl1 = JLabel(\"Gender Selection :\")\n\npanel.add(Box.createVerticalGlue())\npanel.add(lbl)\npanel.add(rb1)\npanel.add(rb2)\npanel.add(Box.createRigidArea(Dimension(0,25)))\npanel.add(lbl1)\n\nframe.setVisible(True)"
},
{
"code": null,
"e": 9234,
"s": 9113,
"text": "Run the above Jython script and change the radio button selection. The selection will appear in the label at the bottom."
},
{
"code": null,
"e": 9458,
"s": 9234,
"text": "Like the JRadioButton, JCheckBox object is also a selectable button with a rectangular checkable box besides its caption. This is generally used to provide user opportunity to select multiple options from the list of items."
},
{
"code": null,
"e": 9659,
"s": 9458,
"text": "In the following example, two check boxes and a label from swing package are added to a JPanel in vertical BoxLayout. The label at bottom displays the instantaneous selection state of two check boxes."
},
{
"code": null,
"e": 9776,
"s": 9659,
"text": "Both checkboxes are declared with the constructor having the actionPerformed property set to the OnCheck() function."
},
{
"code": null,
"e": 9884,
"s": 9776,
"text": "box1 = JCheckBox(\"Check1\", actionPerformed = OnCheck)\nbox2 = JCheckBox(\"Check2\", actionPerformed = OnCheck)"
},
{
"code": null,
"e": 10013,
"s": 9884,
"text": "The OnCheck() function verifies selection state of each check box and displays corresponding message on the label at the bottom."
},
{
"code": null,
"e": 10313,
"s": 10013,
"text": "def OnCheck(event):\n lbl1.text = \"\"\n if box1.isSelected():\n lbl1.text = lbl1.text + \"box1 selected \"\n else:\n lbl1.text = lbl1.text + \"box1 not selected \"\n if box2.isSelected():\n lbl1.text = lbl1.text + \"box2 selected\"\n else:\n lbl1.text = lbl1.text + \"box2 not selected\""
},
{
"code": null,
"e": 10429,
"s": 10313,
"text": "These boxes and a JLabel object are added to a JPanel with a spaceholder of 50 pixels in height added between them."
},
{
"code": null,
"e": 10630,
"s": 10429,
"text": "panel = JPanel()\npanel.setLayout(BoxLayout(panel, BoxLayout.Y_AXIS))\npanel.add(Box.createVerticalGlue())\npanel.add(box1)\npanel.add(box2)\npanel.add(Box.createRigidArea(Dimension(0,50)))\npanel.add(lbl1)"
},
{
"code": null,
"e": 10736,
"s": 10630,
"text": "The panel itself is added to a top-level JFrame window, whose visible property is set to true in the end."
},
{
"code": null,
"e": 10916,
"s": 10736,
"text": "frame = JFrame(\"JCheckBox Example\")\nframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)\nframe.setLocation(100,100)\nframe.setSize(250,150)\nframe.add(panel)\n\nframe.setVisible(True)"
},
{
"code": null,
"e": 11057,
"s": 10916,
"text": "Run the above code and experiment with the selection of check boxes. The instantaneous state of both check boxes is displayed at the bottom."
},
{
"code": null,
"e": 11412,
"s": 11057,
"text": "The JList control in the swing package provides the user with a scrollable list of items to choose. The JComboBox provides a drop down list of items. In Java, the selection event is processed by implementing the valueChanged() method in the ListSelectionListener. In Jython, an event handler is assigned to the valueChanged property of the JList object."
},
{
"code": null,
"e": 11629,
"s": 11412,
"text": "In the following example, a JList object and a label are added to a JFrame in the BorderLayout. The JList is populated with a collection of items in a tuple. Its valueChanged property is set to listSelect() function."
},
{
"code": null,
"e": 11761,
"s": 11629,
"text": "lang = (\"C\", \"C++\", \"Java\", \"Python\", \"Perl\", \"C#\", \"VB\", \"PHP\", \"Javascript\", \"Ruby\")\nlst = JList(lang, valueChanged = listSelect)"
},
{
"code": null,
"e": 11928,
"s": 11761,
"text": "The event handler function obtains the index of the selected item and fetches the corresponding item from the JList object to be displayed on the label at the bottom."
},
{
"code": null,
"e": 12017,
"s": 11928,
"text": "def listSelect(event):\n index = lst.selectedIndex\n lbl1.text = \"Hello\" + lang[index]"
},
{
"code": null,
"e": 12089,
"s": 12017,
"text": "The JList and JLabel object are added to the JFrame using BorderLayout."
},
{
"code": null,
"e": 12122,
"s": 12089,
"text": "The entire code is given below −"
},
{
"code": null,
"e": 12750,
"s": 12122,
"text": "from javax.swing import JFrame, JPanel, JLabel, JList\nfrom java.awt import BorderLayout\n\nframe = JFrame(\"JList Example\")\nframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)\nframe.setLocation(100,100)\nframe.setSize(300,250)\n\nframe.setLayout(BorderLayout())\n\ndef listSelect(event):\n index = lst.selectedIndex\n lbl1.text = \"Hello\" + lang[index]\n\nlang = (\"C\", \"C++\", \"Java\", \"Python\", \"Perl\", \"C#\", \"VB\", \"PHP\", \"Javascript\", \"Ruby\")\nlst = JList(lang, valueChanged = listSelect)\nlbl1 = JLabel(\"box1 not selected box2 not selected\")\nframe.add(lst, BorderLayout.NORTH)\nframe.add(lbl1, BorderLayout.SOUTH)\n\nframe.setVisible(True)"
},
{
"code": null,
"e": 12798,
"s": 12750,
"text": "The output of the following code is as follows."
},
{
"code": null,
"e": 12805,
"s": 12798,
"text": " Print"
},
{
"code": null,
"e": 12816,
"s": 12805,
"text": " Add Notes"
}
]
|
3 Cool Features of Python Altair. It is more than a data visualization... | by Soner Yıldırım | Towards Data Science | Data visualization is an integral part of data science. It expedites many tasks such as exploring data, delivering results, storytelling, and so on. Thankfully, there are great data visualization libraries for Python.
Altair is a declarative statistical visualization library for Python. It provides several features to perform data analysis while creating stunning visualizations.
In this article, we will go over 3 features of Altair that have the potential to increase your efficiency.
As with any other software tool and package, the best method for learning is through practicing. Thus, I will try to explain these features with examples. We will be using a customer churn dataset available on Kaggle under creative commons license. Feel free to download it and follow along.
Altair can easily be installed via pip as follows:
pip install altair#if you are using jupyter notebook!pip install altair
Let’s import the libraries and read the dataset into a Pandas data frame.
import pandas as pdimport altair as altchurn = pd.read_csv("Data\\BankChurners.csv")
We will only use some of the columns in the original dataset. We also need to have at most 5000 observations (i.e. rows) to be able to work with Altair. The following code snippet does the necessary filtering operations.
features = [ "Attrition_Flag", "Customer_Age", "Gender", "Marital_Status", "Income_Category", "Total_Trans_Amt", "Credit_Limit", "Months_Inactive_12_mon"]churn = churn[features].sample(n=5000, ignore_index=True)churn.head()
We can start exploring the cool features of Altair now.
Altair allows for aggregating the data while creating a visualization. It saves us some operations which are typically done with a data analysis and manipulation library such as Pandas.
For instance, we can create a bar plot that demonstrates the average credit limit for each income category.
(alt. Chart(churn). mark_bar(). encode(x='Income_Category', y='mean(Credit_Limit):Q'). properties(height=300, width=400))
What we pass to the y parameter in the encode function performs the same operation as the groupby function of Pandas.
churn.groupby(["Income_Category"]).agg( Mean_Credit_Limit = ("Credit_Limit","mean"))
Altair also provides functions to filter data so that we can create more focused or specific plots. There are several predicates that are passed to the transform_filter function. Each predicate applies a different method of filtering.
For instance, the one of predicates allows for filtering rows based on a list of values. The following code creates a bar plot that shows the average credit limit for each marital status given in the list specified by the oneOf parameter.
(alt. Chart(churn). mark_bar(width=50). encode(x='Marital_Status', y='mean(Credit_Limit):Q'). transform_filter( alt.FieldOneOfPredicate( field="Marital_Status", oneOf=["Single","Married","Divorced"])). properties(height=300, width=500))
As you may have noticed, the bars in the second plot are narrower than the ones in the first plot. The width of bars can be adjusted using the width parameter of the mark_bar function.
We can also implement dynamic filtering with Altair. It allows to bind multiple plots together with a shared filter.
We first create a selection object which captures user interactions. As its name suggests, it is used for selecting values on the visualization. The selection object can be connected to a legend or another plot.
In other words, we specify a condition on one plot or on a legend using the selection object. Then, the values are filtered based on this selection.
It will be more clear with an example.
selection = alt.selection_multi( fields=['Attrition_Flag'], bind='legend')alt.Chart(churn).mark_circle(size=50).encode( x='Credit_Limit', y='Total_Trans_Amt', color="Attrition_Flag", opacity=alt.condition(selection, alt.value(1), alt.value(0.1))).properties( height=350, width=500).add_selection( selection)
What this code snippet does is as follows:
It creates a selection object using the attrition flag column. It is bound to the legend.
Then it creates a scatter plot of the credit limit and the total transaction amount columns. The points are colored based on the attrition flag column.
The opacity parameter is used for adjusting the opacity of points based on the selection.
The properties function modifies the size of the plot.
The final step binds the selection object to this visualization.
Here is the result:
Altair is a powerful data visualization library in terms of data transformations and filtering. It facilitates many typical data manipulation tasks. In this article, we have covered 3 cool features that let us integrate data manipulation operations in the visualizations.
Last but not least, if you are not a Medium member yet and plan to become one, I kindly ask you to do so using the following link. I will receive a portion from your membership fee with no additional cost to you.
sonery.medium.com
Thank you for reading. Please let me know if you have any feedback. | [
{
"code": null,
"e": 390,
"s": 172,
"text": "Data visualization is an integral part of data science. It expedites many tasks such as exploring data, delivering results, storytelling, and so on. Thankfully, there are great data visualization libraries for Python."
},
{
"code": null,
"e": 554,
"s": 390,
"text": "Altair is a declarative statistical visualization library for Python. It provides several features to perform data analysis while creating stunning visualizations."
},
{
"code": null,
"e": 661,
"s": 554,
"text": "In this article, we will go over 3 features of Altair that have the potential to increase your efficiency."
},
{
"code": null,
"e": 953,
"s": 661,
"text": "As with any other software tool and package, the best method for learning is through practicing. Thus, I will try to explain these features with examples. We will be using a customer churn dataset available on Kaggle under creative commons license. Feel free to download it and follow along."
},
{
"code": null,
"e": 1004,
"s": 953,
"text": "Altair can easily be installed via pip as follows:"
},
{
"code": null,
"e": 1076,
"s": 1004,
"text": "pip install altair#if you are using jupyter notebook!pip install altair"
},
{
"code": null,
"e": 1150,
"s": 1076,
"text": "Let’s import the libraries and read the dataset into a Pandas data frame."
},
{
"code": null,
"e": 1235,
"s": 1150,
"text": "import pandas as pdimport altair as altchurn = pd.read_csv(\"Data\\\\BankChurners.csv\")"
},
{
"code": null,
"e": 1456,
"s": 1235,
"text": "We will only use some of the columns in the original dataset. We also need to have at most 5000 observations (i.e. rows) to be able to work with Altair. The following code snippet does the necessary filtering operations."
},
{
"code": null,
"e": 1704,
"s": 1456,
"text": "features = [ \"Attrition_Flag\", \"Customer_Age\", \"Gender\", \"Marital_Status\", \"Income_Category\", \"Total_Trans_Amt\", \"Credit_Limit\", \"Months_Inactive_12_mon\"]churn = churn[features].sample(n=5000, ignore_index=True)churn.head()"
},
{
"code": null,
"e": 1760,
"s": 1704,
"text": "We can start exploring the cool features of Altair now."
},
{
"code": null,
"e": 1946,
"s": 1760,
"text": "Altair allows for aggregating the data while creating a visualization. It saves us some operations which are typically done with a data analysis and manipulation library such as Pandas."
},
{
"code": null,
"e": 2054,
"s": 1946,
"text": "For instance, we can create a bar plot that demonstrates the average credit limit for each income category."
},
{
"code": null,
"e": 2180,
"s": 2054,
"text": "(alt. Chart(churn). mark_bar(). encode(x='Income_Category', y='mean(Credit_Limit):Q'). properties(height=300, width=400))"
},
{
"code": null,
"e": 2298,
"s": 2180,
"text": "What we pass to the y parameter in the encode function performs the same operation as the groupby function of Pandas."
},
{
"code": null,
"e": 2385,
"s": 2298,
"text": "churn.groupby([\"Income_Category\"]).agg( Mean_Credit_Limit = (\"Credit_Limit\",\"mean\"))"
},
{
"code": null,
"e": 2620,
"s": 2385,
"text": "Altair also provides functions to filter data so that we can create more focused or specific plots. There are several predicates that are passed to the transform_filter function. Each predicate applies a different method of filtering."
},
{
"code": null,
"e": 2859,
"s": 2620,
"text": "For instance, the one of predicates allows for filtering rows based on a list of values. The following code creates a bar plot that shows the average credit limit for each marital status given in the list specified by the oneOf parameter."
},
{
"code": null,
"e": 3124,
"s": 2859,
"text": "(alt. Chart(churn). mark_bar(width=50). encode(x='Marital_Status', y='mean(Credit_Limit):Q'). transform_filter( alt.FieldOneOfPredicate( field=\"Marital_Status\", oneOf=[\"Single\",\"Married\",\"Divorced\"])). properties(height=300, width=500))"
},
{
"code": null,
"e": 3309,
"s": 3124,
"text": "As you may have noticed, the bars in the second plot are narrower than the ones in the first plot. The width of bars can be adjusted using the width parameter of the mark_bar function."
},
{
"code": null,
"e": 3426,
"s": 3309,
"text": "We can also implement dynamic filtering with Altair. It allows to bind multiple plots together with a shared filter."
},
{
"code": null,
"e": 3638,
"s": 3426,
"text": "We first create a selection object which captures user interactions. As its name suggests, it is used for selecting values on the visualization. The selection object can be connected to a legend or another plot."
},
{
"code": null,
"e": 3787,
"s": 3638,
"text": "In other words, we specify a condition on one plot or on a legend using the selection object. Then, the values are filtered based on this selection."
},
{
"code": null,
"e": 3826,
"s": 3787,
"text": "It will be more clear with an example."
},
{
"code": null,
"e": 4148,
"s": 3826,
"text": "selection = alt.selection_multi( fields=['Attrition_Flag'], bind='legend')alt.Chart(churn).mark_circle(size=50).encode( x='Credit_Limit', y='Total_Trans_Amt', color=\"Attrition_Flag\", opacity=alt.condition(selection, alt.value(1), alt.value(0.1))).properties( height=350, width=500).add_selection( selection)"
},
{
"code": null,
"e": 4191,
"s": 4148,
"text": "What this code snippet does is as follows:"
},
{
"code": null,
"e": 4281,
"s": 4191,
"text": "It creates a selection object using the attrition flag column. It is bound to the legend."
},
{
"code": null,
"e": 4433,
"s": 4281,
"text": "Then it creates a scatter plot of the credit limit and the total transaction amount columns. The points are colored based on the attrition flag column."
},
{
"code": null,
"e": 4523,
"s": 4433,
"text": "The opacity parameter is used for adjusting the opacity of points based on the selection."
},
{
"code": null,
"e": 4578,
"s": 4523,
"text": "The properties function modifies the size of the plot."
},
{
"code": null,
"e": 4643,
"s": 4578,
"text": "The final step binds the selection object to this visualization."
},
{
"code": null,
"e": 4663,
"s": 4643,
"text": "Here is the result:"
},
{
"code": null,
"e": 4935,
"s": 4663,
"text": "Altair is a powerful data visualization library in terms of data transformations and filtering. It facilitates many typical data manipulation tasks. In this article, we have covered 3 cool features that let us integrate data manipulation operations in the visualizations."
},
{
"code": null,
"e": 5148,
"s": 4935,
"text": "Last but not least, if you are not a Medium member yet and plan to become one, I kindly ask you to do so using the following link. I will receive a portion from your membership fee with no additional cost to you."
},
{
"code": null,
"e": 5166,
"s": 5148,
"text": "sonery.medium.com"
}
]
|
Using Extensions with Selenium & Python | We can use extensions with Selenium webdriver in Python. We can have multiple extensions of the Chrome browser while we manually open the browser and work on it.
However, while the Chrome browser is opened through Selenium webdriver, those extensions which are available to the local browser will not be present. To configure an extension, we have to obtain the .crx extension file of the extension.
Then we have to perform installation of the extension to the browser which is launched by Selenium. To get all the extensions available to the browser enter chrome://extensions on the browser address bar.
To get add an extension for example: Momentum, visit the link −
https://chrome.google.com/webstore/category/extensions and enter Momentum in the search box. Once the search results are displayed, click on the relevant option.
After clicking on the Momentum extension, the details of the extension gets displayed. Copy the URL of the extension as highlighted in the below image.
Now, navigate to the link: https://chrome−extension−downloader.com/ and paste the URL we have copied within the Download extension field.
The .crx file of the extension gets downloaded to our system. We should then save it in a desired location.
To add this extension to the Chrome browser, once it is launched by Selenium webdriver, we have to use the Options class. We shall create an object of this class and apply add_extension method on it.
The path of the .crx file of the extension that we want to add is passed as a parameter to that method. Finally, this information is passed to the webdriver object.
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
#object of Options class
op = Options()
#set .crx file path of extension
op.add_extension('C:\\Users\\Momentum_v0.92.2.crx')
#set geckodriver.exe path
driver = webdriver.Firefox(executable_path="C:\\geckodriver.exe",
options=op)
driver.maximize_window()
#launch browser
driver.get("https://www.tutorialspoint.com/index.htm") | [
{
"code": null,
"e": 1224,
"s": 1062,
"text": "We can use extensions with Selenium webdriver in Python. We can have multiple extensions of the Chrome browser while we manually open the browser and work on it."
},
{
"code": null,
"e": 1462,
"s": 1224,
"text": "However, while the Chrome browser is opened through Selenium webdriver, those extensions which are available to the local browser will not be present. To configure an extension, we have to obtain the .crx extension file of the extension."
},
{
"code": null,
"e": 1667,
"s": 1462,
"text": "Then we have to perform installation of the extension to the browser which is launched by Selenium. To get all the extensions available to the browser enter chrome://extensions on the browser address bar."
},
{
"code": null,
"e": 1731,
"s": 1667,
"text": "To get add an extension for example: Momentum, visit the link −"
},
{
"code": null,
"e": 1893,
"s": 1731,
"text": "https://chrome.google.com/webstore/category/extensions and enter Momentum in the search box. Once the search results are displayed, click on the relevant option."
},
{
"code": null,
"e": 2045,
"s": 1893,
"text": "After clicking on the Momentum extension, the details of the extension gets displayed. Copy the URL of the extension as highlighted in the below image."
},
{
"code": null,
"e": 2183,
"s": 2045,
"text": "Now, navigate to the link: https://chrome−extension−downloader.com/ and paste the URL we have copied within the Download extension field."
},
{
"code": null,
"e": 2291,
"s": 2183,
"text": "The .crx file of the extension gets downloaded to our system. We should then save it in a desired location."
},
{
"code": null,
"e": 2491,
"s": 2291,
"text": "To add this extension to the Chrome browser, once it is launched by Selenium webdriver, we have to use the Options class. We shall create an object of this class and apply add_extension method on it."
},
{
"code": null,
"e": 2656,
"s": 2491,
"text": "The path of the .crx file of the extension that we want to add is passed as a parameter to that method. Finally, this information is passed to the webdriver object."
},
{
"code": null,
"e": 3066,
"s": 2656,
"text": "from selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n#object of Options class\nop = Options()\n#set .crx file path of extension\nop.add_extension('C:\\\\Users\\\\Momentum_v0.92.2.crx')\n#set geckodriver.exe path\ndriver = webdriver.Firefox(executable_path=\"C:\\\\geckodriver.exe\",\noptions=op)\ndriver.maximize_window()\n#launch browser\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")"
}
]
|
Sarcasm Classification (Using FastText) | by Sambit Mahapatra | Towards Data Science | FastText is a library created by the Facebook Research Team for efficient learning of word representations and sentence classification. It has gained a lot of attraction in the NLP community especially as a strong baseline for word representation replacing word2vec as it takes the char n-grams into account while getting the word vectors. Here we will be using FastText for text classification.
The data is collected from https://www.kaggle.com/rmisra/news-headlines-dataset-for-sarcasm-detection. Here the sarcastic ones are from TheOnion and nos-sarcastic ones are from HuffPost. Let’s now jump to coding.
First, let’s inspect the data to decide the approach. You can download the data from https://www.kaggle.com/rmisra/news-headlines-dataset-for-sarcasm-detection/data?select=Sarcasm_Headlines_Dataset_v2.json.
#load dataimport pandas as pddf = pd.read_json("Sarcasm_Headlines_Dataset_v2.json", lines=True)#shuffle the data inplacedf = df.sample(frac=1).reset_index(drop=True)# show first few rowsdf.head()
Basically, on reading the json in tabular form with pandas, the dataset contains 3 columns where ‘headline’ contains the headline texts of the news and ‘is_sarcastic’ contains 1 and 0 signifying sarcastic and non-sarcastic respectively. If we see the representation of sarcastic and non-sarcastic examples are
0 149851 13634Name: is_sarcastic, dtype: int64
Now to just look at how the texts are looking for sarcastic and non-sarcastic examples:
#word cloud on sarcastic headlinessarcastic = ‘ ‘.join(df[df[‘is_sarcastic’]==1][‘headline’].to_list())plot_wordcloud(sarcastic, ‘Reds’)
#word cloud on sarcastic headlines sarcastic = ' '.join(df[df['is_sarcastic']==0]['headline'].to_list()) plot_wordcloud(sarcastic, 'Reds')
Now before going to building the classifier model, we need to do some cleaning of the text to remove noise. Since these are the news headlines, they don’t contain much crap. The cleanings what I thought of having are getting all string lowercase, getting rid of anything which is not alphanumeric and replacing the numeric with a specific label.
df['headline'] = df['headline'].str.lower()df['headline'] = df['headline'].apply(alpha_num)df['headline'] = df['headline'].apply(replace_num)
Now, we are ready with the cleaned text and their corresponding labels to build a binary sarcasm classifier. As discussed, we will build the model using FastText python module.
First, need to install the FastText python module in the environment.
#Building fasttext for python\ !git clone https://github.com/facebookresearch/fastText.git !cd fastText!pip3 install .
We need to make the training and testing file ready in the format which FastText api can understand. The default format of text file on which we want to train our model should be __ label __ <Label> <Text>. We can use other prefix instead of __label__ by changing the parameter accordingly in the training time, which we will see ahead.
#data preparation for fasttextwith open('fasttext_input_sarcastic_comments.txt', 'w') as f: for each_text, each_label in zip(df['headline'], df['is_sarcastic']): f.writelines(f'__label__{each_label} {each_text}\n')
The data in the file looks like this:
!head -n 10 fasttext_input_sarcastic_comments.txt__label__1 school friends dont find camp songs funny__label__0 what cutting americorps would mean for public lands__label__0 when our tears become medicine__label__1 craig kilborn weds self in private ceremony__label__1 white couple admires fall colors__label__1 mom much more insistent about getting grandkids from one child than other__label__0 diary of a queer kids mom__label__1 sephora makeup artist helping woman create the perfect pink eye__label__1 kelloggs pulls controversial chocobastard from store shelves__label__0 winston churchills grandson introduces a new nickname for donald trump
Here __label__0 implies non-sarcastic and __label__1 implies sarcastic. Now we are in good shape to start training the classifier model. For that will divide the dataset into training(90%) and testing(10%) dataset. The FastText function to be used for this supervised binary classification is train_supervised.
''For classification train_supervised call will be used:The default parameters to it: input # training file path (required) lr # learning rate [0.1] dim # size of word vectors [100] ws # size of the context window [5] epoch # number of epochs [5] minCount # minimal number of word occurences [1] minCountLabel # minimal number of label occurences [1] minn # min length of char ngram [0] maxn # max length of char ngram [0] neg # number of negatives sampled [5] wordNgrams # max length of word ngram [1] loss # loss function {ns, hs, softmax, ova} [softmax] bucket # number of buckets [2000000] thread # number of threads [number of cpus] lrUpdateRate # change the rate of updates for the learning rate [100] t # sampling threshold [0.0001] label # label prefix ['__label__'] verbose # verbose [2] pretrainedVectors # pretrained word vectors (.vec file) for supervised learning []'''model = fasttext.train_supervised('sarcasm_train.bin', wordNgrams=2)
To measure the performance in the testing dataset:
#measuring performance on test datadef print_results(sample_size, precision, recall): precision = round(precision, 2) recall = round(recall, 2) print(f'{sample_size=}') print(f'{precision=}') print(f'{recall=}')print_results(*model.test('sarcasm_test.bin'))sample_size=2862 precision=0.87 recall=0.87
The results, though not perfect, look promising. We save the model object now for future inferences.
#save the modelmodel.save_model('fasttext_sarcasm.model')
FastText is also capable of compressing the model in order to have a much smaller size model file by sacrificing only a little bit of performance through quantisation.
# with the previously trained `model` object, callmodel.quantize(input='sarcasm_train.bin', retrain=True)\# results on test setprint_results(*model.test('sarcasm_test.bin'))sample_size=2862 precision=0.86 recall=0.86
If you see the precision and recall seem to suffer .01 score but, looking at the model file size:
!du -kh ./fasttext_sarcasm*98M ./fasttext_sarcasm.ftz774M ./fasttext_sarcasm.model
The compressed model is only 1/12th of the base model. So this is a trade-off between model size and performance which users have to decide depending on the use case. Since the classifier model is trained and ready, now is the time to have the inference script ready so you can plan the deployment.
def predict_is_sarcastic(text): return SarcasmService.get_model().predict(text, k=2)if __name__ == '__main__': ip = 'Make Indian manufacturing competitive to curb Chinese imports: RC Bhargava' print(f'Result : {predict_is_sarcastic(ip)}')Result : (('__label__0', '__label__1'), array([0.5498156 , 0.45020437]))
As can be seen above the result label with maximum probability is __label__0 which means the used headline is non-sarcastic as per the trained model. In model.predict() call the value of k signifies the number of classes you want in output along with their respective probability score. Since we have used softmax activation (default one in FastText), the sum of the probability of the two labels is 1.
To conclude, FastText can be a strong baseline while doing any NLP classification and its implementation is very easy. All the source code of this article can be found at my git repo. The FastText python module is not officially supported but that shouldn’t be an issue for tech people to experiment :). In future post will try to discuss how can the trained model be moved to production. | [
{
"code": null,
"e": 568,
"s": 172,
"text": "FastText is a library created by the Facebook Research Team for efficient learning of word representations and sentence classification. It has gained a lot of attraction in the NLP community especially as a strong baseline for word representation replacing word2vec as it takes the char n-grams into account while getting the word vectors. Here we will be using FastText for text classification."
},
{
"code": null,
"e": 781,
"s": 568,
"text": "The data is collected from https://www.kaggle.com/rmisra/news-headlines-dataset-for-sarcasm-detection. Here the sarcastic ones are from TheOnion and nos-sarcastic ones are from HuffPost. Let’s now jump to coding."
},
{
"code": null,
"e": 988,
"s": 781,
"text": "First, let’s inspect the data to decide the approach. You can download the data from https://www.kaggle.com/rmisra/news-headlines-dataset-for-sarcasm-detection/data?select=Sarcasm_Headlines_Dataset_v2.json."
},
{
"code": null,
"e": 1184,
"s": 988,
"text": "#load dataimport pandas as pddf = pd.read_json(\"Sarcasm_Headlines_Dataset_v2.json\", lines=True)#shuffle the data inplacedf = df.sample(frac=1).reset_index(drop=True)# show first few rowsdf.head()"
},
{
"code": null,
"e": 1494,
"s": 1184,
"text": "Basically, on reading the json in tabular form with pandas, the dataset contains 3 columns where ‘headline’ contains the headline texts of the news and ‘is_sarcastic’ contains 1 and 0 signifying sarcastic and non-sarcastic respectively. If we see the representation of sarcastic and non-sarcastic examples are"
},
{
"code": null,
"e": 1541,
"s": 1494,
"text": "0 149851 13634Name: is_sarcastic, dtype: int64"
},
{
"code": null,
"e": 1629,
"s": 1541,
"text": "Now to just look at how the texts are looking for sarcastic and non-sarcastic examples:"
},
{
"code": null,
"e": 1766,
"s": 1629,
"text": "#word cloud on sarcastic headlinessarcastic = ‘ ‘.join(df[df[‘is_sarcastic’]==1][‘headline’].to_list())plot_wordcloud(sarcastic, ‘Reds’)"
},
{
"code": null,
"e": 1905,
"s": 1766,
"text": "#word cloud on sarcastic headlines sarcastic = ' '.join(df[df['is_sarcastic']==0]['headline'].to_list()) plot_wordcloud(sarcastic, 'Reds')"
},
{
"code": null,
"e": 2251,
"s": 1905,
"text": "Now before going to building the classifier model, we need to do some cleaning of the text to remove noise. Since these are the news headlines, they don’t contain much crap. The cleanings what I thought of having are getting all string lowercase, getting rid of anything which is not alphanumeric and replacing the numeric with a specific label."
},
{
"code": null,
"e": 2393,
"s": 2251,
"text": "df['headline'] = df['headline'].str.lower()df['headline'] = df['headline'].apply(alpha_num)df['headline'] = df['headline'].apply(replace_num)"
},
{
"code": null,
"e": 2570,
"s": 2393,
"text": "Now, we are ready with the cleaned text and their corresponding labels to build a binary sarcasm classifier. As discussed, we will build the model using FastText python module."
},
{
"code": null,
"e": 2640,
"s": 2570,
"text": "First, need to install the FastText python module in the environment."
},
{
"code": null,
"e": 2759,
"s": 2640,
"text": "#Building fasttext for python\\ !git clone https://github.com/facebookresearch/fastText.git !cd fastText!pip3 install ."
},
{
"code": null,
"e": 3096,
"s": 2759,
"text": "We need to make the training and testing file ready in the format which FastText api can understand. The default format of text file on which we want to train our model should be __ label __ <Label> <Text>. We can use other prefix instead of __label__ by changing the parameter accordingly in the training time, which we will see ahead."
},
{
"code": null,
"e": 3321,
"s": 3096,
"text": "#data preparation for fasttextwith open('fasttext_input_sarcastic_comments.txt', 'w') as f: for each_text, each_label in zip(df['headline'], df['is_sarcastic']): f.writelines(f'__label__{each_label} {each_text}\\n')"
},
{
"code": null,
"e": 3359,
"s": 3321,
"text": "The data in the file looks like this:"
},
{
"code": null,
"e": 4007,
"s": 3359,
"text": "!head -n 10 fasttext_input_sarcastic_comments.txt__label__1 school friends dont find camp songs funny__label__0 what cutting americorps would mean for public lands__label__0 when our tears become medicine__label__1 craig kilborn weds self in private ceremony__label__1 white couple admires fall colors__label__1 mom much more insistent about getting grandkids from one child than other__label__0 diary of a queer kids mom__label__1 sephora makeup artist helping woman create the perfect pink eye__label__1 kelloggs pulls controversial chocobastard from store shelves__label__0 winston churchills grandson introduces a new nickname for donald trump"
},
{
"code": null,
"e": 4318,
"s": 4007,
"text": "Here __label__0 implies non-sarcastic and __label__1 implies sarcastic. Now we are in good shape to start training the classifier model. For that will divide the dataset into training(90%) and testing(10%) dataset. The FastText function to be used for this supervised binary classification is train_supervised."
},
{
"code": null,
"e": 5532,
"s": 4318,
"text": "''For classification train_supervised call will be used:The default parameters to it: input # training file path (required) lr # learning rate [0.1] dim # size of word vectors [100] ws # size of the context window [5] epoch # number of epochs [5] minCount # minimal number of word occurences [1] minCountLabel # minimal number of label occurences [1] minn # min length of char ngram [0] maxn # max length of char ngram [0] neg # number of negatives sampled [5] wordNgrams # max length of word ngram [1] loss # loss function {ns, hs, softmax, ova} [softmax] bucket # number of buckets [2000000] thread # number of threads [number of cpus] lrUpdateRate # change the rate of updates for the learning rate [100] t # sampling threshold [0.0001] label # label prefix ['__label__'] verbose # verbose [2] pretrainedVectors # pretrained word vectors (.vec file) for supervised learning []'''model = fasttext.train_supervised('sarcasm_train.bin', wordNgrams=2)"
},
{
"code": null,
"e": 5583,
"s": 5532,
"text": "To measure the performance in the testing dataset:"
},
{
"code": null,
"e": 5906,
"s": 5583,
"text": "#measuring performance on test datadef print_results(sample_size, precision, recall): precision = round(precision, 2) recall = round(recall, 2) print(f'{sample_size=}') print(f'{precision=}') print(f'{recall=}')print_results(*model.test('sarcasm_test.bin'))sample_size=2862 precision=0.87 recall=0.87"
},
{
"code": null,
"e": 6007,
"s": 5906,
"text": "The results, though not perfect, look promising. We save the model object now for future inferences."
},
{
"code": null,
"e": 6065,
"s": 6007,
"text": "#save the modelmodel.save_model('fasttext_sarcasm.model')"
},
{
"code": null,
"e": 6233,
"s": 6065,
"text": "FastText is also capable of compressing the model in order to have a much smaller size model file by sacrificing only a little bit of performance through quantisation."
},
{
"code": null,
"e": 6450,
"s": 6233,
"text": "# with the previously trained `model` object, callmodel.quantize(input='sarcasm_train.bin', retrain=True)\\# results on test setprint_results(*model.test('sarcasm_test.bin'))sample_size=2862 precision=0.86 recall=0.86"
},
{
"code": null,
"e": 6548,
"s": 6450,
"text": "If you see the precision and recall seem to suffer .01 score but, looking at the model file size:"
},
{
"code": null,
"e": 6631,
"s": 6548,
"text": "!du -kh ./fasttext_sarcasm*98M ./fasttext_sarcasm.ftz774M ./fasttext_sarcasm.model"
},
{
"code": null,
"e": 6930,
"s": 6631,
"text": "The compressed model is only 1/12th of the base model. So this is a trade-off between model size and performance which users have to decide depending on the use case. Since the classifier model is trained and ready, now is the time to have the inference script ready so you can plan the deployment."
},
{
"code": null,
"e": 7250,
"s": 6930,
"text": "def predict_is_sarcastic(text): return SarcasmService.get_model().predict(text, k=2)if __name__ == '__main__': ip = 'Make Indian manufacturing competitive to curb Chinese imports: RC Bhargava' print(f'Result : {predict_is_sarcastic(ip)}')Result : (('__label__0', '__label__1'), array([0.5498156 , 0.45020437]))"
},
{
"code": null,
"e": 7653,
"s": 7250,
"text": "As can be seen above the result label with maximum probability is __label__0 which means the used headline is non-sarcastic as per the trained model. In model.predict() call the value of k signifies the number of classes you want in output along with their respective probability score. Since we have used softmax activation (default one in FastText), the sum of the probability of the two labels is 1."
}
]
|
ANOVA With Python And SQL. Understanding why and how to do... | by Nurullah Sirca | Towards Data Science | The analysis of variance (ANOVA) is utilized for analyzing the variance which involves assessing the difference between the two variables. It is an effective statistical tool for analyzing financial or customer data which is helpful for monitoring the planning process and managing the projects successfully. One-way ANOVA should be used when you have collected data about one categorical independent variable and one quantitative dependent variable. The independent variable should have at least three levels. Here, we will fetch a clinical trial dataset from SQL with pyodbc, run ANOVA on Python and interpret the results.
A little backstory before we dive in! Before ANOVA, people were using multiple t-tests to compare if there is a difference between variables. As the world progressed, the data become vaster and the number of groups increased. Doing multiple t-tests were not going to be feasible, therefore ANOVA was born. Note that, use a t-test instead If you only want to compare two groups
Check sample sizes, we need an equal number of observations in each group.
Calculate Mean Square for each group.
Calculate Mean Square error.
Calculate F-value by dividing the difference between groups to the difference within groups.
Using the F-distribution Table for deciding on the Null Hypothesis.
The Shapiro-Wilk test can be used to check the normal distribution of residuals. Null hypothesis being the data is drawn from the normal distribution.Bartlett’s test to check the homogeneity of variances. Null hypothesis being the samples from populations having equal variances. Data isn’t drawn from a normal distribution? Try the Levene test instead.
The Shapiro-Wilk test can be used to check the normal distribution of residuals. Null hypothesis being the data is drawn from the normal distribution.
Bartlett’s test to check the homogeneity of variances. Null hypothesis being the samples from populations having equal variances. Data isn’t drawn from a normal distribution? Try the Levene test instead.
The data we will use is a clinical trials data. It shows the memory performance of patients under three different drugs. To get the data from the SQL server, we will use the Python package pyodbc.
After entering the required credentials, we get the data we need by executing:
cursor.execute("SELECT Drug,(Mem_Score_After - Mem_Score_Before) as Diff FROM trials WHERE Drug IN ('A','S','T')")
After fetching the data, we can transfer it to pandas for further analysis. If we describe and visualize the target variable values by drugs we get:
Note: As they are seen in both boxplot and description of drugs, the memory performance of patients under Drug A is the best clearly.
First of all, the hypotheses need to be defined.
Null Hypothesis:Mean memory performances for different drugs is the same.
Alternate Hypothesis:Mean memory performances for different drugs isn’t same(It might be the case that mean for two drugs are the same, but not all)
Let’s now run a one way ANOVA test to see if the groups are indeed different or not. The python package stats is used for this part of the analysis.
stats.f_oneway(df[‘Diff’][df[‘Drug’] == ‘A’], df[‘Diff’][df[‘Drug’] == ‘S’], df[‘Diff’][df[‘Drug’] == ‘T’])
The P-value obtained from ANOVA analysis is significant (P<0.05),
and therefore, we conclude that there are significant differences among treatments. The results show an F statistic of 22. If F value is bigger than F-critical, which is in our case, we reject the null hypothesis. If F value is smaller than F-critical, we accept the null hypothesis.
Does this make sense? Let’s visualize again.
We can see that for two groups, the difference between them is lower than the difference within them. For the third group, shown in blue, the distribution seems quite different than the other two. Therefore our eyes also tell us that the drug treatment shown in blue is different than the other two.
We have done a basic one way ANOVA to see if any of the drugs improved memory performance. After getting a significant result and an F statistic bigger than the critical value of F, we have concluded that the drugs do not have the same effect. We have seen from the histogram that one of the drugs had much higher performance than the other two. This is a simple dataset, if it was more complex we would use the Tukey HSD test to see which groups are different.
One way ANOVA is a great way to see if there is a difference between groups, let it be groups of customers, trials or financial operations related experiments. I am sure you can find a way to apply them to your work if they haven’t been already.
I welcome feedback, please let me know if you have questions. You can reach me out on LinkedIn. | [
{
"code": null,
"e": 796,
"s": 171,
"text": "The analysis of variance (ANOVA) is utilized for analyzing the variance which involves assessing the difference between the two variables. It is an effective statistical tool for analyzing financial or customer data which is helpful for monitoring the planning process and managing the projects successfully. One-way ANOVA should be used when you have collected data about one categorical independent variable and one quantitative dependent variable. The independent variable should have at least three levels. Here, we will fetch a clinical trial dataset from SQL with pyodbc, run ANOVA on Python and interpret the results."
},
{
"code": null,
"e": 1173,
"s": 796,
"text": "A little backstory before we dive in! Before ANOVA, people were using multiple t-tests to compare if there is a difference between variables. As the world progressed, the data become vaster and the number of groups increased. Doing multiple t-tests were not going to be feasible, therefore ANOVA was born. Note that, use a t-test instead If you only want to compare two groups"
},
{
"code": null,
"e": 1248,
"s": 1173,
"text": "Check sample sizes, we need an equal number of observations in each group."
},
{
"code": null,
"e": 1286,
"s": 1248,
"text": "Calculate Mean Square for each group."
},
{
"code": null,
"e": 1315,
"s": 1286,
"text": "Calculate Mean Square error."
},
{
"code": null,
"e": 1408,
"s": 1315,
"text": "Calculate F-value by dividing the difference between groups to the difference within groups."
},
{
"code": null,
"e": 1476,
"s": 1408,
"text": "Using the F-distribution Table for deciding on the Null Hypothesis."
},
{
"code": null,
"e": 1830,
"s": 1476,
"text": "The Shapiro-Wilk test can be used to check the normal distribution of residuals. Null hypothesis being the data is drawn from the normal distribution.Bartlett’s test to check the homogeneity of variances. Null hypothesis being the samples from populations having equal variances. Data isn’t drawn from a normal distribution? Try the Levene test instead."
},
{
"code": null,
"e": 1981,
"s": 1830,
"text": "The Shapiro-Wilk test can be used to check the normal distribution of residuals. Null hypothesis being the data is drawn from the normal distribution."
},
{
"code": null,
"e": 2185,
"s": 1981,
"text": "Bartlett’s test to check the homogeneity of variances. Null hypothesis being the samples from populations having equal variances. Data isn’t drawn from a normal distribution? Try the Levene test instead."
},
{
"code": null,
"e": 2382,
"s": 2185,
"text": "The data we will use is a clinical trials data. It shows the memory performance of patients under three different drugs. To get the data from the SQL server, we will use the Python package pyodbc."
},
{
"code": null,
"e": 2461,
"s": 2382,
"text": "After entering the required credentials, we get the data we need by executing:"
},
{
"code": null,
"e": 2576,
"s": 2461,
"text": "cursor.execute(\"SELECT Drug,(Mem_Score_After - Mem_Score_Before) as Diff FROM trials WHERE Drug IN ('A','S','T')\")"
},
{
"code": null,
"e": 2725,
"s": 2576,
"text": "After fetching the data, we can transfer it to pandas for further analysis. If we describe and visualize the target variable values by drugs we get:"
},
{
"code": null,
"e": 2859,
"s": 2725,
"text": "Note: As they are seen in both boxplot and description of drugs, the memory performance of patients under Drug A is the best clearly."
},
{
"code": null,
"e": 2908,
"s": 2859,
"text": "First of all, the hypotheses need to be defined."
},
{
"code": null,
"e": 2982,
"s": 2908,
"text": "Null Hypothesis:Mean memory performances for different drugs is the same."
},
{
"code": null,
"e": 3131,
"s": 2982,
"text": "Alternate Hypothesis:Mean memory performances for different drugs isn’t same(It might be the case that mean for two drugs are the same, but not all)"
},
{
"code": null,
"e": 3280,
"s": 3131,
"text": "Let’s now run a one way ANOVA test to see if the groups are indeed different or not. The python package stats is used for this part of the analysis."
},
{
"code": null,
"e": 3389,
"s": 3280,
"text": "stats.f_oneway(df[‘Diff’][df[‘Drug’] == ‘A’], df[‘Diff’][df[‘Drug’] == ‘S’], df[‘Diff’][df[‘Drug’] == ‘T’])"
},
{
"code": null,
"e": 3455,
"s": 3389,
"text": "The P-value obtained from ANOVA analysis is significant (P<0.05),"
},
{
"code": null,
"e": 3739,
"s": 3455,
"text": "and therefore, we conclude that there are significant differences among treatments. The results show an F statistic of 22. If F value is bigger than F-critical, which is in our case, we reject the null hypothesis. If F value is smaller than F-critical, we accept the null hypothesis."
},
{
"code": null,
"e": 3784,
"s": 3739,
"text": "Does this make sense? Let’s visualize again."
},
{
"code": null,
"e": 4084,
"s": 3784,
"text": "We can see that for two groups, the difference between them is lower than the difference within them. For the third group, shown in blue, the distribution seems quite different than the other two. Therefore our eyes also tell us that the drug treatment shown in blue is different than the other two."
},
{
"code": null,
"e": 4546,
"s": 4084,
"text": "We have done a basic one way ANOVA to see if any of the drugs improved memory performance. After getting a significant result and an F statistic bigger than the critical value of F, we have concluded that the drugs do not have the same effect. We have seen from the histogram that one of the drugs had much higher performance than the other two. This is a simple dataset, if it was more complex we would use the Tukey HSD test to see which groups are different."
},
{
"code": null,
"e": 4792,
"s": 4546,
"text": "One way ANOVA is a great way to see if there is a difference between groups, let it be groups of customers, trials or financial operations related experiments. I am sure you can find a way to apply them to your work if they haven’t been already."
}
]
|
Python Increment and Decrement Operators | In this article, we will learn about increment and decrement operators in Python 3.x. Or earlier. In other languages we have pre and post increment and decrement (++ --) operators.
In Python we don’t have any such operators . But we can implement these operators in the form as dicussed in example below.
x=786
x=x+1
print(x)
x+=1
print(x)
x=x-1
print(x)
x-=1
print(x)
787
788
787
786
Other languages have for loops which uses increment and decrement operators. Python offers for loop which has a range function having default increment value “1” set. We can also specify our increment count as a third argument in the range function
for i in range(0,5):
print(i)
for i in range(0,5,2):
print(i)
0
1
2
3
4
0
2
4
In this article, we learned how to use Increment and Decrement Operators in Python. | [
{
"code": null,
"e": 1243,
"s": 1062,
"text": "In this article, we will learn about increment and decrement operators in Python 3.x. Or earlier. In other languages we have pre and post increment and decrement (++ --) operators."
},
{
"code": null,
"e": 1367,
"s": 1243,
"text": "In Python we don’t have any such operators . But we can implement these operators in the form as dicussed in example below."
},
{
"code": null,
"e": 1435,
"s": 1367,
"text": "x=786\n\nx=x+1\nprint(x)\n\nx+=1\nprint(x)\n\nx=x-1\nprint(x)\n\nx-=1\nprint(x)"
},
{
"code": null,
"e": 1451,
"s": 1435,
"text": "787\n788\n787\n786"
},
{
"code": null,
"e": 1700,
"s": 1451,
"text": "Other languages have for loops which uses increment and decrement operators. Python offers for loop which has a range function having default increment value “1” set. We can also specify our increment count as a third argument in the range function"
},
{
"code": null,
"e": 1769,
"s": 1700,
"text": "for i in range(0,5):\n print(i)\n\nfor i in range(0,5,2):\n print(i)"
},
{
"code": null,
"e": 1785,
"s": 1769,
"text": "0\n1\n2\n3\n4\n0\n2\n4"
},
{
"code": null,
"e": 1869,
"s": 1785,
"text": "In this article, we learned how to use Increment and Decrement Operators in Python."
}
]
|
How to build KNN from scratch in Python | by Doug Steen | Towards Data Science | k-Nearest Neighbors (KNN) is a supervised machine learning algorithm that can be used for either regression or classification tasks. KNN is non-parametric, which means that the algorithm does not make assumptions about the underlying distributions of the data. This is in contrast to a technique like linear regression, which is parametric, and requires us to find a function that describes the relationship between dependent and independent variables.
KNN has the advantage of being quite intuitive to understand. When used for classification, a query point (or test point) is classified based on the k labeled training points that are closest to that query point.
For a simplified example, see the figure below. The left panel shows a 2-d plot of sixteen data points — eight are labeled as green, and eight are labeled as purple. Now, the right panel shows how we would classify a new point (the black cross), using KNN when k=3. We find the three closest points, and count up how many ‘votes’ each color has within those three points. In this case, two of the three points are purple — so, the black cross will be labeled as purple.
Calculating Distance
The distance between points is determined by using one of several versions of the Minkowski distance equation. The generalized formula for Minkowski distance can be represented as follows:
where X and Y are data points, n is the number of dimensions, and p is the Minkowski power parameter. When p =1, the distance is known at the Manhattan (or Taxicab) distance, and when p=2 the distance is known as the Euclidean distance. In two dimensions, the Manhattan and Euclidean distances between two points are easy to visualize (see the graph below), however at higher orders of p, the Minkowski distance becomes more abstract.
To implement my own version of the KNN classifier in Python, I’ll first want to import a few common libraries to help out.
To test the KNN classifier, I’m going to use the iris data set from sklearn.datasets. The data set has measurements (Sepal Length, Sepal Width, Petal Length, Petal Width) for 150 iris plants, split evenly among three species (0 = setosa, 1 = versicolor, and 2 = virginica). Below, I load the data and store it in a dataframe.
I’ll also separate the data into features (X) and the target variable (y), which is the species label for each plant.
Creating a functioning KNN classifier can be broken down into several steps. While KNN includes a bit more nuance than this, here’s my bare-bones to-do list:
Define a function to calculate the distance between two pointsUse the distance function to get the distance between a test point and all known data pointsSort distance measurements to find the points closest to the test point (i.e., find the nearest neighbors)Use majority class labels of those closest points to predict the label of the test pointRepeat steps 1 through 4 until all test data points are classified
Define a function to calculate the distance between two points
Use the distance function to get the distance between a test point and all known data points
Sort distance measurements to find the points closest to the test point (i.e., find the nearest neighbors)
Use majority class labels of those closest points to predict the label of the test point
Repeat steps 1 through 4 until all test data points are classified
First, I define a function called minkowski_distance, that takes an input of two data points (a & b) and a Minkowski power parameter p, and returns the distance between the two points. Note that this function calculates distance exactly like the Minkowski formula I mentioned earlier. By making p an adjustable parameter, I can decide whether I want to calculate Manhattan distance (p=1), Euclidean distance (p=2), or some higher order of the Minkowski distance.
0.6999999999999993
For step 2, I simply repeat the minkowski_distance calculation for all labeled points in X and store them in a dataframe.
In step 3, I use the pandas .sort_values() method to sort by distance, and return only the top 5 results.
For this step, I use collections.Counter to keep track of the labels that coincide with the nearest neighbor points. I then use the .most_common() method to return the most commonly occurring label. Note: if there is a tie between two or more labels for the title of “most common” label, the one that was first encountered by the Counter() object will be the one that gets returned.
1
In this step, I put the code I’ve already written to work and write a function to classify the data using KNN. First, I perform a train_test_split on the data (75% train, 25% test), and then scale the data using StandardScaler(). Since KNN is distance-based, it is important to make sure that the features are scaled properly before feeding them into the algorithm.
Additionally, to avoid data leakage, it is good practice to scale the features after the train_test_split has been performed. First, scale the data from the training set only (scaler.fit_transform(X_train)), and then use that information to scale the test set (scaler.tranform(X_test)). This way, I can ensure that no information outside of the training data is used to create the model.
Next, I define a function called knn_predict that takes in all of the training and test data, k, and p, and returns the predictions my KNN classifier makes for the test set (y_hat_test). This function doesn’t really include anything new — it is simply applying what I’ve already worked through above. The function should return a list of label predictions containing only 0’s, 1’s and 2’s.
[0, 1, 1, 0, 2, 1, 2, 0, 0, 2, 1, 0, 2, 1, 1, 0, 1, 1, 0, 0, 1, 1, 2, 0, 2, 1, 0, 0, 1, 2, 1, 2, 1, 2, 2, 0, 1, 0]
And there they are! These are the predictions that this home-brewed KNN classifier has made on the test set. Let’s see how well it worked:
0.9736842105263158
Looks like the classifier achieved 97% accuracy on the test set. Not too bad at all! But how do I know if it actually worked correctly? Let’s check the result of sklearn’s KNeighborsClassifier on the same data:
Sklearn KNN Accuracy: 0.9736842105263158
Nice! sklearn’s implementation of the KNN classifier gives us the exact same accuracy score.
My KNN classifier performed quite well with the selected value of k = 5. KNN doesn’t have as many tune-able parameters as other algorithms like Decision Trees or Random Forests, but k happens to be one of them. Let’s see how the classification accuracy changes when I vary k:
In this case, using nearly any k value less than 20 results in great (>95%) classification accuracy on the test set. However, when k becomes greater than about 60, accuracy really starts to drop off. This makes sense, because the data set only has 150 observations — when k is that high, the classifier is probably considering labeled training data points that are way too far from the test points.
In writing my own KNN classifier, I chose to overlook one clear hyperparameter tuning opportunity: the weight that each of the k nearest points has in classifying a point. In sklearn’s KNeighborsClassifier, this is the weights parameter, and it can be set to ‘uniform’, ‘distance’, or another user-defined function.
When set to ‘uniform’, each of the k nearest neighbors gets an equal vote in labeling a new point. When set to ‘distance’, the neighbors in closest to the new point are weighted more heavily than the neighbors farther away. There are certainly cases where weighting by ‘distance’ would produce better results, and the only way to find out is through hyperparameter tuning.
Now, make no mistake — sklearn’s implementation is undoubtedly more efficient and more user-friendly than what I’ve cobbled together here. However, I found it a valuable exercise to work through KNN from ‘scratch’, and it has only solidified my understanding of the algorithm. I hope it did the same for you! | [
{
"code": null,
"e": 624,
"s": 171,
"text": "k-Nearest Neighbors (KNN) is a supervised machine learning algorithm that can be used for either regression or classification tasks. KNN is non-parametric, which means that the algorithm does not make assumptions about the underlying distributions of the data. This is in contrast to a technique like linear regression, which is parametric, and requires us to find a function that describes the relationship between dependent and independent variables."
},
{
"code": null,
"e": 837,
"s": 624,
"text": "KNN has the advantage of being quite intuitive to understand. When used for classification, a query point (or test point) is classified based on the k labeled training points that are closest to that query point."
},
{
"code": null,
"e": 1307,
"s": 837,
"text": "For a simplified example, see the figure below. The left panel shows a 2-d plot of sixteen data points — eight are labeled as green, and eight are labeled as purple. Now, the right panel shows how we would classify a new point (the black cross), using KNN when k=3. We find the three closest points, and count up how many ‘votes’ each color has within those three points. In this case, two of the three points are purple — so, the black cross will be labeled as purple."
},
{
"code": null,
"e": 1328,
"s": 1307,
"text": "Calculating Distance"
},
{
"code": null,
"e": 1517,
"s": 1328,
"text": "The distance between points is determined by using one of several versions of the Minkowski distance equation. The generalized formula for Minkowski distance can be represented as follows:"
},
{
"code": null,
"e": 1952,
"s": 1517,
"text": "where X and Y are data points, n is the number of dimensions, and p is the Minkowski power parameter. When p =1, the distance is known at the Manhattan (or Taxicab) distance, and when p=2 the distance is known as the Euclidean distance. In two dimensions, the Manhattan and Euclidean distances between two points are easy to visualize (see the graph below), however at higher orders of p, the Minkowski distance becomes more abstract."
},
{
"code": null,
"e": 2075,
"s": 1952,
"text": "To implement my own version of the KNN classifier in Python, I’ll first want to import a few common libraries to help out."
},
{
"code": null,
"e": 2401,
"s": 2075,
"text": "To test the KNN classifier, I’m going to use the iris data set from sklearn.datasets. The data set has measurements (Sepal Length, Sepal Width, Petal Length, Petal Width) for 150 iris plants, split evenly among three species (0 = setosa, 1 = versicolor, and 2 = virginica). Below, I load the data and store it in a dataframe."
},
{
"code": null,
"e": 2519,
"s": 2401,
"text": "I’ll also separate the data into features (X) and the target variable (y), which is the species label for each plant."
},
{
"code": null,
"e": 2677,
"s": 2519,
"text": "Creating a functioning KNN classifier can be broken down into several steps. While KNN includes a bit more nuance than this, here’s my bare-bones to-do list:"
},
{
"code": null,
"e": 3092,
"s": 2677,
"text": "Define a function to calculate the distance between two pointsUse the distance function to get the distance between a test point and all known data pointsSort distance measurements to find the points closest to the test point (i.e., find the nearest neighbors)Use majority class labels of those closest points to predict the label of the test pointRepeat steps 1 through 4 until all test data points are classified"
},
{
"code": null,
"e": 3155,
"s": 3092,
"text": "Define a function to calculate the distance between two points"
},
{
"code": null,
"e": 3248,
"s": 3155,
"text": "Use the distance function to get the distance between a test point and all known data points"
},
{
"code": null,
"e": 3355,
"s": 3248,
"text": "Sort distance measurements to find the points closest to the test point (i.e., find the nearest neighbors)"
},
{
"code": null,
"e": 3444,
"s": 3355,
"text": "Use majority class labels of those closest points to predict the label of the test point"
},
{
"code": null,
"e": 3511,
"s": 3444,
"text": "Repeat steps 1 through 4 until all test data points are classified"
},
{
"code": null,
"e": 3974,
"s": 3511,
"text": "First, I define a function called minkowski_distance, that takes an input of two data points (a & b) and a Minkowski power parameter p, and returns the distance between the two points. Note that this function calculates distance exactly like the Minkowski formula I mentioned earlier. By making p an adjustable parameter, I can decide whether I want to calculate Manhattan distance (p=1), Euclidean distance (p=2), or some higher order of the Minkowski distance."
},
{
"code": null,
"e": 3993,
"s": 3974,
"text": "0.6999999999999993"
},
{
"code": null,
"e": 4115,
"s": 3993,
"text": "For step 2, I simply repeat the minkowski_distance calculation for all labeled points in X and store them in a dataframe."
},
{
"code": null,
"e": 4221,
"s": 4115,
"text": "In step 3, I use the pandas .sort_values() method to sort by distance, and return only the top 5 results."
},
{
"code": null,
"e": 4604,
"s": 4221,
"text": "For this step, I use collections.Counter to keep track of the labels that coincide with the nearest neighbor points. I then use the .most_common() method to return the most commonly occurring label. Note: if there is a tie between two or more labels for the title of “most common” label, the one that was first encountered by the Counter() object will be the one that gets returned."
},
{
"code": null,
"e": 4606,
"s": 4604,
"text": "1"
},
{
"code": null,
"e": 4972,
"s": 4606,
"text": "In this step, I put the code I’ve already written to work and write a function to classify the data using KNN. First, I perform a train_test_split on the data (75% train, 25% test), and then scale the data using StandardScaler(). Since KNN is distance-based, it is important to make sure that the features are scaled properly before feeding them into the algorithm."
},
{
"code": null,
"e": 5360,
"s": 4972,
"text": "Additionally, to avoid data leakage, it is good practice to scale the features after the train_test_split has been performed. First, scale the data from the training set only (scaler.fit_transform(X_train)), and then use that information to scale the test set (scaler.tranform(X_test)). This way, I can ensure that no information outside of the training data is used to create the model."
},
{
"code": null,
"e": 5750,
"s": 5360,
"text": "Next, I define a function called knn_predict that takes in all of the training and test data, k, and p, and returns the predictions my KNN classifier makes for the test set (y_hat_test). This function doesn’t really include anything new — it is simply applying what I’ve already worked through above. The function should return a list of label predictions containing only 0’s, 1’s and 2’s."
},
{
"code": null,
"e": 5865,
"s": 5750,
"text": "[0, 1, 1, 0, 2, 1, 2, 0, 0, 2, 1, 0, 2, 1, 1, 0, 1, 1, 0, 0, 1, 1, 2, 0, 2, 1, 0, 0, 1, 2, 1, 2, 1, 2, 2, 0, 1, 0]"
},
{
"code": null,
"e": 6004,
"s": 5865,
"text": "And there they are! These are the predictions that this home-brewed KNN classifier has made on the test set. Let’s see how well it worked:"
},
{
"code": null,
"e": 6023,
"s": 6004,
"text": "0.9736842105263158"
},
{
"code": null,
"e": 6234,
"s": 6023,
"text": "Looks like the classifier achieved 97% accuracy on the test set. Not too bad at all! But how do I know if it actually worked correctly? Let’s check the result of sklearn’s KNeighborsClassifier on the same data:"
},
{
"code": null,
"e": 6275,
"s": 6234,
"text": "Sklearn KNN Accuracy: 0.9736842105263158"
},
{
"code": null,
"e": 6368,
"s": 6275,
"text": "Nice! sklearn’s implementation of the KNN classifier gives us the exact same accuracy score."
},
{
"code": null,
"e": 6644,
"s": 6368,
"text": "My KNN classifier performed quite well with the selected value of k = 5. KNN doesn’t have as many tune-able parameters as other algorithms like Decision Trees or Random Forests, but k happens to be one of them. Let’s see how the classification accuracy changes when I vary k:"
},
{
"code": null,
"e": 7043,
"s": 6644,
"text": "In this case, using nearly any k value less than 20 results in great (>95%) classification accuracy on the test set. However, when k becomes greater than about 60, accuracy really starts to drop off. This makes sense, because the data set only has 150 observations — when k is that high, the classifier is probably considering labeled training data points that are way too far from the test points."
},
{
"code": null,
"e": 7359,
"s": 7043,
"text": "In writing my own KNN classifier, I chose to overlook one clear hyperparameter tuning opportunity: the weight that each of the k nearest points has in classifying a point. In sklearn’s KNeighborsClassifier, this is the weights parameter, and it can be set to ‘uniform’, ‘distance’, or another user-defined function."
},
{
"code": null,
"e": 7732,
"s": 7359,
"text": "When set to ‘uniform’, each of the k nearest neighbors gets an equal vote in labeling a new point. When set to ‘distance’, the neighbors in closest to the new point are weighted more heavily than the neighbors farther away. There are certainly cases where weighting by ‘distance’ would produce better results, and the only way to find out is through hyperparameter tuning."
}
]
|
Simple Little Tables with Matplotlib | by Michael Demastrie | Towards Data Science | Sometimes, I need to create an image for a document that contains a few rows and columns of data. Like most people, I’ll just use a screen capture to create the image, but this approach doesn’t lend well to automated tasks and requires hand-tweaking to get it ready to present. It’s absurd that I’m working in my Jupyter notebook with Pandas and Matplotlib, and I’m snapping screenshots to capture tables for slide decks and written reports. Matplotlib renders nice graphs. Why not nice, little tables?
One alternative is to generate the report using LaTeX, which has powerful table capabilities. Adopting LaTeX for reporting just to render a little table is overkill and often a yak shave. I’d really like to just use Matplotlib to generate my little grids with nicely centered titles; no extraneous text; a nice, clean border; and maybe a little footer with the date.
Pandas can output decent-looking dataframes within Jupyter notebooks, thanks to Jupyter’s output cell rendering. It can even style these Pandas dataframes using the pandas.Dataframe.style library. The challenge to using these tools to build styled tables is they render the output in HTML. Getting a file into an image format requires workflows that call other external tools, such as wkhtmltoimage, to translate the HTML to images.
Matplotlib can save charts as images. If you search the Matplotlib documentation, you will find it has a matplotlib.pyplot.table package, which looks promising. It is useful. I used it for this article, in fact. The challenge is that matplotlib.pyplot.table creates tables that often hang beneath stacked bar charts to provide readers insight into the data above. You want to show just the chart and you want the chart to look nice.
The first thing that you’ll probably notice when attempting to use matplotlib.pyplot.table is that the tables are rather ugly and don't manage vertical cell padding well. Second, if you try to hide the graph to just show the table grid, alignment issues rear their ugly heads and keep you from ever getting the nicely styled little table you aimed for. It takes some work to get the table to look nice, and I will share with you what I learned from doing this work myself.
The Matplotlib pyplot.table example code creates a table, but does not show how to present data with just a simple table. It generates a table used as an extension to a stacked bar chart. If you follow your intuition and only hide the chart, you will have a poorly formatted image, unsuitable for your article or slide presentation.
In this article, I take you step-by-step through the conversion of the example provided by the Matplotlib example writer to some simple table code for your projects. I provide explanation of the changes I made along the way, which should help you make enhancements. I provide the full code at the end of the article.
From the example, you can see the table feature is used to display data related to an associated stacked bar graph.
Source code for the example (from the Matplotlib Table Demo):
import numpy as npimport matplotlib.pyplot as pltdata = [[ 66386, 174296, 75131, 577908, 32015], [ 58230, 381139, 78045, 99308, 160454], [ 89135, 80552, 152558, 497981, 603535], [ 78415, 81858, 150656, 193263, 69638], [139361, 331509, 343164, 781380, 52269]]columns = ('Freeze', 'Wind', 'Flood', 'Quake', 'Hail')rows = ['%d year' % x for x in (100, 50, 20, 10, 5)]values = np.arange(0, 2500, 500)value_increment = 1000# Get some pastel shades for the colorscolors = plt.cm.BuPu(np.linspace(0, 0.5, len(rows)))n_rows = len(data)index = np.arange(len(columns)) + 0.3bar_width = 0.4# Initialize the vertical-offset for the stacked bar chart.y_offset = np.zeros(len(columns))# Plot bars and create text labels for the tablecell_text = []for row in range(n_rows): plt.bar(index, data[row], bar_width, bottom=y_offset, color=colors[row]) y_offset = y_offset + data[row] cell_text.append(['%1.1f' % (x / 1000.0) for x in y_offset])# Reverse colors and text labels to display the last value at the top.colors = colors[::-1]cell_text.reverse()# Add a table at the bottom of the axesthe_table = plt.table(cellText=cell_text, rowLabels=rows, rowColours=colors, colLabels=columns, loc='bottom')# Adjust layout to make room for the table:plt.subplots_adjust(left=0.2, bottom=0.2)plt.ylabel("Loss in ${0}'s".format(value_increment))plt.yticks(values * value_increment, ['%d' % val for val in values])plt.xticks([])plt.title('Loss by Disaster')# plt.show()# Create image. plt.savefig ignores figure edge and face colors, so map them.fig = plt.gcf()plt.savefig('pyplot-table-original.png', bbox_inches='tight', dpi=150 )
Now, let’s get down to work. First, I’ll break the table free of the chart. I reformatted the chart data to my tastes and removed data specific to the stacked bar chart. This step is optional for you. When I load small amounts of data from a Python list in the code, I prefer including the labels within the data arrays and popping them off at the right time. I can read it more easily when I come back months later. You will probably import the data from an external CSV file or database and manipulate it in a Pandas dataframe. Having the data in a two-dimension list keeps it simple for the example.
I also removed the plt.show() instruction and added code to write the image to a png file. If you called plt.show() before plt.savefig(), the image would be blank, since plt.show() resets the pyplot figure object references. Remember that plt.savefig() can output other image types by detecting the extension of the filename you provide (jpeg, svg, eps, etc.).
Note: I also made minor changes to some data and labels during my experimenting. I forgot to roll them back before publishing for consistency with the original code. For example, “100 year” became “40 year.”
data = [ [ 'Freeze', 'Wind', 'Flood', 'Quake', 'Hail'], [ '5 year', 66386, 174296, 75131, 577908, 32015], ['10 year', 58230, 381139, 78045, 99308, 160454], ['20 year', 89135, 80552, 152558, 497981, 603535], ['30 year', 78415, 81858, 150656, 193263, 69638], ['40 year', 139361, 331509, 343164, 781380, 52269], ]# Pop the headers from the data arraycolumn_headers = data.pop(0)row_headers = [x.pop(0) for x in data]# Table data needs to be non-numeric text. Format the data# while I'm at it.cell_text = []for row in data: cell_text.append([f'{x/1000:1.1f}' for x in row])...fig = plt.gcf()plt.savefig('pyplot-table-original.png', bbox_inches='tight', dpi=150 )
Let’s get to work on isolating and neatening the table. It will take a few steps. I’ll take you through them.
First, let’s hide the x and y axes, with all their ticks and labels.
ax = plt.gca()ax.get_xaxis().set_visible(False)ax.get_yaxis().set_visible(False)
The axes went away, but we’re left with a border around the space where the bar chart used to be. We can easily turn it off.
plt.box(on=None)
It’s getting cleaner, but we see a ton of whitespace between the title and the table. All we have to do is change the existing bottom alignment to center. This will center the table over the hidden axes area. We should also get rid of the subplot position tweak from the example.
Delete this line:
plt.subplots_adjust(left=0.2, bottom=0.2)
And change the plt.table line for the centered loc:
the_table = plt.table(cellText=cell_text, rowLabels=row_headers, rowColours=rcolors, colLabels=column_headers, loc='center')
That change pulls the table upward nicely. Now, let’s address the overly tight vertical space within the cells. pylot.table doesn't allow for specifying cell padding, but we can scale the height 1.5 times with the y argument of the scale(x, y) function. It gives our cell data a little breathing room. You can play with the x and y values to your taste.
the_table.scale(1, 1.5)
Let’s set column colors and set the row header horizontal alignment to right. We'll fill two lists of colors, one for every row header cell and another for every column header cell. We'll just use the plt.cm.BuPm color map that the example used, even though there are better choices than a linear color map for decorative colors. We will set the row and column label colors and alignments when creating the table.
rcolors = plt.cm.BuPu(np.full(len(row_headers), 0.1))ccolors = plt.cm.BuPu(np.full(len(column_headers), 0.1))...the_table = plt.table(cellText=cell_text, rowLabels=row_headers, rowColours=rcolors, rowLoc='right', colColours=ccolors, colLabels=column_headers, loc='center')
We can explicitly declare the figure to get easy control of its border and background color. I’ll use some labeled colors here as an example of that approach in contrast to the color map used above. I’d normally just use white for the background, but sky blue is nice for demonstrating how to set its color.
fig_background_color = 'skyblue'fig_border = 'steelblue'...plt.figure(linewidth=2, edgecolor=fig_border, facecolor=fig_background_color )...plt.savefig('pyplot-table-figure-style.png', bbox_inches='tight', edgecolor=fig.get_edgecolor(), facecolor=fig.get_facecolor(), dpi=150 )
Pretty. Like a summer day. You probably noticed that the title centers on the axes data, excluding the row headers. We’ll need center it on the figure with three code changes. These changes also improve the centering consistency of the table within the figure.
Set the title on the figure instead of the axes, using plt.suptitle()`.Set a small pad value for tight_layout in the figure declaration. Since we are now declaring a tight layout here, we should remove bbox='tight' from savefig. Leaving it in seems to worsen the centering of the table within the figure. This bbox setting is one to experiment with, if you have trouble with centering during image generation. (Experimenters: note that setting pad_inches=1 in save_fig does not have the same effect as tight_layout={'pad':1} called in the figure declaration. Someday, I'll figure out why.)Optionally, call plt.draw() before saving the figure. This can solve problems with figure border clipping and title centering during image rendering. Sometimes it has no effect.
Set the title on the figure instead of the axes, using plt.suptitle()`.
Set a small pad value for tight_layout in the figure declaration. Since we are now declaring a tight layout here, we should remove bbox='tight' from savefig. Leaving it in seems to worsen the centering of the table within the figure. This bbox setting is one to experiment with, if you have trouble with centering during image generation. (Experimenters: note that setting pad_inches=1 in save_fig does not have the same effect as tight_layout={'pad':1} called in the figure declaration. Someday, I'll figure out why.)
Optionally, call plt.draw() before saving the figure. This can solve problems with figure border clipping and title centering during image rendering. Sometimes it has no effect.
title_text = 'Loss by Disaster'...plt.figure(linewidth=2, edgecolor=fig_border, facecolor=fig_background_color, tight_layout={'pad':1} )...plt.suptitle(title_text)...plt.draw()...plt.savefig('pyplot-table-tighten-figsize.png', #bbox_inches='tight', edgecolor=fig.get_edgecolor(), facecolor=fig.get_facecolor(), dpi=150 )
We’ll just use figure text to create a footer and play with the position values until it looks right.
footer_text = 'June 24, 2020'...plt.figtext(0.95, 0.05, footer_text, horizontalalignment='right', size=6, weight='light')
The table image looks pretty good, but the automatic layout doesn’t always produce whitespacing to my taste. Playing with an explicit figure size can often dial this in. Guessing the figure size takes experimentation, and can improve or degrade your table image.
You may also need to add back in the bbox_inches='tight' to savefig to recalculate the bounding box. Otherwise, the image may not have correct right and left padding. You might find the image looks fine in a Jupyter notebook output cell without this call, but is misaligned in your saved image. Making all renderers happy is a balancing act. You should always check the final output images, even if they look great in your IDE's preview.
plt.figure(linewidth=2, edgecolor=fig_border, facecolor=fig_background_color, tight_layout={'pad':1}, figsize=(5,3) )...plt.savefig('pyplot-table-tighten-figsize.png', bbox_inches='tight', edgecolor=fig.get_edgecolor(), facecolor=fig.get_facecolor(), dpi=150 )
This final source code does not include the explicit figure size declaration. I prefer the roomier look.
import numpy as npimport matplotlib.pyplot as plttitle_text = 'Loss by Disaster'footer_text = 'June 24, 2020'fig_background_color = 'skyblue'fig_border = 'steelblue'data = [ [ 'Freeze', 'Wind', 'Flood', 'Quake', 'Hail'], [ '5 year', 66386, 174296, 75131, 577908, 32015], ['10 year', 58230, 381139, 78045, 99308, 160454], ['20 year', 89135, 80552, 152558, 497981, 603535], ['30 year', 78415, 81858, 150656, 193263, 69638], ['40 year', 139361, 331509, 343164, 781380, 52269], ]# Pop the headers from the data arraycolumn_headers = data.pop(0)row_headers = [x.pop(0) for x in data]# Table data needs to be non-numeric text. Format the data# while I'm at it.cell_text = []for row in data: cell_text.append([f'{x/1000:1.1f}' for x in row])# Get some lists of color specs for row and column headersrcolors = plt.cm.BuPu(np.full(len(row_headers), 0.1))ccolors = plt.cm.BuPu(np.full(len(column_headers), 0.1))# Create the figure. Setting a small pad on tight_layout# seems to better regulate white space. Sometimes experimenting# with an explicit figsize here can produce better outcome.plt.figure(linewidth=2, edgecolor=fig_border, facecolor=fig_background_color, tight_layout={'pad':1}, #figsize=(5,3) )# Add a table at the bottom of the axesthe_table = plt.table(cellText=cell_text, rowLabels=row_headers, rowColours=rcolors, rowLoc='right', colColours=ccolors, colLabels=column_headers, loc='center')# Scaling is the only influence we have over top and bottom cell padding.# Make the rows taller (i.e., make cell y scale larger).the_table.scale(1, 1.5)# Hide axesax = plt.gca()ax.get_xaxis().set_visible(False)ax.get_yaxis().set_visible(False)# Hide axes borderplt.box(on=None)# Add titleplt.suptitle(title_text)# Add footerplt.figtext(0.95, 0.05, footer_text, horizontalalignment='right', size=6, weight='light')# Force the figure to update, so backends center objects correctly within the figure.# Without plt.draw() here, the title will center on the axes and not the figure.plt.draw()# Create image. plt.savefig ignores figure edge and face colors, so map them.fig = plt.gcf()plt.savefig('pyplot-table-demo.png', #bbox='tight', edgecolor=fig.get_edgecolor(), facecolor=fig.get_facecolor(), dpi=150 )
I shared a step-by-step transformation of the Matplotlib pyplot.tables example into a simple, neat, little table, free of an attached chart. The table is well-aligned and suitable for your publication or presentation. The steps included code changes to hide the chart, center the table, set colors, insert a footer, and tips to improve the alignment and spacing of the final image file. Maybe these steps will save you time someday. | [
{
"code": null,
"e": 675,
"s": 172,
"text": "Sometimes, I need to create an image for a document that contains a few rows and columns of data. Like most people, I’ll just use a screen capture to create the image, but this approach doesn’t lend well to automated tasks and requires hand-tweaking to get it ready to present. It’s absurd that I’m working in my Jupyter notebook with Pandas and Matplotlib, and I’m snapping screenshots to capture tables for slide decks and written reports. Matplotlib renders nice graphs. Why not nice, little tables?"
},
{
"code": null,
"e": 1042,
"s": 675,
"text": "One alternative is to generate the report using LaTeX, which has powerful table capabilities. Adopting LaTeX for reporting just to render a little table is overkill and often a yak shave. I’d really like to just use Matplotlib to generate my little grids with nicely centered titles; no extraneous text; a nice, clean border; and maybe a little footer with the date."
},
{
"code": null,
"e": 1475,
"s": 1042,
"text": "Pandas can output decent-looking dataframes within Jupyter notebooks, thanks to Jupyter’s output cell rendering. It can even style these Pandas dataframes using the pandas.Dataframe.style library. The challenge to using these tools to build styled tables is they render the output in HTML. Getting a file into an image format requires workflows that call other external tools, such as wkhtmltoimage, to translate the HTML to images."
},
{
"code": null,
"e": 1908,
"s": 1475,
"text": "Matplotlib can save charts as images. If you search the Matplotlib documentation, you will find it has a matplotlib.pyplot.table package, which looks promising. It is useful. I used it for this article, in fact. The challenge is that matplotlib.pyplot.table creates tables that often hang beneath stacked bar charts to provide readers insight into the data above. You want to show just the chart and you want the chart to look nice."
},
{
"code": null,
"e": 2381,
"s": 1908,
"text": "The first thing that you’ll probably notice when attempting to use matplotlib.pyplot.table is that the tables are rather ugly and don't manage vertical cell padding well. Second, if you try to hide the graph to just show the table grid, alignment issues rear their ugly heads and keep you from ever getting the nicely styled little table you aimed for. It takes some work to get the table to look nice, and I will share with you what I learned from doing this work myself."
},
{
"code": null,
"e": 2714,
"s": 2381,
"text": "The Matplotlib pyplot.table example code creates a table, but does not show how to present data with just a simple table. It generates a table used as an extension to a stacked bar chart. If you follow your intuition and only hide the chart, you will have a poorly formatted image, unsuitable for your article or slide presentation."
},
{
"code": null,
"e": 3031,
"s": 2714,
"text": "In this article, I take you step-by-step through the conversion of the example provided by the Matplotlib example writer to some simple table code for your projects. I provide explanation of the changes I made along the way, which should help you make enhancements. I provide the full code at the end of the article."
},
{
"code": null,
"e": 3147,
"s": 3031,
"text": "From the example, you can see the table feature is used to display data related to an associated stacked bar graph."
},
{
"code": null,
"e": 3209,
"s": 3147,
"text": "Source code for the example (from the Matplotlib Table Demo):"
},
{
"code": null,
"e": 4976,
"s": 3209,
"text": "import numpy as npimport matplotlib.pyplot as pltdata = [[ 66386, 174296, 75131, 577908, 32015], [ 58230, 381139, 78045, 99308, 160454], [ 89135, 80552, 152558, 497981, 603535], [ 78415, 81858, 150656, 193263, 69638], [139361, 331509, 343164, 781380, 52269]]columns = ('Freeze', 'Wind', 'Flood', 'Quake', 'Hail')rows = ['%d year' % x for x in (100, 50, 20, 10, 5)]values = np.arange(0, 2500, 500)value_increment = 1000# Get some pastel shades for the colorscolors = plt.cm.BuPu(np.linspace(0, 0.5, len(rows)))n_rows = len(data)index = np.arange(len(columns)) + 0.3bar_width = 0.4# Initialize the vertical-offset for the stacked bar chart.y_offset = np.zeros(len(columns))# Plot bars and create text labels for the tablecell_text = []for row in range(n_rows): plt.bar(index, data[row], bar_width, bottom=y_offset, color=colors[row]) y_offset = y_offset + data[row] cell_text.append(['%1.1f' % (x / 1000.0) for x in y_offset])# Reverse colors and text labels to display the last value at the top.colors = colors[::-1]cell_text.reverse()# Add a table at the bottom of the axesthe_table = plt.table(cellText=cell_text, rowLabels=rows, rowColours=colors, colLabels=columns, loc='bottom')# Adjust layout to make room for the table:plt.subplots_adjust(left=0.2, bottom=0.2)plt.ylabel(\"Loss in ${0}'s\".format(value_increment))plt.yticks(values * value_increment, ['%d' % val for val in values])plt.xticks([])plt.title('Loss by Disaster')# plt.show()# Create image. plt.savefig ignores figure edge and face colors, so map them.fig = plt.gcf()plt.savefig('pyplot-table-original.png', bbox_inches='tight', dpi=150 )"
},
{
"code": null,
"e": 5579,
"s": 4976,
"text": "Now, let’s get down to work. First, I’ll break the table free of the chart. I reformatted the chart data to my tastes and removed data specific to the stacked bar chart. This step is optional for you. When I load small amounts of data from a Python list in the code, I prefer including the labels within the data arrays and popping them off at the right time. I can read it more easily when I come back months later. You will probably import the data from an external CSV file or database and manipulate it in a Pandas dataframe. Having the data in a two-dimension list keeps it simple for the example."
},
{
"code": null,
"e": 5940,
"s": 5579,
"text": "I also removed the plt.show() instruction and added code to write the image to a png file. If you called plt.show() before plt.savefig(), the image would be blank, since plt.show() resets the pyplot figure object references. Remember that plt.savefig() can output other image types by detecting the extension of the filename you provide (jpeg, svg, eps, etc.)."
},
{
"code": null,
"e": 6148,
"s": 5940,
"text": "Note: I also made minor changes to some data and labels during my experimenting. I forgot to roll them back before publishing for consistency with the original code. For example, “100 year” became “40 year.”"
},
{
"code": null,
"e": 6947,
"s": 6148,
"text": "data = [ [ 'Freeze', 'Wind', 'Flood', 'Quake', 'Hail'], [ '5 year', 66386, 174296, 75131, 577908, 32015], ['10 year', 58230, 381139, 78045, 99308, 160454], ['20 year', 89135, 80552, 152558, 497981, 603535], ['30 year', 78415, 81858, 150656, 193263, 69638], ['40 year', 139361, 331509, 343164, 781380, 52269], ]# Pop the headers from the data arraycolumn_headers = data.pop(0)row_headers = [x.pop(0) for x in data]# Table data needs to be non-numeric text. Format the data# while I'm at it.cell_text = []for row in data: cell_text.append([f'{x/1000:1.1f}' for x in row])...fig = plt.gcf()plt.savefig('pyplot-table-original.png', bbox_inches='tight', dpi=150 )"
},
{
"code": null,
"e": 7057,
"s": 6947,
"text": "Let’s get to work on isolating and neatening the table. It will take a few steps. I’ll take you through them."
},
{
"code": null,
"e": 7126,
"s": 7057,
"text": "First, let’s hide the x and y axes, with all their ticks and labels."
},
{
"code": null,
"e": 7207,
"s": 7126,
"text": "ax = plt.gca()ax.get_xaxis().set_visible(False)ax.get_yaxis().set_visible(False)"
},
{
"code": null,
"e": 7332,
"s": 7207,
"text": "The axes went away, but we’re left with a border around the space where the bar chart used to be. We can easily turn it off."
},
{
"code": null,
"e": 7349,
"s": 7332,
"text": "plt.box(on=None)"
},
{
"code": null,
"e": 7629,
"s": 7349,
"text": "It’s getting cleaner, but we see a ton of whitespace between the title and the table. All we have to do is change the existing bottom alignment to center. This will center the table over the hidden axes area. We should also get rid of the subplot position tweak from the example."
},
{
"code": null,
"e": 7647,
"s": 7629,
"text": "Delete this line:"
},
{
"code": null,
"e": 7689,
"s": 7647,
"text": "plt.subplots_adjust(left=0.2, bottom=0.2)"
},
{
"code": null,
"e": 7741,
"s": 7689,
"text": "And change the plt.table line for the centered loc:"
},
{
"code": null,
"e": 7950,
"s": 7741,
"text": "the_table = plt.table(cellText=cell_text, rowLabels=row_headers, rowColours=rcolors, colLabels=column_headers, loc='center')"
},
{
"code": null,
"e": 8304,
"s": 7950,
"text": "That change pulls the table upward nicely. Now, let’s address the overly tight vertical space within the cells. pylot.table doesn't allow for specifying cell padding, but we can scale the height 1.5 times with the y argument of the scale(x, y) function. It gives our cell data a little breathing room. You can play with the x and y values to your taste."
},
{
"code": null,
"e": 8328,
"s": 8304,
"text": "the_table.scale(1, 1.5)"
},
{
"code": null,
"e": 8742,
"s": 8328,
"text": "Let’s set column colors and set the row header horizontal alignment to right. We'll fill two lists of colors, one for every row header cell and another for every column header cell. We'll just use the plt.cm.BuPm color map that the example used, even though there are better choices than a linear color map for decorative colors. We will set the row and column label colors and alignments when creating the table."
},
{
"code": null,
"e": 9141,
"s": 8742,
"text": "rcolors = plt.cm.BuPu(np.full(len(row_headers), 0.1))ccolors = plt.cm.BuPu(np.full(len(column_headers), 0.1))...the_table = plt.table(cellText=cell_text, rowLabels=row_headers, rowColours=rcolors, rowLoc='right', colColours=ccolors, colLabels=column_headers, loc='center')"
},
{
"code": null,
"e": 9449,
"s": 9141,
"text": "We can explicitly declare the figure to get easy control of its border and background color. I’ll use some labeled colors here as an example of that approach in contrast to the color map used above. I’d normally just use white for the background, but sky blue is nice for demonstrating how to set its color."
},
{
"code": null,
"e": 9811,
"s": 9449,
"text": "fig_background_color = 'skyblue'fig_border = 'steelblue'...plt.figure(linewidth=2, edgecolor=fig_border, facecolor=fig_background_color )...plt.savefig('pyplot-table-figure-style.png', bbox_inches='tight', edgecolor=fig.get_edgecolor(), facecolor=fig.get_facecolor(), dpi=150 )"
},
{
"code": null,
"e": 10072,
"s": 9811,
"text": "Pretty. Like a summer day. You probably noticed that the title centers on the axes data, excluding the row headers. We’ll need center it on the figure with three code changes. These changes also improve the centering consistency of the table within the figure."
},
{
"code": null,
"e": 10839,
"s": 10072,
"text": "Set the title on the figure instead of the axes, using plt.suptitle()`.Set a small pad value for tight_layout in the figure declaration. Since we are now declaring a tight layout here, we should remove bbox='tight' from savefig. Leaving it in seems to worsen the centering of the table within the figure. This bbox setting is one to experiment with, if you have trouble with centering during image generation. (Experimenters: note that setting pad_inches=1 in save_fig does not have the same effect as tight_layout={'pad':1} called in the figure declaration. Someday, I'll figure out why.)Optionally, call plt.draw() before saving the figure. This can solve problems with figure border clipping and title centering during image rendering. Sometimes it has no effect."
},
{
"code": null,
"e": 10911,
"s": 10839,
"text": "Set the title on the figure instead of the axes, using plt.suptitle()`."
},
{
"code": null,
"e": 11430,
"s": 10911,
"text": "Set a small pad value for tight_layout in the figure declaration. Since we are now declaring a tight layout here, we should remove bbox='tight' from savefig. Leaving it in seems to worsen the centering of the table within the figure. This bbox setting is one to experiment with, if you have trouble with centering during image generation. (Experimenters: note that setting pad_inches=1 in save_fig does not have the same effect as tight_layout={'pad':1} called in the figure declaration. Someday, I'll figure out why.)"
},
{
"code": null,
"e": 11608,
"s": 11430,
"text": "Optionally, call plt.draw() before saving the figure. This can solve problems with figure border clipping and title centering during image rendering. Sometimes it has no effect."
},
{
"code": null,
"e": 12023,
"s": 11608,
"text": "title_text = 'Loss by Disaster'...plt.figure(linewidth=2, edgecolor=fig_border, facecolor=fig_background_color, tight_layout={'pad':1} )...plt.suptitle(title_text)...plt.draw()...plt.savefig('pyplot-table-tighten-figsize.png', #bbox_inches='tight', edgecolor=fig.get_edgecolor(), facecolor=fig.get_facecolor(), dpi=150 )"
},
{
"code": null,
"e": 12125,
"s": 12023,
"text": "We’ll just use figure text to create a footer and play with the position values until it looks right."
},
{
"code": null,
"e": 12247,
"s": 12125,
"text": "footer_text = 'June 24, 2020'...plt.figtext(0.95, 0.05, footer_text, horizontalalignment='right', size=6, weight='light')"
},
{
"code": null,
"e": 12510,
"s": 12247,
"text": "The table image looks pretty good, but the automatic layout doesn’t always produce whitespacing to my taste. Playing with an explicit figure size can often dial this in. Guessing the figure size takes experimentation, and can improve or degrade your table image."
},
{
"code": null,
"e": 12948,
"s": 12510,
"text": "You may also need to add back in the bbox_inches='tight' to savefig to recalculate the bounding box. Otherwise, the image may not have correct right and left padding. You might find the image looks fine in a Jupyter notebook output cell without this call, but is misaligned in your saved image. Making all renderers happy is a balancing act. You should always check the final output images, even if they look great in your IDE's preview."
},
{
"code": null,
"e": 13313,
"s": 12948,
"text": "plt.figure(linewidth=2, edgecolor=fig_border, facecolor=fig_background_color, tight_layout={'pad':1}, figsize=(5,3) )...plt.savefig('pyplot-table-tighten-figsize.png', bbox_inches='tight', edgecolor=fig.get_edgecolor(), facecolor=fig.get_facecolor(), dpi=150 )"
},
{
"code": null,
"e": 13418,
"s": 13313,
"text": "This final source code does not include the explicit figure size declaration. I prefer the roomier look."
},
{
"code": null,
"e": 15955,
"s": 13418,
"text": "import numpy as npimport matplotlib.pyplot as plttitle_text = 'Loss by Disaster'footer_text = 'June 24, 2020'fig_background_color = 'skyblue'fig_border = 'steelblue'data = [ [ 'Freeze', 'Wind', 'Flood', 'Quake', 'Hail'], [ '5 year', 66386, 174296, 75131, 577908, 32015], ['10 year', 58230, 381139, 78045, 99308, 160454], ['20 year', 89135, 80552, 152558, 497981, 603535], ['30 year', 78415, 81858, 150656, 193263, 69638], ['40 year', 139361, 331509, 343164, 781380, 52269], ]# Pop the headers from the data arraycolumn_headers = data.pop(0)row_headers = [x.pop(0) for x in data]# Table data needs to be non-numeric text. Format the data# while I'm at it.cell_text = []for row in data: cell_text.append([f'{x/1000:1.1f}' for x in row])# Get some lists of color specs for row and column headersrcolors = plt.cm.BuPu(np.full(len(row_headers), 0.1))ccolors = plt.cm.BuPu(np.full(len(column_headers), 0.1))# Create the figure. Setting a small pad on tight_layout# seems to better regulate white space. Sometimes experimenting# with an explicit figsize here can produce better outcome.plt.figure(linewidth=2, edgecolor=fig_border, facecolor=fig_background_color, tight_layout={'pad':1}, #figsize=(5,3) )# Add a table at the bottom of the axesthe_table = plt.table(cellText=cell_text, rowLabels=row_headers, rowColours=rcolors, rowLoc='right', colColours=ccolors, colLabels=column_headers, loc='center')# Scaling is the only influence we have over top and bottom cell padding.# Make the rows taller (i.e., make cell y scale larger).the_table.scale(1, 1.5)# Hide axesax = plt.gca()ax.get_xaxis().set_visible(False)ax.get_yaxis().set_visible(False)# Hide axes borderplt.box(on=None)# Add titleplt.suptitle(title_text)# Add footerplt.figtext(0.95, 0.05, footer_text, horizontalalignment='right', size=6, weight='light')# Force the figure to update, so backends center objects correctly within the figure.# Without plt.draw() here, the title will center on the axes and not the figure.plt.draw()# Create image. plt.savefig ignores figure edge and face colors, so map them.fig = plt.gcf()plt.savefig('pyplot-table-demo.png', #bbox='tight', edgecolor=fig.get_edgecolor(), facecolor=fig.get_facecolor(), dpi=150 )"
}
]
|
How to add a regression line to a plot in base R if intercept and slope are given? | To add a regression line to a plot in base R if intercept and slope are given, we can follow the below steps −
First of all, create two vectors and the scatterplot between them.
Then, use abline function to create the regression line with intercept and slope given by a and b respectively.
Use plot functions to create scatterplot between two random vectors x and y −
Live Demo
> x<-round(rnorm(20),2)
> y<-round(rnorm(20),2)
> plot(x,y)
Using abline function to add the regression line to the scatterplot with given intercept a = 0.51 and slope = -1.05 −
Live Demo
> x<-round(rnorm(20),2)
> y<-round(rnorm(20),2)
> plot(x,y)
> abline(a=0.51,b=-1.05) | [
{
"code": null,
"e": 1173,
"s": 1062,
"text": "To add a regression line to a plot in base R if intercept and slope are given, we can follow the below steps −"
},
{
"code": null,
"e": 1240,
"s": 1173,
"text": "First of all, create two vectors and the scatterplot between them."
},
{
"code": null,
"e": 1352,
"s": 1240,
"text": "Then, use abline function to create the regression line with intercept and slope given by a and b respectively."
},
{
"code": null,
"e": 1430,
"s": 1352,
"text": "Use plot functions to create scatterplot between two random vectors x and y −"
},
{
"code": null,
"e": 1441,
"s": 1430,
"text": " Live Demo"
},
{
"code": null,
"e": 1501,
"s": 1441,
"text": "> x<-round(rnorm(20),2)\n> y<-round(rnorm(20),2)\n> plot(x,y)"
},
{
"code": null,
"e": 1619,
"s": 1501,
"text": "Using abline function to add the regression line to the scatterplot with given intercept a = 0.51 and slope = -1.05 −"
},
{
"code": null,
"e": 1630,
"s": 1619,
"text": " Live Demo"
},
{
"code": null,
"e": 1715,
"s": 1630,
"text": "> x<-round(rnorm(20),2)\n> y<-round(rnorm(20),2)\n> plot(x,y)\n> abline(a=0.51,b=-1.05)"
}
]
|
SQL - Transactions | A transaction is a unit of work that is performed against a database. Transactions are units or sequences of work accomplished in a logical order, whether in a manual fashion by a user or automatically by some sort of a database program.
A transaction is the propagation of one or more changes to the database. For example, if you are creating a record or updating a record or deleting a record from the table, then you are performing a transaction on that table. It is important to control these transactions to ensure the data integrity and to handle database errors.
Practically, you will club many SQL queries into a group and you will execute all of them together as a part of a transaction.
Transactions have the following four standard properties, usually referred to by the acronym ACID.
Atomicity − ensures that all operations within the work unit are completed successfully. Otherwise, the transaction is aborted at the point of failure and all the previous operations are rolled back to their former state.
Atomicity − ensures that all operations within the work unit are completed successfully. Otherwise, the transaction is aborted at the point of failure and all the previous operations are rolled back to their former state.
Consistency − ensures that the database properly changes states upon a successfully committed transaction.
Consistency − ensures that the database properly changes states upon a successfully committed transaction.
Isolation − enables transactions to operate independently of and transparent to each other.
Isolation − enables transactions to operate independently of and transparent to each other.
Durability − ensures that the result or effect of a committed transaction persists in case of a system failure.
Durability − ensures that the result or effect of a committed transaction persists in case of a system failure.
The following commands are used to control transactions.
COMMIT − to save the changes.
COMMIT − to save the changes.
ROLLBACK − to roll back the changes.
ROLLBACK − to roll back the changes.
SAVEPOINT − creates points within the groups of transactions in which to ROLLBACK.
SAVEPOINT − creates points within the groups of transactions in which to ROLLBACK.
SET TRANSACTION − Places a name on a transaction.
SET TRANSACTION − Places a name on a transaction.
Transactional control commands are only used with the DML Commands such as - INSERT, UPDATE and DELETE only. They cannot be used while creating tables or dropping them because these operations are automatically committed in the database.
The COMMIT command is the transactional command used to save changes invoked by a transaction to the database.
The COMMIT command is the transactional command used to save changes invoked by a transaction to the database. The COMMIT command saves all the transactions to the database since the last COMMIT or ROLLBACK command.
The syntax for the COMMIT command is as follows.
COMMIT;
Example
Consider the CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is an example which would delete those records from the table which have age = 25 and then COMMIT the changes in the database.
SQL> DELETE FROM CUSTOMERS
WHERE AGE = 25;
SQL> COMMIT;
Thus, two rows from the table would be deleted and the SELECT statement would produce the following result.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
The ROLLBACK command is the transactional command used to undo transactions that have not already been saved to the database. This command can only be used to undo transactions since the last COMMIT or ROLLBACK command was issued.
The syntax for a ROLLBACK command is as follows −
ROLLBACK;
Example
Consider the CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is an example, which would delete those records from the table which have the age = 25 and then ROLLBACK the changes in the database.
SQL> DELETE FROM CUSTOMERS
WHERE AGE = 25;
SQL> ROLLBACK;
Thus, the delete operation would not impact the table and the SELECT statement would produce the following result.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
A SAVEPOINT is a point in a transaction when you can roll the transaction back to a certain point without rolling back the entire transaction.
The syntax for a SAVEPOINT command is as shown below.
SAVEPOINT SAVEPOINT_NAME;
This command serves only in the creation of a SAVEPOINT among all the transactional statements. The ROLLBACK command is used to undo a group of transactions.
The syntax for rolling back to a SAVEPOINT is as shown below.
ROLLBACK TO SAVEPOINT_NAME;
Following is an example where you plan to delete the three different records from the CUSTOMERS table. You want to create a SAVEPOINT before each delete, so that you can ROLLBACK to any SAVEPOINT at any time to return the appropriate data to its original state.
Example
Consider the CUSTOMERS table having the following records.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
The following code block contains the series of operations.
SQL> SAVEPOINT SP1;
Savepoint created.
SQL> DELETE FROM CUSTOMERS WHERE ID=1;
1 row deleted.
SQL> SAVEPOINT SP2;
Savepoint created.
SQL> DELETE FROM CUSTOMERS WHERE ID=2;
1 row deleted.
SQL> SAVEPOINT SP3;
Savepoint created.
SQL> DELETE FROM CUSTOMERS WHERE ID=3;
1 row deleted.
Now that the three deletions have taken place, let us assume that you have changed your mind and decided to ROLLBACK to the SAVEPOINT that you identified as SP2. Because SP2 was created after the first deletion, the last two deletions are undone −
SQL> ROLLBACK TO SP2;
Rollback complete.
Notice that only the first deletion took place since you rolled back to SP2.
SQL> SELECT * FROM CUSTOMERS;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
6 rows selected.
The RELEASE SAVEPOINT command is used to remove a SAVEPOINT that you have created.
The syntax for a RELEASE SAVEPOINT command is as follows.
RELEASE SAVEPOINT SAVEPOINT_NAME;
Once a SAVEPOINT has been released, you can no longer use the ROLLBACK command to undo transactions performed since the last SAVEPOINT.
The SET TRANSACTION command can be used to initiate a database transaction. This command is used to specify characteristics for the transaction that follows. For example, you can specify a transaction to be read only or read write.
The syntax for a SET TRANSACTION command is as follows.
SET TRANSACTION [ READ WRITE | READ ONLY ];
42 Lectures
5 hours
Anadi Sharma
14 Lectures
2 hours
Anadi Sharma
44 Lectures
4.5 hours
Anadi Sharma
94 Lectures
7 hours
Abhishek And Pukhraj
80 Lectures
6.5 hours
Oracle Master Training | 150,000+ Students Worldwide
31 Lectures
6 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2691,
"s": 2453,
"text": "A transaction is a unit of work that is performed against a database. Transactions are units or sequences of work accomplished in a logical order, whether in a manual fashion by a user or automatically by some sort of a database program."
},
{
"code": null,
"e": 3023,
"s": 2691,
"text": "A transaction is the propagation of one or more changes to the database. For example, if you are creating a record or updating a record or deleting a record from the table, then you are performing a transaction on that table. It is important to control these transactions to ensure the data integrity and to handle database errors."
},
{
"code": null,
"e": 3150,
"s": 3023,
"text": "Practically, you will club many SQL queries into a group and you will execute all of them together as a part of a transaction."
},
{
"code": null,
"e": 3249,
"s": 3150,
"text": "Transactions have the following four standard properties, usually referred to by the acronym ACID."
},
{
"code": null,
"e": 3471,
"s": 3249,
"text": "Atomicity − ensures that all operations within the work unit are completed successfully. Otherwise, the transaction is aborted at the point of failure and all the previous operations are rolled back to their former state."
},
{
"code": null,
"e": 3693,
"s": 3471,
"text": "Atomicity − ensures that all operations within the work unit are completed successfully. Otherwise, the transaction is aborted at the point of failure and all the previous operations are rolled back to their former state."
},
{
"code": null,
"e": 3800,
"s": 3693,
"text": "Consistency − ensures that the database properly changes states upon a successfully committed transaction."
},
{
"code": null,
"e": 3907,
"s": 3800,
"text": "Consistency − ensures that the database properly changes states upon a successfully committed transaction."
},
{
"code": null,
"e": 3999,
"s": 3907,
"text": "Isolation − enables transactions to operate independently of and transparent to each other."
},
{
"code": null,
"e": 4091,
"s": 3999,
"text": "Isolation − enables transactions to operate independently of and transparent to each other."
},
{
"code": null,
"e": 4203,
"s": 4091,
"text": "Durability − ensures that the result or effect of a committed transaction persists in case of a system failure."
},
{
"code": null,
"e": 4315,
"s": 4203,
"text": "Durability − ensures that the result or effect of a committed transaction persists in case of a system failure."
},
{
"code": null,
"e": 4372,
"s": 4315,
"text": "The following commands are used to control transactions."
},
{
"code": null,
"e": 4402,
"s": 4372,
"text": "COMMIT − to save the changes."
},
{
"code": null,
"e": 4432,
"s": 4402,
"text": "COMMIT − to save the changes."
},
{
"code": null,
"e": 4469,
"s": 4432,
"text": "ROLLBACK − to roll back the changes."
},
{
"code": null,
"e": 4506,
"s": 4469,
"text": "ROLLBACK − to roll back the changes."
},
{
"code": null,
"e": 4589,
"s": 4506,
"text": "SAVEPOINT − creates points within the groups of transactions in which to ROLLBACK."
},
{
"code": null,
"e": 4672,
"s": 4589,
"text": "SAVEPOINT − creates points within the groups of transactions in which to ROLLBACK."
},
{
"code": null,
"e": 4722,
"s": 4672,
"text": "SET TRANSACTION − Places a name on a transaction."
},
{
"code": null,
"e": 4772,
"s": 4722,
"text": "SET TRANSACTION − Places a name on a transaction."
},
{
"code": null,
"e": 5010,
"s": 4772,
"text": "Transactional control commands are only used with the DML Commands such as - INSERT, UPDATE and DELETE only. They cannot be used while creating tables or dropping them because these operations are automatically committed in the database."
},
{
"code": null,
"e": 5121,
"s": 5010,
"text": "The COMMIT command is the transactional command used to save changes invoked by a transaction to the database."
},
{
"code": null,
"e": 5337,
"s": 5121,
"text": "The COMMIT command is the transactional command used to save changes invoked by a transaction to the database. The COMMIT command saves all the transactions to the database since the last COMMIT or ROLLBACK command."
},
{
"code": null,
"e": 5386,
"s": 5337,
"text": "The syntax for the COMMIT command is as follows."
},
{
"code": null,
"e": 5395,
"s": 5386,
"text": "COMMIT;\n"
},
{
"code": null,
"e": 5403,
"s": 5395,
"text": "Example"
},
{
"code": null,
"e": 5463,
"s": 5403,
"text": "Consider the CUSTOMERS table having the following records −"
},
{
"code": null,
"e": 5980,
"s": 5463,
"text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+"
},
{
"code": null,
"e": 6117,
"s": 5980,
"text": "Following is an example which would delete those records from the table which have age = 25 and then COMMIT the changes in the database."
},
{
"code": null,
"e": 6176,
"s": 6117,
"text": "SQL> DELETE FROM CUSTOMERS\n WHERE AGE = 25;\nSQL> COMMIT;"
},
{
"code": null,
"e": 6284,
"s": 6176,
"text": "Thus, two rows from the table would be deleted and the SELECT statement would produce the following result."
},
{
"code": null,
"e": 6708,
"s": 6284,
"text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n"
},
{
"code": null,
"e": 6939,
"s": 6708,
"text": "The ROLLBACK command is the transactional command used to undo transactions that have not already been saved to the database. This command can only be used to undo transactions since the last COMMIT or ROLLBACK command was issued."
},
{
"code": null,
"e": 6989,
"s": 6939,
"text": "The syntax for a ROLLBACK command is as follows −"
},
{
"code": null,
"e": 7000,
"s": 6989,
"text": "ROLLBACK;\n"
},
{
"code": null,
"e": 7008,
"s": 7000,
"text": "Example"
},
{
"code": null,
"e": 7068,
"s": 7008,
"text": "Consider the CUSTOMERS table having the following records −"
},
{
"code": null,
"e": 7585,
"s": 7068,
"text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+"
},
{
"code": null,
"e": 7729,
"s": 7585,
"text": "Following is an example, which would delete those records from the table which have the age = 25 and then ROLLBACK the changes in the database."
},
{
"code": null,
"e": 7790,
"s": 7729,
"text": "SQL> DELETE FROM CUSTOMERS\n WHERE AGE = 25;\nSQL> ROLLBACK;"
},
{
"code": null,
"e": 7905,
"s": 7790,
"text": "Thus, the delete operation would not impact the table and the SELECT statement would produce the following result."
},
{
"code": null,
"e": 8423,
"s": 7905,
"text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n"
},
{
"code": null,
"e": 8566,
"s": 8423,
"text": "A SAVEPOINT is a point in a transaction when you can roll the transaction back to a certain point without rolling back the entire transaction."
},
{
"code": null,
"e": 8620,
"s": 8566,
"text": "The syntax for a SAVEPOINT command is as shown below."
},
{
"code": null,
"e": 8647,
"s": 8620,
"text": "SAVEPOINT SAVEPOINT_NAME;\n"
},
{
"code": null,
"e": 8805,
"s": 8647,
"text": "This command serves only in the creation of a SAVEPOINT among all the transactional statements. The ROLLBACK command is used to undo a group of transactions."
},
{
"code": null,
"e": 8867,
"s": 8805,
"text": "The syntax for rolling back to a SAVEPOINT is as shown below."
},
{
"code": null,
"e": 8896,
"s": 8867,
"text": "ROLLBACK TO SAVEPOINT_NAME;\n"
},
{
"code": null,
"e": 9158,
"s": 8896,
"text": "Following is an example where you plan to delete the three different records from the CUSTOMERS table. You want to create a SAVEPOINT before each delete, so that you can ROLLBACK to any SAVEPOINT at any time to return the appropriate data to its original state."
},
{
"code": null,
"e": 9166,
"s": 9158,
"text": "Example"
},
{
"code": null,
"e": 9225,
"s": 9166,
"text": "Consider the CUSTOMERS table having the following records."
},
{
"code": null,
"e": 9742,
"s": 9225,
"text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+"
},
{
"code": null,
"e": 9802,
"s": 9742,
"text": "The following code block contains the series of operations."
},
{
"code": null,
"e": 10081,
"s": 9802,
"text": "SQL> SAVEPOINT SP1;\nSavepoint created.\nSQL> DELETE FROM CUSTOMERS WHERE ID=1;\n1 row deleted.\nSQL> SAVEPOINT SP2;\nSavepoint created.\nSQL> DELETE FROM CUSTOMERS WHERE ID=2;\n1 row deleted.\nSQL> SAVEPOINT SP3;\nSavepoint created.\nSQL> DELETE FROM CUSTOMERS WHERE ID=3;\n1 row deleted."
},
{
"code": null,
"e": 10329,
"s": 10081,
"text": "Now that the three deletions have taken place, let us assume that you have changed your mind and decided to ROLLBACK to the SAVEPOINT that you identified as SP2. Because SP2 was created after the first deletion, the last two deletions are undone −"
},
{
"code": null,
"e": 10370,
"s": 10329,
"text": "SQL> ROLLBACK TO SP2;\nRollback complete."
},
{
"code": null,
"e": 10447,
"s": 10370,
"text": "Notice that only the first deletion took place since you rolled back to SP2."
},
{
"code": null,
"e": 10964,
"s": 10447,
"text": "SQL> SELECT * FROM CUSTOMERS;\n+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n6 rows selected."
},
{
"code": null,
"e": 11047,
"s": 10964,
"text": "The RELEASE SAVEPOINT command is used to remove a SAVEPOINT that you have created."
},
{
"code": null,
"e": 11105,
"s": 11047,
"text": "The syntax for a RELEASE SAVEPOINT command is as follows."
},
{
"code": null,
"e": 11140,
"s": 11105,
"text": "RELEASE SAVEPOINT SAVEPOINT_NAME;\n"
},
{
"code": null,
"e": 11276,
"s": 11140,
"text": "Once a SAVEPOINT has been released, you can no longer use the ROLLBACK command to undo transactions performed since the last SAVEPOINT."
},
{
"code": null,
"e": 11508,
"s": 11276,
"text": "The SET TRANSACTION command can be used to initiate a database transaction. This command is used to specify characteristics for the transaction that follows. For example, you can specify a transaction to be read only or read write."
},
{
"code": null,
"e": 11564,
"s": 11508,
"text": "The syntax for a SET TRANSACTION command is as follows."
},
{
"code": null,
"e": 11609,
"s": 11564,
"text": "SET TRANSACTION [ READ WRITE | READ ONLY ];\n"
},
{
"code": null,
"e": 11642,
"s": 11609,
"text": "\n 42 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 11656,
"s": 11642,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 11689,
"s": 11656,
"text": "\n 14 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 11703,
"s": 11689,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 11738,
"s": 11703,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 11752,
"s": 11738,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 11785,
"s": 11752,
"text": "\n 94 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 11807,
"s": 11785,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 11842,
"s": 11807,
"text": "\n 80 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 11896,
"s": 11842,
"text": " Oracle Master Training | 150,000+ Students Worldwide"
},
{
"code": null,
"e": 11929,
"s": 11896,
"text": "\n 31 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 11957,
"s": 11929,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 11964,
"s": 11957,
"text": " Print"
},
{
"code": null,
"e": 11975,
"s": 11964,
"text": " Add Notes"
}
]
|
Break statement in Scala - GeeksforGeeks | 17 Jan, 2019
In Scala, we use a break statement to break the execution of the loop in the program. Scala programing language does not contain any concept of break statement(in above 2.8 versions), instead of break statement, it provides a break method, which is used to break the execution of a program or a loop. Break method is used by importing scala.util.control.breaks._ package.
Flow Chart:
Syntax:
// import package
import scala.util.control._
// create a Breaks object
val loop = new breaks;
// loop inside breakable
loop.breakable{
// Loop starts
for(..)
{
// code
loop.break
}
}
or
import scala.util.control.Breaks._
breakable
{
for(..)
{
code..
break
}
}
For example:
// Scala program to illustrate the // implementation of break // Importing break packageimport scala.util.control.Breaks._object MainObject { // Main methoddef main(args: Array[String]) { // Here, breakable is used to prevent exception breakable { for (a <- 1 to 10) { if (a == 6) // terminate the loop when // the value of a is equal to 6 break else println(a); } }}}
Output:
1
2
3
4
5
Break in Nested loop: We can also use break method in nested loop.
For example:
// Scala program to illustrate the // implementation of break in nested loop // Importing break packageimport scala.util.control._ object Test { // Main methoddef main(args: Array[String]) { var num1 = 0; var num2 = 0; val x = List(5, 10, 15); val y = List(20, 25, 30); val outloop = new Breaks; val inloop = new Breaks; // Here, breakable is used to // prevent from exception outloop.breakable { for (num1 <- x) { // print list x println(" " + num1); inloop.breakable { for (num2 <- y) { //print list y println(" " + num2); if (num2 == 25) { // inloop is break when // num2 is equal to 25 inloop.break; } } // Here, inloop breakable } } // Here, outloop breakable } }}
Output:
5
20
25
10
20
25
15
20
25
Explanation: In the above example, the initial value of both num1 and num2 is 0. Now first outer for loop start and print 5 from the x list, then the inner for loop start its working and print 20, 25 from the y list, when the controls go to num2 == 25 condition, then the inner loop breaks. Similarly for 10 and 15.
Scala
Scala-Basics
Scala-Decision-Making
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
For Loop in Scala
Scala Tutorial – Learn Scala with Step By Step Guide
Scala | map() method
Scala | flatMap Method
Scala List filter() method with example
Scala | reduce() Function
String concatenation in Scala
Type Casting in Scala
Scala List contains() method with example
Scala String substring() method with example | [
{
"code": null,
"e": 24427,
"s": 24399,
"text": "\n17 Jan, 2019"
},
{
"code": null,
"e": 24799,
"s": 24427,
"text": "In Scala, we use a break statement to break the execution of the loop in the program. Scala programing language does not contain any concept of break statement(in above 2.8 versions), instead of break statement, it provides a break method, which is used to break the execution of a program or a loop. Break method is used by importing scala.util.control.breaks._ package."
},
{
"code": null,
"e": 24811,
"s": 24799,
"text": "Flow Chart:"
},
{
"code": null,
"e": 24819,
"s": 24811,
"text": "Syntax:"
},
{
"code": null,
"e": 25008,
"s": 24819,
"text": "// import package\nimport scala.util.control._\n\n// create a Breaks object \nval loop = new breaks;\n\n// loop inside breakable\nloop.breakable{\n\n// Loop starts\nfor(..)\n{\n// code\nloop.break\n}\n}\n"
},
{
"code": null,
"e": 25011,
"s": 25008,
"text": "or"
},
{
"code": null,
"e": 25089,
"s": 25011,
"text": "import scala.util.control.Breaks._\nbreakable \n{\n for(..)\n{\n code..\n break\n}\n}"
},
{
"code": null,
"e": 25102,
"s": 25089,
"text": "For example:"
},
{
"code": "// Scala program to illustrate the // implementation of break // Importing break packageimport scala.util.control.Breaks._object MainObject { // Main methoddef main(args: Array[String]) { // Here, breakable is used to prevent exception breakable { for (a <- 1 to 10) { if (a == 6) // terminate the loop when // the value of a is equal to 6 break else println(a); } }}}",
"e": 25611,
"s": 25102,
"text": null
},
{
"code": null,
"e": 25619,
"s": 25611,
"text": "Output:"
},
{
"code": null,
"e": 25629,
"s": 25619,
"text": "1\n2\n3\n4\n5"
},
{
"code": null,
"e": 25697,
"s": 25629,
"text": " Break in Nested loop: We can also use break method in nested loop."
},
{
"code": null,
"e": 25710,
"s": 25697,
"text": "For example:"
},
{
"code": "// Scala program to illustrate the // implementation of break in nested loop // Importing break packageimport scala.util.control._ object Test { // Main methoddef main(args: Array[String]) { var num1 = 0; var num2 = 0; val x = List(5, 10, 15); val y = List(20, 25, 30); val outloop = new Breaks; val inloop = new Breaks; // Here, breakable is used to // prevent from exception outloop.breakable { for (num1 <- x) { // print list x println(\" \" + num1); inloop.breakable { for (num2 <- y) { //print list y println(\" \" + num2); if (num2 == 25) { // inloop is break when // num2 is equal to 25 inloop.break; } } // Here, inloop breakable } } // Here, outloop breakable } }}",
"e": 26709,
"s": 25710,
"text": null
},
{
"code": null,
"e": 26717,
"s": 26709,
"text": "Output:"
},
{
"code": null,
"e": 26753,
"s": 26717,
"text": " 5\n 20\n 25\n 10\n 20\n 25\n 15\n 20\n 25"
},
{
"code": null,
"e": 27069,
"s": 26753,
"text": "Explanation: In the above example, the initial value of both num1 and num2 is 0. Now first outer for loop start and print 5 from the x list, then the inner for loop start its working and print 20, 25 from the y list, when the controls go to num2 == 25 condition, then the inner loop breaks. Similarly for 10 and 15."
},
{
"code": null,
"e": 27075,
"s": 27069,
"text": "Scala"
},
{
"code": null,
"e": 27088,
"s": 27075,
"text": "Scala-Basics"
},
{
"code": null,
"e": 27110,
"s": 27088,
"text": "Scala-Decision-Making"
},
{
"code": null,
"e": 27116,
"s": 27110,
"text": "Scala"
},
{
"code": null,
"e": 27214,
"s": 27116,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27223,
"s": 27214,
"text": "Comments"
},
{
"code": null,
"e": 27236,
"s": 27223,
"text": "Old Comments"
},
{
"code": null,
"e": 27254,
"s": 27236,
"text": "For Loop in Scala"
},
{
"code": null,
"e": 27307,
"s": 27254,
"text": "Scala Tutorial – Learn Scala with Step By Step Guide"
},
{
"code": null,
"e": 27328,
"s": 27307,
"text": "Scala | map() method"
},
{
"code": null,
"e": 27351,
"s": 27328,
"text": "Scala | flatMap Method"
},
{
"code": null,
"e": 27391,
"s": 27351,
"text": "Scala List filter() method with example"
},
{
"code": null,
"e": 27417,
"s": 27391,
"text": "Scala | reduce() Function"
},
{
"code": null,
"e": 27447,
"s": 27417,
"text": "String concatenation in Scala"
},
{
"code": null,
"e": 27469,
"s": 27447,
"text": "Type Casting in Scala"
},
{
"code": null,
"e": 27511,
"s": 27469,
"text": "Scala List contains() method with example"
}
]
|
How to Deploy Static Website using Caddy Webserver? - GeeksforGeeks | 23 Jun, 2021
Caddy web server is an open-source web server written in Go. It uses the Go standard library for its HTTP functionality and supports HTTPS natively, which means it takes care of your SSL certificate management. In this article, we are going to deploy a static website to caddy webserver on a VPS. We will be using ubuntu
Basic Linux experience
An Ubuntu VPs(new/existing)
Basic knowledge of HTML and CSS
Domain name
Step 1: login into your new/existing VPS and make sure its packages are up to date.
ssh user@<vps-ip/hostname>
sudo apt update && sudo apt upgrade
Step 2: Install the latest version of the Go programming language. The below command will install the latest version of Go Snap( whatever version you install make sure it is above 1.14.2)
sudo snap install go --classic
Go installed
Step 3: Download and install the latest version of xcaddy, xcaddy helps us to install caddy easily
sudo apt install -y debian-keyring debian-archive-keyring apt-transport-https
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/xcaddy/gpg.key' | sudo apt-key add -
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/xcaddy/debian.deb.txt' | sudo tee /etc/apt/sources.list.d/caddy-xcaddy.list
sudo apt update
sudo apt install xcaddy
Installing Xcaddy
Step 4: After installing xcaddy now we need to install the Caddy webserver. For that follow the below commands
mkdir ~/caddyserver
cd ~/caddyserver
// for only caddy build
xcaddy build
// for building caddy with some plugins
xcaddy build --with=github.com/caddy-dns/cloudflare
sudo mv caddy /usr/bin
To check whether caddy is installed successfully or not you can use the below command, if it prints out the version of caddy then its installed
caddy version
//output
v2.4.2 h1:chB106RlsIaY4mVEyq9OQM5g/9lHYVputo/LAX2ndFg=
Caddy Web server installed
Step 5: Configure a systemd service so that Caddy can be launched automatically on system boot
sudo groupadd --system caddy
sudo useradd --system --gid caddy --create-home --home-dir /var/lib/caddy --shell /usr/sbin/nologin --comment "Caddy web server | learned from GFG" caddy
Added user and group caddy
As caddy requires its own group and user to run the systemd process, the first command creates a new group caddy(you can give your own name, but it will be useful to identify in case of troubleshooting) and the second command creates user again named caddy and assigns it to caddy group. nologin command says that you can’t login into shell as caddy user.
Step 6: Create a caddy service file and add required permissions to it.
sudo nano /etc/systemd/system/caddy.service
Copy and paste the below prebuilt system service file from Caddy repository
# caddy.service
#
# For using Caddy with a config file.
#
# Make sure the ExecStart and ExecReload commands are correct
# for your installation.
#
# See https://caddyserver.com/docs/install for instructions.
#
# WARNING: This service does not use the --resume flag, so if you
# use the API to make changes, they will be overwritten by the
# Caddyfile next time the service is restarted. If you intend to
# use Caddy's API to configure it, add the --resume flag to the
# `caddy run` command or use the caddy-api.service file instead.
[Unit]
Description=Caddy
Documentation=https://caddyserver.com/docs/
After=network.target network-online.target
Requires=network-online.target
[Service]
Type=notify
User=caddy
Group=caddy
ExecStart=/usr/bin/caddy run --environ --config /etc/caddy/Caddyfile
ExecReload=/usr/bin/caddy reload --config /etc/caddy/Caddyfile
TimeoutStopSec=5s
LimitNOFILE=1048576
LimitNPROC=512
PrivateTmp=true
ProtectSystem=full
AmbientCapabilities=CAP_NET_BIND_SERVICE
[Install]
WantedBy=multi-user.target
systemd service
Assign permission so that only the root user can modify it
sudo chmod 644 /etc/systemd/system/caddy.service
Step 7: Now we need to set directory permissions to caddy directories
// 755 permission gives root user rwx but others only rx for caddy binary
sudo chmod 755 /usr/bin/caddy
// creating caddy configuration folder
sudo mkdir /etc/caddy
// creating caddy config file
sudo touch /etc/caddy/Caddyfile
//giving ownership of caddy config folder to both root user and caddy group
sudo chown -R root:caddy /etc/caddy
// creating ssl folder for caddy to store the fetched ssl certificates
sudo mkdir /etc/ssl/caddy
//giving ownership of caddy config folder to both root user and caddy group
sudo chown -R root:caddy /etc/ssl/caddy
// 770 ensures that caddy can write to the folder and it can't be executed
sudo chmod 0770 /etc/ssl/caddy
// create and assign ownership of website contents to caddy uper and group
sudo mkdir /var/www/public_html
sudo chown caddy:caddy /var/www/public_html
Setting permissions
Step 8: Create a simple index.html file int public_html folder we created in previous step
sudo nano /var/www/public_html/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="viewport"content="width=device-width,initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"rel="stylesheet"integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl"crossorigin="anonymous">
<title>Host Static website using Caddy web server</title>
</head>
<body class="text-center">
<div class="jumbotron text-center">
<h1>Welcome to GeeksForGeeks</h1>
<h2 class="h2 card-title">This article explains how to host static websites using caddy webserver</h2>
<h6 class="h6 card-text">Thank You for Reading</h6>
</div>
</body>
</html>
index.html
Step 9: Configuring Caddy for this you need to edit the config file we created in step 7.
sudo nano /etc/caddy/Caddyfile
Below is a sample caddy config file.
example.com {
tls {
email [email protected]
}
root * /var/www/public_html
encode gzip
file_server
header / {
Content-Security-Policy = "upgrade-insecure-requests; default-src 'self'; style-src 'self'; script-src 'self'; img-src 'self'; object-src 'self'; worker-src 'self'; manifest-src 'self';"
Strict-Transport-Security = "max-age=63072000; includeSubDomains; preload"
X-Xss-Protection = "1; mode=block"
X-Frame-Options = "DENY"
X-Content-Type-Options = "nosniff"
Referrer-Policy = "strict-origin-when-cross-origin"
Permissions-Policy = "fullscreen=(self)"
cache-control = "max-age=0,no-cache,no-store,must-revalidate"
}
}
First line tells the caddy the domain name(example.com) that block of configuration belongs to. It’s also used to fetch SSL certificates.
The TLS block helps us to configure SSL for the domain, for this specific file configuration email the hostname for any issuance and errors in the SSL fetching and configuration
Root tells the root directory of the website contents
Encoding of the content
File_server helps caddy to serve static files
Header block tells caddy to send these headers along with the response, the specific config tells caddy to serve CSP, XSS, HSTS and cache control headers along with the response
Caddyfile
Step 10: Now run caddy using the below commands
// reloading daemon to apply caddy system service file
sudo systemctl daemon-reload
// starting caddy
sudo systemctl start caddy
//activating caddy system file
sudo systemctl enable caddy
sudo systemctl restart caddy
Caddy server running successfully
Now visit your website from your favorite browser:
Running in browser
Advanced Computer Subject
How To
Linux-Unix
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Copying Files to and from Docker Containers
Principal Component Analysis with Python
OpenCV - Overview
Mounting a Volume Inside Docker Container
Fuzzy Logic | Introduction
How to Install PIP on Windows ?
How to Find the Wi-Fi Password Using CMD in Windows?
How to install Jupyter Notebook on Windows?
How to Align Text in HTML?
How to Install OpenCV for Python on Windows? | [
{
"code": null,
"e": 23837,
"s": 23809,
"text": "\n23 Jun, 2021"
},
{
"code": null,
"e": 24158,
"s": 23837,
"text": "Caddy web server is an open-source web server written in Go. It uses the Go standard library for its HTTP functionality and supports HTTPS natively, which means it takes care of your SSL certificate management. In this article, we are going to deploy a static website to caddy webserver on a VPS. We will be using ubuntu"
},
{
"code": null,
"e": 24181,
"s": 24158,
"text": "Basic Linux experience"
},
{
"code": null,
"e": 24209,
"s": 24181,
"text": "An Ubuntu VPs(new/existing)"
},
{
"code": null,
"e": 24241,
"s": 24209,
"text": "Basic knowledge of HTML and CSS"
},
{
"code": null,
"e": 24253,
"s": 24241,
"text": "Domain name"
},
{
"code": null,
"e": 24337,
"s": 24253,
"text": "Step 1: login into your new/existing VPS and make sure its packages are up to date."
},
{
"code": null,
"e": 24400,
"s": 24337,
"text": "ssh user@<vps-ip/hostname>\nsudo apt update && sudo apt upgrade"
},
{
"code": null,
"e": 24588,
"s": 24400,
"text": "Step 2: Install the latest version of the Go programming language. The below command will install the latest version of Go Snap( whatever version you install make sure it is above 1.14.2)"
},
{
"code": null,
"e": 24619,
"s": 24588,
"text": "sudo snap install go --classic"
},
{
"code": null,
"e": 24632,
"s": 24619,
"text": "Go installed"
},
{
"code": null,
"e": 24731,
"s": 24632,
"text": "Step 3: Download and install the latest version of xcaddy, xcaddy helps us to install caddy easily"
},
{
"code": null,
"e": 25062,
"s": 24731,
"text": "sudo apt install -y debian-keyring debian-archive-keyring apt-transport-https\ncurl -1sLf 'https://dl.cloudsmith.io/public/caddy/xcaddy/gpg.key' | sudo apt-key add -\ncurl -1sLf 'https://dl.cloudsmith.io/public/caddy/xcaddy/debian.deb.txt' | sudo tee /etc/apt/sources.list.d/caddy-xcaddy.list\nsudo apt update\nsudo apt install xcaddy"
},
{
"code": null,
"e": 25080,
"s": 25062,
"text": "Installing Xcaddy"
},
{
"code": null,
"e": 25192,
"s": 25080,
"text": "Step 4: After installing xcaddy now we need to install the Caddy webserver. For that follow the below commands"
},
{
"code": null,
"e": 25384,
"s": 25192,
"text": "mkdir ~/caddyserver\ncd ~/caddyserver\n\n// for only caddy build\nxcaddy build\n\n// for building caddy with some plugins\nxcaddy build --with=github.com/caddy-dns/cloudflare\n\nsudo mv caddy /usr/bin"
},
{
"code": null,
"e": 25528,
"s": 25384,
"text": "To check whether caddy is installed successfully or not you can use the below command, if it prints out the version of caddy then its installed"
},
{
"code": null,
"e": 25607,
"s": 25528,
"text": "caddy version\n\n//output\nv2.4.2 h1:chB106RlsIaY4mVEyq9OQM5g/9lHYVputo/LAX2ndFg="
},
{
"code": null,
"e": 25634,
"s": 25607,
"text": "Caddy Web server installed"
},
{
"code": null,
"e": 25729,
"s": 25634,
"text": "Step 5: Configure a systemd service so that Caddy can be launched automatically on system boot"
},
{
"code": null,
"e": 25912,
"s": 25729,
"text": "sudo groupadd --system caddy\nsudo useradd --system --gid caddy --create-home --home-dir /var/lib/caddy --shell /usr/sbin/nologin --comment \"Caddy web server | learned from GFG\" caddy"
},
{
"code": null,
"e": 25939,
"s": 25912,
"text": "Added user and group caddy"
},
{
"code": null,
"e": 26295,
"s": 25939,
"text": "As caddy requires its own group and user to run the systemd process, the first command creates a new group caddy(you can give your own name, but it will be useful to identify in case of troubleshooting) and the second command creates user again named caddy and assigns it to caddy group. nologin command says that you can’t login into shell as caddy user."
},
{
"code": null,
"e": 26367,
"s": 26295,
"text": "Step 6: Create a caddy service file and add required permissions to it."
},
{
"code": null,
"e": 26411,
"s": 26367,
"text": "sudo nano /etc/systemd/system/caddy.service"
},
{
"code": null,
"e": 26487,
"s": 26411,
"text": "Copy and paste the below prebuilt system service file from Caddy repository"
},
{
"code": null,
"e": 27509,
"s": 26487,
"text": "# caddy.service\n#\n# For using Caddy with a config file.\n#\n# Make sure the ExecStart and ExecReload commands are correct\n# for your installation.\n#\n# See https://caddyserver.com/docs/install for instructions.\n#\n# WARNING: This service does not use the --resume flag, so if you\n# use the API to make changes, they will be overwritten by the\n# Caddyfile next time the service is restarted. If you intend to\n# use Caddy's API to configure it, add the --resume flag to the\n# `caddy run` command or use the caddy-api.service file instead.\n\n[Unit]\nDescription=Caddy\nDocumentation=https://caddyserver.com/docs/\nAfter=network.target network-online.target\nRequires=network-online.target\n\n[Service]\nType=notify\nUser=caddy\nGroup=caddy\nExecStart=/usr/bin/caddy run --environ --config /etc/caddy/Caddyfile\nExecReload=/usr/bin/caddy reload --config /etc/caddy/Caddyfile\nTimeoutStopSec=5s\nLimitNOFILE=1048576\nLimitNPROC=512\nPrivateTmp=true\nProtectSystem=full\nAmbientCapabilities=CAP_NET_BIND_SERVICE\n\n[Install]\nWantedBy=multi-user.target"
},
{
"code": null,
"e": 27525,
"s": 27509,
"text": "systemd service"
},
{
"code": null,
"e": 27584,
"s": 27525,
"text": "Assign permission so that only the root user can modify it"
},
{
"code": null,
"e": 27633,
"s": 27584,
"text": "sudo chmod 644 /etc/systemd/system/caddy.service"
},
{
"code": null,
"e": 27704,
"s": 27633,
"text": "Step 7: Now we need to set directory permissions to caddy directories "
},
{
"code": null,
"e": 28520,
"s": 27704,
"text": "// 755 permission gives root user rwx but others only rx for caddy binary\nsudo chmod 755 /usr/bin/caddy\n\n// creating caddy configuration folder\nsudo mkdir /etc/caddy\n\n// creating caddy config file\nsudo touch /etc/caddy/Caddyfile\n\n//giving ownership of caddy config folder to both root user and caddy group\nsudo chown -R root:caddy /etc/caddy\n\n// creating ssl folder for caddy to store the fetched ssl certificates\nsudo mkdir /etc/ssl/caddy\n\n//giving ownership of caddy config folder to both root user and caddy group\nsudo chown -R root:caddy /etc/ssl/caddy\n\n// 770 ensures that caddy can write to the folder and it can't be executed\nsudo chmod 0770 /etc/ssl/caddy\n\n// create and assign ownership of website contents to caddy uper and group\nsudo mkdir /var/www/public_html\nsudo chown caddy:caddy /var/www/public_html"
},
{
"code": null,
"e": 28540,
"s": 28520,
"text": "Setting permissions"
},
{
"code": null,
"e": 28631,
"s": 28540,
"text": "Step 8: Create a simple index.html file int public_html folder we created in previous step"
},
{
"code": null,
"e": 28673,
"s": 28631,
"text": "sudo nano /var/www/public_html/index.html"
},
{
"code": null,
"e": 29455,
"s": 28673,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />\n <meta name=\"viewport\"content=\"width=device-width,initial-scale=1.0\">\n <link href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\"rel=\"stylesheet\"integrity=\"sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl\"crossorigin=\"anonymous\">\n <title>Host Static website using Caddy web server</title>\n</head>\n<body class=\"text-center\">\n <div class=\"jumbotron text-center\">\n <h1>Welcome to GeeksForGeeks</h1>\n <h2 class=\"h2 card-title\">This article explains how to host static websites using caddy webserver</h2>\n <h6 class=\"h6 card-text\">Thank You for Reading</h6>\n </div>\n</body>\n</html>"
},
{
"code": null,
"e": 29466,
"s": 29455,
"text": "index.html"
},
{
"code": null,
"e": 29556,
"s": 29466,
"text": "Step 9: Configuring Caddy for this you need to edit the config file we created in step 7."
},
{
"code": null,
"e": 29587,
"s": 29556,
"text": "sudo nano /etc/caddy/Caddyfile"
},
{
"code": null,
"e": 29624,
"s": 29587,
"text": "Below is a sample caddy config file."
},
{
"code": null,
"e": 30363,
"s": 29624,
"text": "example.com {\n tls {\n email [email protected]\n }\n root * /var/www/public_html\n encode gzip\n file_server\n header / {\n Content-Security-Policy = \"upgrade-insecure-requests; default-src 'self'; style-src 'self'; script-src 'self'; img-src 'self'; object-src 'self'; worker-src 'self'; manifest-src 'self';\"\n Strict-Transport-Security = \"max-age=63072000; includeSubDomains; preload\"\n X-Xss-Protection = \"1; mode=block\"\n X-Frame-Options = \"DENY\"\n X-Content-Type-Options = \"nosniff\"\n Referrer-Policy = \"strict-origin-when-cross-origin\"\n Permissions-Policy = \"fullscreen=(self)\"\n cache-control = \"max-age=0,no-cache,no-store,must-revalidate\"\n }\n}"
},
{
"code": null,
"e": 30501,
"s": 30363,
"text": "First line tells the caddy the domain name(example.com) that block of configuration belongs to. It’s also used to fetch SSL certificates."
},
{
"code": null,
"e": 30679,
"s": 30501,
"text": "The TLS block helps us to configure SSL for the domain, for this specific file configuration email the hostname for any issuance and errors in the SSL fetching and configuration"
},
{
"code": null,
"e": 30733,
"s": 30679,
"text": "Root tells the root directory of the website contents"
},
{
"code": null,
"e": 30757,
"s": 30733,
"text": "Encoding of the content"
},
{
"code": null,
"e": 30803,
"s": 30757,
"text": "File_server helps caddy to serve static files"
},
{
"code": null,
"e": 30981,
"s": 30803,
"text": "Header block tells caddy to send these headers along with the response, the specific config tells caddy to serve CSP, XSS, HSTS and cache control headers along with the response"
},
{
"code": null,
"e": 30991,
"s": 30981,
"text": "Caddyfile"
},
{
"code": null,
"e": 31039,
"s": 30991,
"text": "Step 10: Now run caddy using the below commands"
},
{
"code": null,
"e": 31258,
"s": 31039,
"text": "// reloading daemon to apply caddy system service file\nsudo systemctl daemon-reload\n\n// starting caddy\nsudo systemctl start caddy\n\n//activating caddy system file\nsudo systemctl enable caddy\nsudo systemctl restart caddy"
},
{
"code": null,
"e": 31292,
"s": 31258,
"text": "Caddy server running successfully"
},
{
"code": null,
"e": 31343,
"s": 31292,
"text": "Now visit your website from your favorite browser:"
},
{
"code": null,
"e": 31362,
"s": 31343,
"text": "Running in browser"
},
{
"code": null,
"e": 31388,
"s": 31362,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 31395,
"s": 31388,
"text": "How To"
},
{
"code": null,
"e": 31406,
"s": 31395,
"text": "Linux-Unix"
},
{
"code": null,
"e": 31415,
"s": 31406,
"text": "TechTips"
},
{
"code": null,
"e": 31513,
"s": 31415,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31522,
"s": 31513,
"text": "Comments"
},
{
"code": null,
"e": 31535,
"s": 31522,
"text": "Old Comments"
},
{
"code": null,
"e": 31579,
"s": 31535,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 31620,
"s": 31579,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 31638,
"s": 31620,
"text": "OpenCV - Overview"
},
{
"code": null,
"e": 31680,
"s": 31638,
"text": "Mounting a Volume Inside Docker Container"
},
{
"code": null,
"e": 31707,
"s": 31680,
"text": "Fuzzy Logic | Introduction"
},
{
"code": null,
"e": 31739,
"s": 31707,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 31792,
"s": 31739,
"text": "How to Find the Wi-Fi Password Using CMD in Windows?"
},
{
"code": null,
"e": 31836,
"s": 31792,
"text": "How to install Jupyter Notebook on Windows?"
},
{
"code": null,
"e": 31863,
"s": 31836,
"text": "How to Align Text in HTML?"
}
]
|
How to get the size of PyGame Window? - GeeksforGeeks | 02 Jun, 2021
In this article, we will learn How to get the size of a PyGame Window.
Game programming is very rewarding nowadays and it can also be used in advertising and as a teaching tool too. Game development includes mathematics, logic, physics, AI, and much more and it can be amazingly fun. In python, game programming is done in pygame and it is one of the best modules for doing so.
Installation:
This library can be installed using the below command:
pip install pygame
Step-by-step Approach:
Import pygame.Initialize pygame.Form a screen by using pygame.display.set_mode() method.Get size of formed screen by using screen.get_size() method.Quit pygame.
Import pygame.
Initialize pygame.
Form a screen by using pygame.display.set_mode() method.
Get size of formed screen by using screen.get_size() method.
Quit pygame.
Below are some examples based on the above approach:
Example 1:
Python3
# import package pygameimport pygame # initialize pygamepygame.init() # Form screenscreen = pygame.display.set_mode() # get the default sizex, y = screen.get_size() # quit pygamepygame.display.quit() # view size (width x height)print(x, y)
Output :
1536 864
Example 2:
Python3
# import package pygameimport pygame # initialize pygamepygame.init() # Form screenscreen = pygame.display.set_mode((500, 500)) # get the sizex, y = screen.get_size() # quit pygamepygame.display.quit() # view size (width x height)print(x, y)
Output :
500 500
arorakashish0911
Picked
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 ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n02 Jun, 2021"
},
{
"code": null,
"e": 24364,
"s": 24292,
"text": "In this article, we will learn How to get the size of a PyGame Window. "
},
{
"code": null,
"e": 24671,
"s": 24364,
"text": "Game programming is very rewarding nowadays and it can also be used in advertising and as a teaching tool too. Game development includes mathematics, logic, physics, AI, and much more and it can be amazingly fun. In python, game programming is done in pygame and it is one of the best modules for doing so."
},
{
"code": null,
"e": 24685,
"s": 24671,
"text": "Installation:"
},
{
"code": null,
"e": 24740,
"s": 24685,
"text": "This library can be installed using the below command:"
},
{
"code": null,
"e": 24760,
"s": 24740,
"text": "pip install pygame "
},
{
"code": null,
"e": 24783,
"s": 24760,
"text": "Step-by-step Approach:"
},
{
"code": null,
"e": 24944,
"s": 24783,
"text": "Import pygame.Initialize pygame.Form a screen by using pygame.display.set_mode() method.Get size of formed screen by using screen.get_size() method.Quit pygame."
},
{
"code": null,
"e": 24959,
"s": 24944,
"text": "Import pygame."
},
{
"code": null,
"e": 24978,
"s": 24959,
"text": "Initialize pygame."
},
{
"code": null,
"e": 25035,
"s": 24978,
"text": "Form a screen by using pygame.display.set_mode() method."
},
{
"code": null,
"e": 25096,
"s": 25035,
"text": "Get size of formed screen by using screen.get_size() method."
},
{
"code": null,
"e": 25109,
"s": 25096,
"text": "Quit pygame."
},
{
"code": null,
"e": 25162,
"s": 25109,
"text": "Below are some examples based on the above approach:"
},
{
"code": null,
"e": 25173,
"s": 25162,
"text": "Example 1:"
},
{
"code": null,
"e": 25181,
"s": 25173,
"text": "Python3"
},
{
"code": "# import package pygameimport pygame # initialize pygamepygame.init() # Form screenscreen = pygame.display.set_mode() # get the default sizex, y = screen.get_size() # quit pygamepygame.display.quit() # view size (width x height)print(x, y)",
"e": 25421,
"s": 25181,
"text": null
},
{
"code": null,
"e": 25430,
"s": 25421,
"text": "Output :"
},
{
"code": null,
"e": 25439,
"s": 25430,
"text": "1536 864"
},
{
"code": null,
"e": 25450,
"s": 25439,
"text": "Example 2:"
},
{
"code": null,
"e": 25458,
"s": 25450,
"text": "Python3"
},
{
"code": "# import package pygameimport pygame # initialize pygamepygame.init() # Form screenscreen = pygame.display.set_mode((500, 500)) # get the sizex, y = screen.get_size() # quit pygamepygame.display.quit() # view size (width x height)print(x, y)",
"e": 25700,
"s": 25458,
"text": null
},
{
"code": null,
"e": 25709,
"s": 25700,
"text": "Output :"
},
{
"code": null,
"e": 25717,
"s": 25709,
"text": "500 500"
},
{
"code": null,
"e": 25734,
"s": 25717,
"text": "arorakashish0911"
},
{
"code": null,
"e": 25741,
"s": 25734,
"text": "Picked"
},
{
"code": null,
"e": 25755,
"s": 25741,
"text": "Python-PyGame"
},
{
"code": null,
"e": 25762,
"s": 25755,
"text": "Python"
},
{
"code": null,
"e": 25860,
"s": 25762,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25892,
"s": 25860,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25948,
"s": 25892,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25990,
"s": 25948,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26032,
"s": 25990,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26054,
"s": 26032,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26093,
"s": 26054,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26124,
"s": 26093,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26179,
"s": 26124,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26208,
"s": 26179,
"text": "Create a directory in Python"
}
]
|
Check if a number is magic (Recursive sum of digits is 1) - GeeksforGeeks | 14 Jul, 2021
A number is said to be a magic number, if the sum of its digits are calculated till a single digit recursively by adding the sum of the digits after every addition. If the single digit comes out to be 1,then the number is a magic number.
For example- Number= 50113 => 5+0+1+1+3=10 => 1+0=1 This is a Magic Number
For example- Number= 1234 => 1+2+3+4=10 => 1+0=1 This is a Magic Number
Examples :
Input : 1234
Output : Magic Number
Input : 12345
Output : Not a magic Number
The approach used brute force. The function keeps adding digits until a single digit sum is reached. To understand how i am calculating the sum upto a single digit view this page- Finding sum of digits of a number until sum becomes single digit
C++
Java
Python3
C#
PHP
Javascript
// CPP program to check if a number is Magic// number.#include<iostream>using namespace std; bool isMagic(int n){ int sum = 0; // Note that the loop continues // if n is 0 and sum is non-zero. // It stops when n becomes 0 and // sum becomes single digit. while (n > 0 || sum > 9) { if (n == 0) { n = sum; sum = 0; } sum += n % 10; n /= 10; } // Return true if sum becomes 1. return (sum == 1);} // Driver codeint main(){ int n = 1234; if (isMagic(n)) cout << "Magic Number"; else cout << "Not a magic Number"; return 0;}
// Java program to check if// a number is Magic number.class GFG{ public static boolean isMagic(int n) { int sum = 0; // Note that the loop continues // if n is 0 and sum is non-zero. // It stops when n becomes 0 and // sum becomes single digit. while (n > 0 || sum > 9) { if (n == 0) { n = sum; sum = 0; } sum += n % 10; n /= 10; } // Return true if sum becomes 1. return (sum == 1); } // Driver code public static void main(String args[]) { int n = 1234; if (isMagic(n)) System.out.println("Magic Number"); else System.out.println("Not a magic Number"); }} // This code is contributed by Anshika Goyal.
# Python3 program to check# if a number is Magic# number. def isMagic(n): sum = 0; # Note that the loop # continues if n is 0 # and sum is non-zero. # It stops when n becomes # 0 and sum becomes single # digit. while (n > 0 or sum > 9): if (n == 0): n = sum; sum = 0; sum = sum + n % 10; n = int(n / 10); # Return true if # sum becomes 1. return True if (sum == 1) else False; # Driver coden = 1234;if (isMagic(n)): print("Magic Number");else: print("Not a magic Number"); # This code is contributed# by mits.
// C# program to check if// a number is Magic number.using System; class GFG{ public static bool isMagic(int n) { int sum = 0; // Note that the loop continues // if n is 0 and sum is non-zero. // It stops when n becomes 0 and // sum becomes single digit. while (n > 0 || sum > 9) { if (n == 0) { n = sum; sum = 0; } sum += n % 10; n /= 10; } // Return true if sum becomes 1. return (sum == 1); } // Driver code public static void Main() { int n = 1234; if (isMagic(n)) Console.WriteLine("Magic Number"); else Console.WriteLine("Not a magic Number"); }} // This code is contributed by vt_m.
<?php// PHP program to check if// a number is Magic number.function isMagic($n){ $sum = 0; // Note that the loop // continues if n is 0 // and sum is non-zero. // It stops when n becomes // 0 and sum becomes single // digit. while ($n > 0 || $sum > 9) { if ($n == 0) { $n = $sum; $sum = 0; } $sum += $n % 10; $n /= 10; } // Return true if // sum becomes 1. return ($sum == 1);} // Driver code$n = 1234;if (isMagic($n)) echo"Magic Number";else echo "Not a magic Number"; // This code is contributed// by nitin mittal.?>
<script> // JavaScript program to check if// a number is Magic number.function isMagic( n) { var sum = 0; // Note that the loop continues // if n is 0 and sum is non-zero. // It stops when n becomes 0 and // sum becomes single digit. while (n > 0 || sum > 9) { if (n = 0) { n = sum; sum = 0; } sum += n % 10; n /= 10; } // Return true if sum becomes 1. return (sum = 1); } // Driver code var n = 1234; if (isMagic(n)) document.write("Magic Number"); else document.write("Not a magic Number"); // This code is contributed by shivanisinghss2110 </script>
Magic Number
Efficient Approach(Shortcut): There is also a shortcut method to verify Magic Number. The function will determine if the remainder on dividing the input by 9 is 1 or not. If it is 1, then the number is a magic number. The divisibility rule of 9 says that a number is divisible by 9 if the sum of its digits are also divisible by 9. Therefore, if a number is divisible by 9, then, recursively, all the digit sums are also divisible by 9. The final digit sum is always 9. An increase of 1 in the original number will increase the ultimate value by 1, making it 10 and the ultimate sum will be 1, thus verifying that it is a magic number.
C++
C
Java
Python3
C#
Javascript
// C++ program to check// Whether the number is Magic or not.#include <iostream>using namespace std; int main() { // Accepting sample input int x = 1234; // Condition to check Magic number if(x%9==1) cout << ("Magic Number"); else cout << ("Not a Magic Number"); return 0;}
// C program to check// Whether the number is Magic or not.#include <stdio.h> int main() { // Accepting sample input int x = 1234; // Condition to check Magic number if(x%9==1) printf("Magic Number"); else printf("Not a Magic Number"); return 0;}
// Java program to check// Whether the number is Magic or not.class GFG{ public static void main(String[] args){ // Accepting sample input int x = 1234; // Condition to check Magic number if (x % 9 == 1) System.out.printf("Magic Number"); else System.out.printf("Not a Magic Number");}} // This code is contributed by Amit Katiyar
# Python3 program to check# Whether the number is Magic or not. # Accepting sample inputx = 1234 # Condition to check Magic numberif (x % 9 == 1): print("Magic Number")else: print("Not a Magic Number") # This code is contributed by kirti
// C# program to check// Whether the number is Magic or not.using System;using System.Collections.Generic; class GFG{ public static void Main(String[] args){ // Accepting sample input int x = 1234; // Condition to check Magic number if (x % 9 == 1) Console.Write("Magic Number"); else Console.Write("Not a Magic Number");}} // This code is contributed by Princi Singh
<script> // JavaScript program to check// Whether the number is Magic or not. // Accepting sample inputvar x = 1234; // Condition to check Magic numberif (x % 9 == 1) document.write("Magic Number");else document.write("Not a Magic Number"); // This code is contributed by shivanisinghss2110 </script>
Magic Number
This article is contributed by Ayush Saxena. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
Mithun Kumar
imgrer44
amit143katiyar
Kirti_Mangal
princi singh
shivanisinghss2110
series
Mathematical
School Programming
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program for Decimal to Binary Conversion
Find all factors of a natural number | Set 1
Python Dictionary
Arrays in C/C++
Reverse a string in Java
Inheritance in C++
Constructors in C++ | [
{
"code": null,
"e": 24392,
"s": 24364,
"text": "\n14 Jul, 2021"
},
{
"code": null,
"e": 24631,
"s": 24392,
"text": "A number is said to be a magic number, if the sum of its digits are calculated till a single digit recursively by adding the sum of the digits after every addition. If the single digit comes out to be 1,then the number is a magic number. "
},
{
"code": null,
"e": 24707,
"s": 24631,
"text": "For example- Number= 50113 => 5+0+1+1+3=10 => 1+0=1 This is a Magic Number "
},
{
"code": null,
"e": 24779,
"s": 24707,
"text": "For example- Number= 1234 => 1+2+3+4=10 => 1+0=1 This is a Magic Number"
},
{
"code": null,
"e": 24791,
"s": 24779,
"text": "Examples : "
},
{
"code": null,
"e": 24871,
"s": 24791,
"text": " Input : 1234\nOutput : Magic Number\n\nInput : 12345\nOutput : Not a magic Number"
},
{
"code": null,
"e": 25116,
"s": 24871,
"text": "The approach used brute force. The function keeps adding digits until a single digit sum is reached. To understand how i am calculating the sum upto a single digit view this page- Finding sum of digits of a number until sum becomes single digit"
},
{
"code": null,
"e": 25120,
"s": 25116,
"text": "C++"
},
{
"code": null,
"e": 25125,
"s": 25120,
"text": "Java"
},
{
"code": null,
"e": 25133,
"s": 25125,
"text": "Python3"
},
{
"code": null,
"e": 25136,
"s": 25133,
"text": "C#"
},
{
"code": null,
"e": 25140,
"s": 25136,
"text": "PHP"
},
{
"code": null,
"e": 25151,
"s": 25140,
"text": "Javascript"
},
{
"code": "// CPP program to check if a number is Magic// number.#include<iostream>using namespace std; bool isMagic(int n){ int sum = 0; // Note that the loop continues // if n is 0 and sum is non-zero. // It stops when n becomes 0 and // sum becomes single digit. while (n > 0 || sum > 9) { if (n == 0) { n = sum; sum = 0; } sum += n % 10; n /= 10; } // Return true if sum becomes 1. return (sum == 1);} // Driver codeint main(){ int n = 1234; if (isMagic(n)) cout << \"Magic Number\"; else cout << \"Not a magic Number\"; return 0;}",
"e": 25796,
"s": 25151,
"text": null
},
{
"code": "// Java program to check if// a number is Magic number.class GFG{ public static boolean isMagic(int n) { int sum = 0; // Note that the loop continues // if n is 0 and sum is non-zero. // It stops when n becomes 0 and // sum becomes single digit. while (n > 0 || sum > 9) { if (n == 0) { n = sum; sum = 0; } sum += n % 10; n /= 10; } // Return true if sum becomes 1. return (sum == 1); } // Driver code public static void main(String args[]) { int n = 1234; if (isMagic(n)) System.out.println(\"Magic Number\"); else System.out.println(\"Not a magic Number\"); }} // This code is contributed by Anshika Goyal.",
"e": 26606,
"s": 25796,
"text": null
},
{
"code": "# Python3 program to check# if a number is Magic# number. def isMagic(n): sum = 0; # Note that the loop # continues if n is 0 # and sum is non-zero. # It stops when n becomes # 0 and sum becomes single # digit. while (n > 0 or sum > 9): if (n == 0): n = sum; sum = 0; sum = sum + n % 10; n = int(n / 10); # Return true if # sum becomes 1. return True if (sum == 1) else False; # Driver coden = 1234;if (isMagic(n)): print(\"Magic Number\");else: print(\"Not a magic Number\"); # This code is contributed# by mits.",
"e": 27216,
"s": 26606,
"text": null
},
{
"code": "// C# program to check if// a number is Magic number.using System; class GFG{ public static bool isMagic(int n) { int sum = 0; // Note that the loop continues // if n is 0 and sum is non-zero. // It stops when n becomes 0 and // sum becomes single digit. while (n > 0 || sum > 9) { if (n == 0) { n = sum; sum = 0; } sum += n % 10; n /= 10; } // Return true if sum becomes 1. return (sum == 1); } // Driver code public static void Main() { int n = 1234; if (isMagic(n)) Console.WriteLine(\"Magic Number\"); else Console.WriteLine(\"Not a magic Number\"); }} // This code is contributed by vt_m.",
"e": 28061,
"s": 27216,
"text": null
},
{
"code": "<?php// PHP program to check if// a number is Magic number.function isMagic($n){ $sum = 0; // Note that the loop // continues if n is 0 // and sum is non-zero. // It stops when n becomes // 0 and sum becomes single // digit. while ($n > 0 || $sum > 9) { if ($n == 0) { $n = $sum; $sum = 0; } $sum += $n % 10; $n /= 10; } // Return true if // sum becomes 1. return ($sum == 1);} // Driver code$n = 1234;if (isMagic($n)) echo\"Magic Number\";else echo \"Not a magic Number\"; // This code is contributed// by nitin mittal.?>",
"e": 28692,
"s": 28061,
"text": null
},
{
"code": "<script> // JavaScript program to check if// a number is Magic number.function isMagic( n) { var sum = 0; // Note that the loop continues // if n is 0 and sum is non-zero. // It stops when n becomes 0 and // sum becomes single digit. while (n > 0 || sum > 9) { if (n = 0) { n = sum; sum = 0; } sum += n % 10; n /= 10; } // Return true if sum becomes 1. return (sum = 1); } // Driver code var n = 1234; if (isMagic(n)) document.write(\"Magic Number\"); else document.write(\"Not a magic Number\"); // This code is contributed by shivanisinghss2110 </script>",
"e": 29437,
"s": 28692,
"text": null
},
{
"code": null,
"e": 29450,
"s": 29437,
"text": "Magic Number"
},
{
"code": null,
"e": 30089,
"s": 29452,
"text": "Efficient Approach(Shortcut): There is also a shortcut method to verify Magic Number. The function will determine if the remainder on dividing the input by 9 is 1 or not. If it is 1, then the number is a magic number. The divisibility rule of 9 says that a number is divisible by 9 if the sum of its digits are also divisible by 9. Therefore, if a number is divisible by 9, then, recursively, all the digit sums are also divisible by 9. The final digit sum is always 9. An increase of 1 in the original number will increase the ultimate value by 1, making it 10 and the ultimate sum will be 1, thus verifying that it is a magic number. "
},
{
"code": null,
"e": 30093,
"s": 30089,
"text": "C++"
},
{
"code": null,
"e": 30095,
"s": 30093,
"text": "C"
},
{
"code": null,
"e": 30100,
"s": 30095,
"text": "Java"
},
{
"code": null,
"e": 30108,
"s": 30100,
"text": "Python3"
},
{
"code": null,
"e": 30111,
"s": 30108,
"text": "C#"
},
{
"code": null,
"e": 30122,
"s": 30111,
"text": "Javascript"
},
{
"code": "// C++ program to check// Whether the number is Magic or not.#include <iostream>using namespace std; int main() { // Accepting sample input int x = 1234; // Condition to check Magic number if(x%9==1) cout << (\"Magic Number\"); else cout << (\"Not a Magic Number\"); return 0;}",
"e": 30438,
"s": 30122,
"text": null
},
{
"code": "// C program to check// Whether the number is Magic or not.#include <stdio.h> int main() { // Accepting sample input int x = 1234; // Condition to check Magic number if(x%9==1) printf(\"Magic Number\"); else printf(\"Not a Magic Number\"); return 0;}",
"e": 30734,
"s": 30438,
"text": null
},
{
"code": "// Java program to check// Whether the number is Magic or not.class GFG{ public static void main(String[] args){ // Accepting sample input int x = 1234; // Condition to check Magic number if (x % 9 == 1) System.out.printf(\"Magic Number\"); else System.out.printf(\"Not a Magic Number\");}} // This code is contributed by Amit Katiyar",
"e": 31104,
"s": 30734,
"text": null
},
{
"code": "# Python3 program to check# Whether the number is Magic or not. # Accepting sample inputx = 1234 # Condition to check Magic numberif (x % 9 == 1): print(\"Magic Number\")else: print(\"Not a Magic Number\") # This code is contributed by kirti",
"e": 31348,
"s": 31104,
"text": null
},
{
"code": "// C# program to check// Whether the number is Magic or not.using System;using System.Collections.Generic; class GFG{ public static void Main(String[] args){ // Accepting sample input int x = 1234; // Condition to check Magic number if (x % 9 == 1) Console.Write(\"Magic Number\"); else Console.Write(\"Not a Magic Number\");}} // This code is contributed by Princi Singh",
"e": 31755,
"s": 31348,
"text": null
},
{
"code": "<script> // JavaScript program to check// Whether the number is Magic or not. // Accepting sample inputvar x = 1234; // Condition to check Magic numberif (x % 9 == 1) document.write(\"Magic Number\");else document.write(\"Not a Magic Number\"); // This code is contributed by shivanisinghss2110 </script>",
"e": 32062,
"s": 31755,
"text": null
},
{
"code": null,
"e": 32075,
"s": 32062,
"text": "Magic Number"
},
{
"code": null,
"e": 32497,
"s": 32077,
"text": "This article is contributed by Ayush Saxena. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 32510,
"s": 32497,
"text": "nitin mittal"
},
{
"code": null,
"e": 32523,
"s": 32510,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 32532,
"s": 32523,
"text": "imgrer44"
},
{
"code": null,
"e": 32547,
"s": 32532,
"text": "amit143katiyar"
},
{
"code": null,
"e": 32560,
"s": 32547,
"text": "Kirti_Mangal"
},
{
"code": null,
"e": 32573,
"s": 32560,
"text": "princi singh"
},
{
"code": null,
"e": 32592,
"s": 32573,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 32599,
"s": 32592,
"text": "series"
},
{
"code": null,
"e": 32612,
"s": 32599,
"text": "Mathematical"
},
{
"code": null,
"e": 32631,
"s": 32612,
"text": "School Programming"
},
{
"code": null,
"e": 32644,
"s": 32631,
"text": "Mathematical"
},
{
"code": null,
"e": 32651,
"s": 32644,
"text": "series"
},
{
"code": null,
"e": 32749,
"s": 32651,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32758,
"s": 32749,
"text": "Comments"
},
{
"code": null,
"e": 32771,
"s": 32758,
"text": "Old Comments"
},
{
"code": null,
"e": 32795,
"s": 32771,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 32838,
"s": 32795,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 32852,
"s": 32838,
"text": "Prime Numbers"
},
{
"code": null,
"e": 32893,
"s": 32852,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 32938,
"s": 32893,
"text": "Find all factors of a natural number | Set 1"
},
{
"code": null,
"e": 32956,
"s": 32938,
"text": "Python Dictionary"
},
{
"code": null,
"e": 32972,
"s": 32956,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 32997,
"s": 32972,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 33016,
"s": 32997,
"text": "Inheritance in C++"
}
]
|
How to change file or directory permission in Linux/Unix? | We know that the Linux/Unix is a multiuser operating system files and directories are associated with permission so that only authorized users can access the files.
The chmod command is used to change the access permission of files or directories.
The general syntax of the chmod command is as follows −
chmod [OPTION]... [Mode]... [File]...
Syntax of chmod command is as followed, it contains some three parameters that will help to set or change the permission of the file.
We will discuss each parameter in detail so that you can have a better idea of using the chmod command.
A brief description of options available in the chmod command −
Mode can be represented in two different ways.
Numeric notation
Symbolic notation
In numeric notation, a three figures octal number (0-7) sequence is followed. Each digit holds Its own class. First digit for user Second digit for group and the last one is for others. If digits are out of range then it will be considered as zeros.
Symbolic notation is a combination of letters that specifies the permission. Some important letters are (u) for user (g) for group (o) for others and (a) for all the users.
Some arithmetic operators are used for certain permission.
“+” Plus, the operator will be used for adding the next permission to the existing one.
“- “Minus operator for removing.
“=” And equal means that it is the only permission is being used.
We can change the permission of a file and allow only the owner to read the file using the chmod command.
First, we will check permission of a file using the below command.
$ ls -l
Then we will change the permission of a file using the chmod command. We can provide permission numeric mode or symbolic mode.
Numeric notation –
$ chmod 400 file.txt
Or we can use the below command instead of numeric notation.
Symbolic notation –
$ chmod u + r hello.txt
As mentioned in the above tabular form, the option 200 allows the owner only to write into the file.
After executing the below command, only the owner of the file is allowed to modify it.
$ chmod 200 file.txt
To display more information about the chmod command, we use the --help option with the chmod command as shown below.
$ chmod --help | [
{
"code": null,
"e": 1227,
"s": 1062,
"text": "We know that the Linux/Unix is a multiuser operating system files and directories are associated with permission so that only authorized users can access the files."
},
{
"code": null,
"e": 1310,
"s": 1227,
"text": "The chmod command is used to change the access permission of files or directories."
},
{
"code": null,
"e": 1366,
"s": 1310,
"text": "The general syntax of the chmod command is as follows −"
},
{
"code": null,
"e": 1404,
"s": 1366,
"text": "chmod [OPTION]... [Mode]... [File]..."
},
{
"code": null,
"e": 1538,
"s": 1404,
"text": "Syntax of chmod command is as followed, it contains some three parameters that will help to set or change the permission of the file."
},
{
"code": null,
"e": 1642,
"s": 1538,
"text": "We will discuss each parameter in detail so that you can have a better idea of using the chmod command."
},
{
"code": null,
"e": 1706,
"s": 1642,
"text": "A brief description of options available in the chmod command −"
},
{
"code": null,
"e": 1753,
"s": 1706,
"text": "Mode can be represented in two different ways."
},
{
"code": null,
"e": 1770,
"s": 1753,
"text": "Numeric notation"
},
{
"code": null,
"e": 1788,
"s": 1770,
"text": "Symbolic notation"
},
{
"code": null,
"e": 2038,
"s": 1788,
"text": "In numeric notation, a three figures octal number (0-7) sequence is followed. Each digit holds Its own class. First digit for user Second digit for group and the last one is for others. If digits are out of range then it will be considered as zeros."
},
{
"code": null,
"e": 2211,
"s": 2038,
"text": "Symbolic notation is a combination of letters that specifies the permission. Some important letters are (u) for user (g) for group (o) for others and (a) for all the users."
},
{
"code": null,
"e": 2270,
"s": 2211,
"text": "Some arithmetic operators are used for certain permission."
},
{
"code": null,
"e": 2358,
"s": 2270,
"text": "“+” Plus, the operator will be used for adding the next permission to the existing one."
},
{
"code": null,
"e": 2391,
"s": 2358,
"text": "“- “Minus operator for removing."
},
{
"code": null,
"e": 2457,
"s": 2391,
"text": "“=” And equal means that it is the only permission is being used."
},
{
"code": null,
"e": 2563,
"s": 2457,
"text": "We can change the permission of a file and allow only the owner to read the file using the chmod command."
},
{
"code": null,
"e": 2630,
"s": 2563,
"text": "First, we will check permission of a file using the below command."
},
{
"code": null,
"e": 2638,
"s": 2630,
"text": "$ ls -l"
},
{
"code": null,
"e": 2765,
"s": 2638,
"text": "Then we will change the permission of a file using the chmod command. We can provide permission numeric mode or symbolic mode."
},
{
"code": null,
"e": 2784,
"s": 2765,
"text": "Numeric notation –"
},
{
"code": null,
"e": 2805,
"s": 2784,
"text": "$ chmod 400 file.txt"
},
{
"code": null,
"e": 2866,
"s": 2805,
"text": "Or we can use the below command instead of numeric notation."
},
{
"code": null,
"e": 2886,
"s": 2866,
"text": "Symbolic notation –"
},
{
"code": null,
"e": 2910,
"s": 2886,
"text": "$ chmod u + r hello.txt"
},
{
"code": null,
"e": 3011,
"s": 2910,
"text": "As mentioned in the above tabular form, the option 200 allows the owner only to write into the file."
},
{
"code": null,
"e": 3098,
"s": 3011,
"text": "After executing the below command, only the owner of the file is allowed to modify it."
},
{
"code": null,
"e": 3119,
"s": 3098,
"text": "$ chmod 200 file.txt"
},
{
"code": null,
"e": 3236,
"s": 3119,
"text": "To display more information about the chmod command, we use the --help option with the chmod command as shown below."
},
{
"code": null,
"e": 3251,
"s": 3236,
"text": "$ chmod --help"
}
]
|
How to style multi-line conditions in 'if' statements in Python? | There are many ways you can style multiple if conditions. You don't need to use 4 spaces on your second conditional line. So you can use something like &minusl;
if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
# Actual code
You can also start the conditions from the next line −
if (
cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'
):
# Actual code
Or you can provide enough space between if and ( to accomodate the conditions in the same vertical column.
if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
# Actual code
You can also do this without brackets, but note that PEP8 guidelines discourage this. For example,
if cond1 == 'val1' and cond2 == 'val2' and \
cond3 == 'val3' and cond4 == 'val4':
# Actual code | [
{
"code": null,
"e": 1223,
"s": 1062,
"text": "There are many ways you can style multiple if conditions. You don't need to use 4 spaces on your second conditional line. So you can use something like &minusl;"
},
{
"code": null,
"e": 1309,
"s": 1223,
"text": "if (cond1 == 'val1' and cond2 == 'val2' and\n cond3 == 'val3' and cond4 == 'val4'):"
},
{
"code": null,
"e": 1323,
"s": 1309,
"text": "# Actual code"
},
{
"code": null,
"e": 1378,
"s": 1323,
"text": "You can also start the conditions from the next line −"
},
{
"code": null,
"e": 1468,
"s": 1378,
"text": "if (\n cond1 == 'val1' and cond2 == 'val2' and\n cond3 == 'val3' and cond4 == 'val4'\n):"
},
{
"code": null,
"e": 1482,
"s": 1468,
"text": "# Actual code"
},
{
"code": null,
"e": 1589,
"s": 1482,
"text": "Or you can provide enough space between if and ( to accomodate the conditions in the same vertical column."
},
{
"code": null,
"e": 1675,
"s": 1589,
"text": "if (cond1 == 'val1' and cond2 == 'val2' and\n cond3 == 'val3' and cond4 == 'val4'):"
},
{
"code": null,
"e": 1689,
"s": 1675,
"text": "# Actual code"
},
{
"code": null,
"e": 1788,
"s": 1689,
"text": "You can also do this without brackets, but note that PEP8 guidelines discourage this. For example,"
},
{
"code": null,
"e": 1873,
"s": 1788,
"text": "if cond1 == 'val1' and cond2 == 'val2' and \\\n cond3 == 'val3' and cond4 == 'val4':"
},
{
"code": null,
"e": 1887,
"s": 1873,
"text": "# Actual code"
}
]
|
MySQL - SQRT Function | MySQL SQRT function is used to find out the square root of any number. You can use SELECT statement to find out square root of any number as follows −
mysql> select SQRT(16);
+----------+
| SQRT(16) |
+----------+
| 4.000000 |
+----------+
1 row in set (0.00 sec)
You are seeing float value here because internally MySQL will manipulate square root in float data type.
You can use SQRT function to find out square root of various records as well. To understand SQRT function in more detail, consider an employee_tbl table, which is having following records −
mysql> SELECT * FROM employee_tbl;
+------+------+------------+--------------------+
| id | name | work_date | daily_typing_pages |
+------+------+------------+--------------------+
| 1 | John | 2007-01-24 | 250 |
| 2 | Ram | 2007-05-27 | 220 |
| 3 | Jack | 2007-05-06 | 170 |
| 3 | Jack | 2007-04-06 | 100 |
| 4 | Jill | 2007-04-06 | 220 |
| 5 | Zara | 2007-06-06 | 300 |
| 5 | Zara | 2007-02-06 | 350 |
+------+------+------------+--------------------+
7 rows in set (0.00 sec)
Now, suppose based on the above table you want to calculate square root of all the dialy_typing_pages, then you can do so by using the following command −
mysql> SELECT name, SQRT(daily_typing_pages)
-> FROM employee_tbl;
+------+--------------------------+
| name | SQRT(daily_typing_pages) |
+------+--------------------------+
| John | 15.811388 |
| Ram | 14.832397 |
| Jack | 13.038405 |
| Jack | 10.000000 |
| Jill | 14.832397 |
| Zara | 17.320508 |
| Zara | 18.708287 |
+------+--------------------------+
7 rows in set (0.00 sec)
31 Lectures
6 hours
Eduonix Learning Solutions
84 Lectures
5.5 hours
Frahaan Hussain
6 Lectures
3.5 hours
DATAhill Solutions Srinivas Reddy
60 Lectures
10 hours
Vijay Kumar Parvatha Reddy
10 Lectures
1 hours
Harshit Srivastava
25 Lectures
4 hours
Trevoir Williams
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2484,
"s": 2333,
"text": "MySQL SQRT function is used to find out the square root of any number. You can use SELECT statement to find out square root of any number as follows −"
},
{
"code": null,
"e": 2598,
"s": 2484,
"text": "mysql> select SQRT(16);\n+----------+\n| SQRT(16) |\n+----------+\n| 4.000000 |\n+----------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 2703,
"s": 2598,
"text": "You are seeing float value here because internally MySQL will manipulate square root in float data type."
},
{
"code": null,
"e": 2893,
"s": 2703,
"text": "You can use SQRT function to find out square root of various records as well. To understand SQRT function in more detail, consider an employee_tbl table, which is having following records −"
},
{
"code": null,
"e": 3503,
"s": 2893,
"text": "mysql> SELECT * FROM employee_tbl;\n+------+------+------------+--------------------+\n| id | name | work_date | daily_typing_pages |\n+------+------+------------+--------------------+\n| 1 | John | 2007-01-24 | 250 |\n| 2 | Ram | 2007-05-27 | 220 |\n| 3 | Jack | 2007-05-06 | 170 |\n| 3 | Jack | 2007-04-06 | 100 |\n| 4 | Jill | 2007-04-06 | 220 |\n| 5 | Zara | 2007-06-06 | 300 |\n| 5 | Zara | 2007-02-06 | 350 |\n+------+------+------------+--------------------+\n7 rows in set (0.00 sec)"
},
{
"code": null,
"e": 3659,
"s": 3503,
"text": "Now, suppose based on the above table you want to calculate square root of all the dialy_typing_pages, then you can do so by using the following command −"
},
{
"code": null,
"e": 4150,
"s": 3659,
"text": "mysql> SELECT name, SQRT(daily_typing_pages)\n -> FROM employee_tbl;\n+------+--------------------------+\n| name | SQRT(daily_typing_pages) |\n+------+--------------------------+\n| John | 15.811388 |\n| Ram | 14.832397 |\n| Jack | 13.038405 |\n| Jack | 10.000000 |\n| Jill | 14.832397 |\n| Zara | 17.320508 |\n| Zara | 18.708287 |\n+------+--------------------------+\n7 rows in set (0.00 sec)"
},
{
"code": null,
"e": 4183,
"s": 4150,
"text": "\n 31 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4211,
"s": 4183,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4246,
"s": 4211,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4263,
"s": 4246,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4297,
"s": 4263,
"text": "\n 6 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4332,
"s": 4297,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 4366,
"s": 4332,
"text": "\n 60 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 4394,
"s": 4366,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 4427,
"s": 4394,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4447,
"s": 4427,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 4480,
"s": 4447,
"text": "\n 25 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4498,
"s": 4480,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 4505,
"s": 4498,
"text": " Print"
},
{
"code": null,
"e": 4516,
"s": 4505,
"text": " Add Notes"
}
]
|
Print all k-sum paths in a binary tree in C++ | In this problem, we are given a binary tree and a number K and we have to print all paths in the tree which have the sum of nodes in the path equal k.
Here, the path of the tree can start from any node of the tree and end at any node. The path should always direct from the root node to the leaf node. The values of the nodes of the tree can be positive, negative, or zero.
Let’s take an example to understand the problem −
K = 5
Output −
1 3 1
3 2
1 4
To solve this problem, we will treat each node as the root node of the tree and find the path from the temporary root to other nodes that sum values to K.
We store all nodes of the path in vector and check the sum value to be evaluated to k.
Program to show the implementation of the algorithm −
Live Demo
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *left,*right;
Node(int x){
data = x;
left = right = NULL;
}
};
void printPath(const vector<int>& v, int i) {
for (int j=i; j<v.size(); j++)
cout<<v[j]<<"\t";
cout<<"\n";
}
void findKSumPath(Node *root, vector<int>& path, int k) {
if (!root)
return;
path.push_back(root->data);
findKSumPath(root->left, path, k);
findKSumPath(root->right, path, k);
int f = 0;
for (int j=path.size()-1; j>=0; j--){
f += path[j];
if (f == k)
printPath(path, j);
}
path.pop_back();
}
int main() {
Node *root = new Node(1);
root->left = new Node(3);
root->left->left = new Node(1);
root->left->right = new Node(2);
root->right = new Node(4);
root->right->right = new Node(7);
int k = 5;
cout<<"Paths with sum "<<k<<" are :\n";
vector<int> path;
findKSumPath(root, path, k);
return 0;
}
Paths with sum 5 are −
1 3 1
3 2
1 4 | [
{
"code": null,
"e": 1213,
"s": 1062,
"text": "In this problem, we are given a binary tree and a number K and we have to print all paths in the tree which have the sum of nodes in the path equal k."
},
{
"code": null,
"e": 1436,
"s": 1213,
"text": "Here, the path of the tree can start from any node of the tree and end at any node. The path should always direct from the root node to the leaf node. The values of the nodes of the tree can be positive, negative, or zero."
},
{
"code": null,
"e": 1486,
"s": 1436,
"text": "Let’s take an example to understand the problem −"
},
{
"code": null,
"e": 1492,
"s": 1486,
"text": "K = 5"
},
{
"code": null,
"e": 1501,
"s": 1492,
"text": "Output −"
},
{
"code": null,
"e": 1515,
"s": 1501,
"text": "1 3 1\n3 2\n1 4"
},
{
"code": null,
"e": 1670,
"s": 1515,
"text": "To solve this problem, we will treat each node as the root node of the tree and find the path from the temporary root to other nodes that sum values to K."
},
{
"code": null,
"e": 1757,
"s": 1670,
"text": "We store all nodes of the path in vector and check the sum value to be evaluated to k."
},
{
"code": null,
"e": 1811,
"s": 1757,
"text": "Program to show the implementation of the algorithm −"
},
{
"code": null,
"e": 1822,
"s": 1811,
"text": " Live Demo"
},
{
"code": null,
"e": 2782,
"s": 1822,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nstruct Node {\n int data;\n Node *left,*right;\n Node(int x){\n data = x;\n left = right = NULL;\n }\n};\nvoid printPath(const vector<int>& v, int i) {\n for (int j=i; j<v.size(); j++)\n cout<<v[j]<<\"\\t\";\n cout<<\"\\n\";\n}\nvoid findKSumPath(Node *root, vector<int>& path, int k) {\n if (!root)\n return;\n path.push_back(root->data);\n findKSumPath(root->left, path, k);\n findKSumPath(root->right, path, k);\n int f = 0;\n for (int j=path.size()-1; j>=0; j--){\n f += path[j];\n if (f == k)\n printPath(path, j);\n }\n path.pop_back();\n}\nint main() {\n Node *root = new Node(1);\n root->left = new Node(3);\n root->left->left = new Node(1);\n root->left->right = new Node(2);\n root->right = new Node(4);\n root->right->right = new Node(7);\n int k = 5;\n cout<<\"Paths with sum \"<<k<<\" are :\\n\";\n vector<int> path;\n findKSumPath(root, path, k);\n return 0;\n}"
},
{
"code": null,
"e": 2819,
"s": 2782,
"text": "Paths with sum 5 are −\n1 3 1\n3 2\n1 4"
}
]
|
What is difference between gravity and layout_gravity on Android? | Android supports both gravity and layout_gravity. Gravity adjusts view position. Using gravity we can do alignment of view as shown below.
<TextView
android:id = "@+id/button"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:gravity = "center"
android:text = "Click here to hide"
/>
In the above code Textview going to set in middle of parent layout.
Center − it going to put view in center of parent layout.
Center − it going to put view in center of parent layout.
Right − it going to put view in right of parent layout.
Right − it going to put view in right of parent layout.
Left − it going to put view in left of parent layout.
Left − it going to put view in left of parent layout.
End − it going to put view in end position of parent layout.
End − it going to put view in end position of parent layout.
Start − it going to put view in start position of parent layout.
Start − it going to put view in start position of parent layout.
Top − It going to put view in Top position of parent layout.
Top − It going to put view in Top position of parent layout.
Bottom − it going to put view in Bottom position of parent layout.
Bottom − it going to put view in Bottom position of parent layout.
Center vertical − it going to put view in center vertical of parent layout. But it required MATCH_PARENT as Height for child view.
Center vertical − it going to put view in center vertical of parent layout. But it required MATCH_PARENT as Height for child view.
Center Horizontal − It going to put view in center horizontal of parent layout. But it required MATCH_PARENT as width for child view.
Center Horizontal − It going to put view in center horizontal of parent layout. But it required MATCH_PARENT as width for child view.
layout_gravity − Layout gravity same as gravity but it going to put view based on parent layout corners as shown below.
<EditText
android:id = "@+id/editext"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_gravity = "right">
</EditText>
In the above example we kept layout_gravity as right. It going to place at right side of parent view.
This example demonstrate about difference between gravity and layout_gravity.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
android:id = "@+id/rootview"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:orientation = "vertical"
tools:context = ".MainActivity">
<EditText
android:id = "@+id/editext"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_gravity = "right"></EditText>
<TextView
android:id = "@+id/button"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:gravity = "center"
android:text = "Click here to hide" />
</LinearLayout>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
In the above code we kept gravity as center for textview so it is placed at center of parent view and in edittext we kept layout gravity as right so it is placed at right side of parent view.
Click here to download the project code | [
{
"code": null,
"e": 1201,
"s": 1062,
"text": "Android supports both gravity and layout_gravity. Gravity adjusts view position. Using gravity we can do alignment of view as shown below."
},
{
"code": null,
"e": 1396,
"s": 1201,
"text": "<TextView\n android:id = \"@+id/button\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:gravity = \"center\"\n android:text = \"Click here to hide\"\n/>"
},
{
"code": null,
"e": 1464,
"s": 1396,
"text": "In the above code Textview going to set in middle of parent layout."
},
{
"code": null,
"e": 1522,
"s": 1464,
"text": "Center − it going to put view in center of parent layout."
},
{
"code": null,
"e": 1580,
"s": 1522,
"text": "Center − it going to put view in center of parent layout."
},
{
"code": null,
"e": 1636,
"s": 1580,
"text": "Right − it going to put view in right of parent layout."
},
{
"code": null,
"e": 1692,
"s": 1636,
"text": "Right − it going to put view in right of parent layout."
},
{
"code": null,
"e": 1746,
"s": 1692,
"text": "Left − it going to put view in left of parent layout."
},
{
"code": null,
"e": 1800,
"s": 1746,
"text": "Left − it going to put view in left of parent layout."
},
{
"code": null,
"e": 1861,
"s": 1800,
"text": "End − it going to put view in end position of parent layout."
},
{
"code": null,
"e": 1922,
"s": 1861,
"text": "End − it going to put view in end position of parent layout."
},
{
"code": null,
"e": 1987,
"s": 1922,
"text": "Start − it going to put view in start position of parent layout."
},
{
"code": null,
"e": 2052,
"s": 1987,
"text": "Start − it going to put view in start position of parent layout."
},
{
"code": null,
"e": 2113,
"s": 2052,
"text": "Top − It going to put view in Top position of parent layout."
},
{
"code": null,
"e": 2174,
"s": 2113,
"text": "Top − It going to put view in Top position of parent layout."
},
{
"code": null,
"e": 2241,
"s": 2174,
"text": "Bottom − it going to put view in Bottom position of parent layout."
},
{
"code": null,
"e": 2308,
"s": 2241,
"text": "Bottom − it going to put view in Bottom position of parent layout."
},
{
"code": null,
"e": 2439,
"s": 2308,
"text": "Center vertical − it going to put view in center vertical of parent layout. But it required MATCH_PARENT as Height for child view."
},
{
"code": null,
"e": 2570,
"s": 2439,
"text": "Center vertical − it going to put view in center vertical of parent layout. But it required MATCH_PARENT as Height for child view."
},
{
"code": null,
"e": 2704,
"s": 2570,
"text": "Center Horizontal − It going to put view in center horizontal of parent layout. But it required MATCH_PARENT as width for child view."
},
{
"code": null,
"e": 2838,
"s": 2704,
"text": "Center Horizontal − It going to put view in center horizontal of parent layout. But it required MATCH_PARENT as width for child view."
},
{
"code": null,
"e": 2958,
"s": 2838,
"text": "layout_gravity − Layout gravity same as gravity but it going to put view based on parent layout corners as shown below."
},
{
"code": null,
"e": 3131,
"s": 2958,
"text": "<EditText\n android:id = \"@+id/editext\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:layout_gravity = \"right\">\n</EditText>"
},
{
"code": null,
"e": 3233,
"s": 3131,
"text": "In the above example we kept layout_gravity as right. It going to place at right side of parent view."
},
{
"code": null,
"e": 3311,
"s": 3233,
"text": "This example demonstrate about difference between gravity and layout_gravity."
},
{
"code": null,
"e": 3440,
"s": 3311,
"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": 3505,
"s": 3440,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 4278,
"s": 3505,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:id = \"@+id/rootview\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:orientation = \"vertical\"\n tools:context = \".MainActivity\">\n <EditText\n android:id = \"@+id/editext\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:layout_gravity = \"right\"></EditText>\n <TextView\n android:id = \"@+id/button\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:gravity = \"center\"\n android:text = \"Click here to hide\" />\n</LinearLayout>"
},
{
"code": null,
"e": 4624,
"s": 4278,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen"
},
{
"code": null,
"e": 4816,
"s": 4624,
"text": "In the above code we kept gravity as center for textview so it is placed at center of parent view and in edittext we kept layout gravity as right so it is placed at right side of parent view."
},
{
"code": null,
"e": 4856,
"s": 4816,
"text": "Click here to download the project code"
}
]
|
How to Create Fake Data with Faker | by Khuyen Tran | Towards Data Science | Let’s say you want to create data with certain data types (bool, float, text, integers) with special characteristics (names, address, color, email, phone number, location) to test some Python libraries or specific implementation. But it takes time to find that specific kind of data. You wonder: is there a quick way that you can create your own data?
What if there is a package that enables you to create fake data in one line of code such as this:
fake.profile()
This can be done with Faker, a Python package that generates fake data for you, ranging from a specific data type to specific characteristics of that data, and the origin or language of the data. Let’s discover how we can use Faker to create fake data.
Start with installing the package
pip install Faker
Import Faker
from faker import Fakerfake = Faker()
Some basic methods of Faker:
>>> fake.color_name()'SeaGreen'>>> fake.name()'Vanessa Schroeder'>>> fake.address()'3138 Jennings Shore\nPort Anthony, MT 90833'>>> fake.job()'Buyer, industrial'>>> fake.date_of_birth(minimum_age=30)datetime.date(1906, 9, 18)>>> fake.city()'Rebeccastad'
Let’s say you are an author of a fiction book who want to create a character but find it difficult and time-consuming to come up with a realistic name and information. You can write
>>> name = fake.name()>>> color = fake.color_name()>>> city = fake.city()>>> job = fake.job()>>> print('Her name is {}. She lives in {}. Her favorite color is {}. She works as a {}'.format(name, city,color, job))
Outcome:
Her name is Natalie Gamble. She lives in East Tammyborough. Her favorite color is Magenta. She works as a Metallurgist
With Faker, you can generate a persuasive example instantly!
Luckily, we can also specify the location of the data we want to fake. Maybe the character you want to create is from Italy. You also want to create instances of her friends. Since you are from the US, it is difficult for you to generate relevant information to that location. That can be easily taken care of by adding location parameter in the class Faker
fake = Faker('it_IT')for _ in range(10): print(fake.name())
Outcome:
Lando Bertoli-Bulzoni Danilo Gianvecchio Dott. Margherita Veneziano Bianca Morabito Alfredo Rossetti Claudia Chechi Dott. Gastone Loredan Dott. Fulvio Russo Camilla Crisafulli-Gentileschi Agnolo Gioberti
Or create information from multiple locations
fake = Faker(['ja_JP','zh_CN','es_ES','en_US','fr_FR'])for _ in range(10): print(fake.city())
Outcome:
Ceuta Juanhaven 佳市 East Sarah 山武郡横芝光町 川崎市宮前区 Blondel-sur-Pottier West Christine Lake Amandahaven Weekshaven
If you are from these specific countries, I hope you recognize the location. In case you are curious about other locations that you can specify, check out the doc here.
We can create random text with
>>> fake.text()'Lay industry reach move candidate from local spring. Wind someone really but. One rock fund different down own.'
Try with the Japanese language
>>> fake = Faker('ja_JP')>>> fake.text()'普通の器官証言する仕上げ鉱山癌。カラム索引障害自体今ブラケット創傷。細かい見出し見出し目的自体持っていました。\nピックバケツリンク自体。職人サワーカラム人形自体。癌ブランチ普通のデフォルト同行ヘア不自然な。\nあった偏差〜偏差今特徴敵。バストスパン拡張助けて。\nスマッシュ彼女ボトル隠す品質隠すサンプル。ヘアパイオニアスマッシュ風景。\nパン発生する装置尊敬する。偏差省略自体。'
Or we can also create text from a list of words
fake = Faker()my_information = ['dog','swimming', '21', 'slow', 'girl', 'coffee', 'flower','pink']fake.sentence(ext_word_list=my_information)
First run:
'Girl slow slow girl flower flower girl.'
and second run
'Flower 21 flower coffee flower dog.'
We can quickly create a profile with:
fake = Faker()fake.profile()
As we can see, most relevant information about a person is created with ease, even with mail, ssn, username, and website.
What is even more useful is that we can create a dataframe of 100 users from different countries
import pandas as pdfake = Faker(['it_IT','ja_JP', 'zh_CN', 'de_DE','en_US'])profiles = [fake.profile() for i in range(100)]pd.DataFrame(profiles).head()
Or create a customized profile
If we just care about the type of your data, without caring so much about the information, we can easily generate random datatypes such as:
Boolean
>>> fake.pybool()False
A list of 5 elements with different data_type
>>> fake.pylist(nb_elements=5, variable_nb_elements=True)['TiZaWQDCzVIgSALOSKJD', 8100, 'hZTFGZpYVwJUcGZUoauG', Decimal('-3512.1951'), 37442800222.8852, 'XIxdbnwYMfOJDsZlaowZ']
A decimal with 5 left digits and 6 right digits (after the .)
>>> fake.pydecimal(left_digits=5, right_digits=6, positive=False, min_value=None, max_value=None)Decimal('92511.722977')
You can find more about other Python datatypes that you can create here
I hope you find Faker a helpful tool to create data efficiently. You may find this tool useful for what you are working on or may not at the moment. But it is helpful to know that there exists a tool that enables you to generate data with ease for your specific needs such as testing.
Feel free to fork and play with the code for this article in this Github repo or more information about Faker here.
I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter.
Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these: | [
{
"code": null,
"e": 523,
"s": 171,
"text": "Let’s say you want to create data with certain data types (bool, float, text, integers) with special characteristics (names, address, color, email, phone number, location) to test some Python libraries or specific implementation. But it takes time to find that specific kind of data. You wonder: is there a quick way that you can create your own data?"
},
{
"code": null,
"e": 621,
"s": 523,
"text": "What if there is a package that enables you to create fake data in one line of code such as this:"
},
{
"code": null,
"e": 636,
"s": 621,
"text": "fake.profile()"
},
{
"code": null,
"e": 889,
"s": 636,
"text": "This can be done with Faker, a Python package that generates fake data for you, ranging from a specific data type to specific characteristics of that data, and the origin or language of the data. Let’s discover how we can use Faker to create fake data."
},
{
"code": null,
"e": 923,
"s": 889,
"text": "Start with installing the package"
},
{
"code": null,
"e": 941,
"s": 923,
"text": "pip install Faker"
},
{
"code": null,
"e": 954,
"s": 941,
"text": "Import Faker"
},
{
"code": null,
"e": 992,
"s": 954,
"text": "from faker import Fakerfake = Faker()"
},
{
"code": null,
"e": 1021,
"s": 992,
"text": "Some basic methods of Faker:"
},
{
"code": null,
"e": 1275,
"s": 1021,
"text": ">>> fake.color_name()'SeaGreen'>>> fake.name()'Vanessa Schroeder'>>> fake.address()'3138 Jennings Shore\\nPort Anthony, MT 90833'>>> fake.job()'Buyer, industrial'>>> fake.date_of_birth(minimum_age=30)datetime.date(1906, 9, 18)>>> fake.city()'Rebeccastad'"
},
{
"code": null,
"e": 1457,
"s": 1275,
"text": "Let’s say you are an author of a fiction book who want to create a character but find it difficult and time-consuming to come up with a realistic name and information. You can write"
},
{
"code": null,
"e": 1670,
"s": 1457,
"text": ">>> name = fake.name()>>> color = fake.color_name()>>> city = fake.city()>>> job = fake.job()>>> print('Her name is {}. She lives in {}. Her favorite color is {}. She works as a {}'.format(name, city,color, job))"
},
{
"code": null,
"e": 1679,
"s": 1670,
"text": "Outcome:"
},
{
"code": null,
"e": 1798,
"s": 1679,
"text": "Her name is Natalie Gamble. She lives in East Tammyborough. Her favorite color is Magenta. She works as a Metallurgist"
},
{
"code": null,
"e": 1859,
"s": 1798,
"text": "With Faker, you can generate a persuasive example instantly!"
},
{
"code": null,
"e": 2217,
"s": 1859,
"text": "Luckily, we can also specify the location of the data we want to fake. Maybe the character you want to create is from Italy. You also want to create instances of her friends. Since you are from the US, it is difficult for you to generate relevant information to that location. That can be easily taken care of by adding location parameter in the class Faker"
},
{
"code": null,
"e": 2279,
"s": 2217,
"text": "fake = Faker('it_IT')for _ in range(10): print(fake.name())"
},
{
"code": null,
"e": 2288,
"s": 2279,
"text": "Outcome:"
},
{
"code": null,
"e": 2494,
"s": 2288,
"text": "Lando Bertoli-Bulzoni Danilo Gianvecchio Dott. Margherita Veneziano Bianca Morabito Alfredo Rossetti Claudia Chechi Dott. Gastone Loredan Dott. Fulvio Russo Camilla Crisafulli-Gentileschi Agnolo Gioberti"
},
{
"code": null,
"e": 2540,
"s": 2494,
"text": "Or create information from multiple locations"
},
{
"code": null,
"e": 2635,
"s": 2540,
"text": "fake = Faker(['ja_JP','zh_CN','es_ES','en_US','fr_FR'])for _ in range(10): print(fake.city())"
},
{
"code": null,
"e": 2644,
"s": 2635,
"text": "Outcome:"
},
{
"code": null,
"e": 2752,
"s": 2644,
"text": "Ceuta Juanhaven 佳市 East Sarah 山武郡横芝光町 川崎市宮前区 Blondel-sur-Pottier West Christine Lake Amandahaven Weekshaven"
},
{
"code": null,
"e": 2921,
"s": 2752,
"text": "If you are from these specific countries, I hope you recognize the location. In case you are curious about other locations that you can specify, check out the doc here."
},
{
"code": null,
"e": 2952,
"s": 2921,
"text": "We can create random text with"
},
{
"code": null,
"e": 3081,
"s": 2952,
"text": ">>> fake.text()'Lay industry reach move candidate from local spring. Wind someone really but. One rock fund different down own.'"
},
{
"code": null,
"e": 3112,
"s": 3081,
"text": "Try with the Japanese language"
},
{
"code": null,
"e": 3358,
"s": 3112,
"text": ">>> fake = Faker('ja_JP')>>> fake.text()'普通の器官証言する仕上げ鉱山癌。カラム索引障害自体今ブラケット創傷。細かい見出し見出し目的自体持っていました。\\nピックバケツリンク自体。職人サワーカラム人形自体。癌ブランチ普通のデフォルト同行ヘア不自然な。\\nあった偏差〜偏差今特徴敵。バストスパン拡張助けて。\\nスマッシュ彼女ボトル隠す品質隠すサンプル。ヘアパイオニアスマッシュ風景。\\nパン発生する装置尊敬する。偏差省略自体。'"
},
{
"code": null,
"e": 3406,
"s": 3358,
"text": "Or we can also create text from a list of words"
},
{
"code": null,
"e": 3548,
"s": 3406,
"text": "fake = Faker()my_information = ['dog','swimming', '21', 'slow', 'girl', 'coffee', 'flower','pink']fake.sentence(ext_word_list=my_information)"
},
{
"code": null,
"e": 3559,
"s": 3548,
"text": "First run:"
},
{
"code": null,
"e": 3601,
"s": 3559,
"text": "'Girl slow slow girl flower flower girl.'"
},
{
"code": null,
"e": 3616,
"s": 3601,
"text": "and second run"
},
{
"code": null,
"e": 3654,
"s": 3616,
"text": "'Flower 21 flower coffee flower dog.'"
},
{
"code": null,
"e": 3692,
"s": 3654,
"text": "We can quickly create a profile with:"
},
{
"code": null,
"e": 3721,
"s": 3692,
"text": "fake = Faker()fake.profile()"
},
{
"code": null,
"e": 3843,
"s": 3721,
"text": "As we can see, most relevant information about a person is created with ease, even with mail, ssn, username, and website."
},
{
"code": null,
"e": 3940,
"s": 3843,
"text": "What is even more useful is that we can create a dataframe of 100 users from different countries"
},
{
"code": null,
"e": 4093,
"s": 3940,
"text": "import pandas as pdfake = Faker(['it_IT','ja_JP', 'zh_CN', 'de_DE','en_US'])profiles = [fake.profile() for i in range(100)]pd.DataFrame(profiles).head()"
},
{
"code": null,
"e": 4124,
"s": 4093,
"text": "Or create a customized profile"
},
{
"code": null,
"e": 4264,
"s": 4124,
"text": "If we just care about the type of your data, without caring so much about the information, we can easily generate random datatypes such as:"
},
{
"code": null,
"e": 4272,
"s": 4264,
"text": "Boolean"
},
{
"code": null,
"e": 4295,
"s": 4272,
"text": ">>> fake.pybool()False"
},
{
"code": null,
"e": 4341,
"s": 4295,
"text": "A list of 5 elements with different data_type"
},
{
"code": null,
"e": 4523,
"s": 4341,
"text": ">>> fake.pylist(nb_elements=5, variable_nb_elements=True)['TiZaWQDCzVIgSALOSKJD', 8100, 'hZTFGZpYVwJUcGZUoauG', Decimal('-3512.1951'), 37442800222.8852, 'XIxdbnwYMfOJDsZlaowZ']"
},
{
"code": null,
"e": 4585,
"s": 4523,
"text": "A decimal with 5 left digits and 6 right digits (after the .)"
},
{
"code": null,
"e": 4706,
"s": 4585,
"text": ">>> fake.pydecimal(left_digits=5, right_digits=6, positive=False, min_value=None, max_value=None)Decimal('92511.722977')"
},
{
"code": null,
"e": 4778,
"s": 4706,
"text": "You can find more about other Python datatypes that you can create here"
},
{
"code": null,
"e": 5063,
"s": 4778,
"text": "I hope you find Faker a helpful tool to create data efficiently. You may find this tool useful for what you are working on or may not at the moment. But it is helpful to know that there exists a tool that enables you to generate data with ease for your specific needs such as testing."
},
{
"code": null,
"e": 5179,
"s": 5063,
"text": "Feel free to fork and play with the code for this article in this Github repo or more information about Faker here."
},
{
"code": null,
"e": 5339,
"s": 5179,
"text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter."
}
]
|
C++ String Library - c_str | It returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object.
Following is the declaration for std::string::c_str.
const char* c_str() const;
const char* c_str() const noexcept;
const char* c_str() const noexcept;
none
It returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object.
if an exception is thrown, there are no changes in the string.
In below example for std::string::c_str.
#include <iostream>
#include <cstring>
#include <string>
int main () {
std::string str ("Please divide this sentance into parts");
char * cstr = new char [str.length()+1];
std::strcpy (cstr, str.c_str());
char * p = std::strtok (cstr," ");
while (p!=0) {
std::cout << p << '\n';
p = std::strtok(NULL," ");
}
delete[] cstr;
return 0;
}
The sample output should be like this −
Please
divide
this
sentance
into
parts
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2763,
"s": 2603,
"text": "It returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object."
},
{
"code": null,
"e": 2816,
"s": 2763,
"text": "Following is the declaration for std::string::c_str."
},
{
"code": null,
"e": 2843,
"s": 2816,
"text": "const char* c_str() const;"
},
{
"code": null,
"e": 2879,
"s": 2843,
"text": "const char* c_str() const noexcept;"
},
{
"code": null,
"e": 2915,
"s": 2879,
"text": "const char* c_str() const noexcept;"
},
{
"code": null,
"e": 2920,
"s": 2915,
"text": "none"
},
{
"code": null,
"e": 3080,
"s": 2920,
"text": "It returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object."
},
{
"code": null,
"e": 3143,
"s": 3080,
"text": "if an exception is thrown, there are no changes in the string."
},
{
"code": null,
"e": 3184,
"s": 3143,
"text": "In below example for std::string::c_str."
},
{
"code": null,
"e": 3559,
"s": 3184,
"text": "#include <iostream>\n#include <cstring>\n#include <string>\n\nint main () {\n std::string str (\"Please divide this sentance into parts\");\n\n char * cstr = new char [str.length()+1];\n std::strcpy (cstr, str.c_str());\n\n char * p = std::strtok (cstr,\" \");\n while (p!=0) {\n std::cout << p << '\\n';\n p = std::strtok(NULL,\" \");\n }\n\n delete[] cstr;\n return 0;\n}"
},
{
"code": null,
"e": 3599,
"s": 3559,
"text": "The sample output should be like this −"
},
{
"code": null,
"e": 3639,
"s": 3599,
"text": "Please\ndivide\nthis\nsentance\ninto\nparts\n"
},
{
"code": null,
"e": 3646,
"s": 3639,
"text": " Print"
},
{
"code": null,
"e": 3657,
"s": 3646,
"text": " Add Notes"
}
]
|
Phik (φk) — get familiar with the latest correlation coefficient | by Eryk Lewinson | Towards Data Science | Recently I was doing EDA using pandas-profiling and something piqued my interest. In the correlations tab, I saw many known metrics I have known since university — Pearson’s r, Spearman’s ρ, and so on. However, among those I have seen something new — Phik (φk). I have not heard about this metric before so I decided to dive a bit deeper into it.
Fortunately, the report generated by pandas-profiling also has an option to display some more details about the metrics. The following information was provided about Phik:
Phik (φk) is a new and practical correlation coefficient that works consistently between categorical, ordinal and interval variables, captures non-linear dependency and reverts to the Pearson correlation coefficient in case of a bivariate normal input distribution.
I must say, this sounds really useful! Especially when working with datasets containing a mixture of numeric and categorical features. In this article, you can find out a quick summary of what the new correlation metric does and how to use it in practice with the phik library.
In many fields (not only data science), Pearson’s correlation coefficient is a standard approach of measuring correlation between two variables. However, it has some drawbacks:
it works only with continuous variables,
it only accounts for a linear relationship between variables,
it is sensitive to outliers.
That is where φk comes into play and offers several improvements over the current go-to measure. The key differentiators of Phik are:
it is based on several refinements to Pearson’s χ2 (chi-squared) contingency test — a hypothesis test for independence between two (or more) variables,
it works consistently between categorical, ordinal, and interval (continuous) variables,
ti captures non-linear dependencies,
it reverts to Pearson’s correlation coefficient in the case of a bivariate normal distribution of the input,
the algorithm contains a built-in noise reduction technique against statistical fluctuations.
The most similar metric to φk is Cramer’s φ, which is a correlation coefficient meant for two categorical variables and is also based on Pearson’s χ2 test statistic. What is important to note is that even though it is a measure used for categorical variables, it can also be used for ordinal and binned interval variables. However, the value of the coefficient is highly dependent on the binning chosen per variable and can therefore be difficult to interpret and compare. That is not the case for φk. Additionally, Cramer’s φ is sensitive to outliers, especially for smaller sample sizes.
In the figure below, you can see a few comparisons presenting the selected three correlation metrics. We can see that φk does a good job at detecting non-linear patterns missed by other coefficients. As you can see, the values of φk are between 0 and 1, so there is no indication of the direction of the relationship.
Naturally, there are also some drawbacks of the new method:
the calculation of φk is computationally expensive (due to calculation of some integrals under the hood),
no closed-form formula,
no indication of direction,
when working with numeric-only variables, other correlation coefficients will be more precise, especially for small samples.
In this article, I do not want to go much into the details of how to actually calculate the φk. The main reason for that is that the process is more complex than just explaining one formula as in the case of Pearson’s r. That is why I prefer to focus on the practical part ahead, and refer all interested to the source paper (which is written in a nice and easy-to-understand way).
For a while, I was wondering what would be a good dataset for testing out the new correlation coefficient. And inspiration came unexpectedly while browsing some video game news — a dataset containing all the Pokémon will be perfect for the analysis, as it combines categorical and numerical features. There are no ordinal features in the dataset, but that will not be a problem for presenting how to work with phik. You can find the data here.
As always, the first step is to load the libraries.
Then, we load and prepare the data. We only keep the relevant columns (battle statistics, generation, type and boolean flags indicating whether a Pokémon is legendary or not), as many of the other ones are related to evolutions and other forms.
Now we are ready for exploring the data using the φk coefficient.
Getting the correlation matrix containing the pair-wise φk coefficients is as easy as using the phik_matrix method. By default, the library drops the NaNs from the data for calculating the correlation coefficient. Additionally, we round the results to two decimals, for improved readability.
phik_overview = df.phik_matrix()phik_overview.round(2)
When we do not provide a list containing the interval columns as an argument, the columns will be selected based on educated guessing. In this case, the is_legendary and related are not interval columns, so we will create an appropriate list and pass it as an argument.
Also, we can manually specify the bins we would like to use for the interval variables. We do not do so, so the bins will be determined automatically.
To make the analysis of the table easier, we can use the plot_correlation_matrix function to plot the results as a heatmap.
We can see that there is some correlation between variables such as defense and hp, or hp and attack. What is more, we can see that there is no correlation between special attack and generation.
When assessing correlations we should not only look at the coefficients but also at their statistical significance. Because in the end, a large correlation may be statistically insignificant, and vice versa.
The heatmap above presents the significance matrix. The color scale indicates the level of significance and it saturates at +/- 5 standard deviations. The relatively high values of the correlation coefficient for the battle stats we mentioned above are statistically significant, while the correlation of special attack versus generation is not.
For more details on how to calculate the statistical significance and what corrections to the “standard” p-value calculation are taken into account, please refer to the original paper.
The global correlation coefficient is a useful measure expressing the total correlation of one variable to all other variables in the dataset. This gives us an indication of how well one variable can be modeled using the other variables.
All variables have pretty high values of the global correlation metric, with the highest one going to defense. We have seen before that there was a strong correlation between defense and some other battle stats, hence the highest score here.
While Pearson’s correlation between two continuous variables is easy to interpret, that is not the case for φk between two variables of mixed types, especially when it concerns categorical variables. That is why the authors provided additional functionality to look at the outliers — excesses, and deficits over the expected frequencies coming from the contingency table of two variables.
We first take a look at a continuous vs. categorical feature. For that example, we selected secondary_type and defense.
Running the code generates the following heatmap:
Some of the conclusions we can draw from the plot above — rock and steel Pokémon (as secondary type) have significantly higher defense, while the inverse is true for the poison/fairy/flying ones.
Then, we do a similar analysis for two categorical variables — primary and secondary types.
Analyzing this table indicates that are significantly more normal-flying and grass-poison Pokémon than expected, and significantly fewer normal-poison and dragon-bug. From my knowledge of Pokémon, that is indeed the case, and the conclusions from this table represent the actual types of Pokémon in the games.
Above, we have seen four different things we can investigate with the phik library. There is also a convenience function that allows us to generate all of the above with a single line of code.
The function generates a report by pairwise evaluation of all correlations, their significances and outlier significances.
Note: The number of plots can easily explode for a larger dataset. That is why we can tune the correlation and significance thresholds to only plot the relevant variables.
φk is a new correlation coefficient, especially suitable for working with mixed-type variables.
using the coefficient, we can find variable pairs that have (un)expected correlations, and evaluate their statistical significance. We can also interpret the dependencies between each pair of variables.
You can find the code used for this article on my GitHub. Also, any constructive feedback is welcome. You can reach out to me on Twitter or in the comments.
If you liked this article, you might also be interested in one of the following:
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
Baak, M., Koopman, R., Snoek, H., & Klous, S. (2020). A new correlation coefficient between categorical, ordinal and interval variables with Pearson characteristics. Computational Statistics & Data Analysis, 152, 107043. — https://arxiv.org/abs/1811.11440 | [
{
"code": null,
"e": 518,
"s": 171,
"text": "Recently I was doing EDA using pandas-profiling and something piqued my interest. In the correlations tab, I saw many known metrics I have known since university — Pearson’s r, Spearman’s ρ, and so on. However, among those I have seen something new — Phik (φk). I have not heard about this metric before so I decided to dive a bit deeper into it."
},
{
"code": null,
"e": 690,
"s": 518,
"text": "Fortunately, the report generated by pandas-profiling also has an option to display some more details about the metrics. The following information was provided about Phik:"
},
{
"code": null,
"e": 956,
"s": 690,
"text": "Phik (φk) is a new and practical correlation coefficient that works consistently between categorical, ordinal and interval variables, captures non-linear dependency and reverts to the Pearson correlation coefficient in case of a bivariate normal input distribution."
},
{
"code": null,
"e": 1234,
"s": 956,
"text": "I must say, this sounds really useful! Especially when working with datasets containing a mixture of numeric and categorical features. In this article, you can find out a quick summary of what the new correlation metric does and how to use it in practice with the phik library."
},
{
"code": null,
"e": 1411,
"s": 1234,
"text": "In many fields (not only data science), Pearson’s correlation coefficient is a standard approach of measuring correlation between two variables. However, it has some drawbacks:"
},
{
"code": null,
"e": 1452,
"s": 1411,
"text": "it works only with continuous variables,"
},
{
"code": null,
"e": 1514,
"s": 1452,
"text": "it only accounts for a linear relationship between variables,"
},
{
"code": null,
"e": 1543,
"s": 1514,
"text": "it is sensitive to outliers."
},
{
"code": null,
"e": 1677,
"s": 1543,
"text": "That is where φk comes into play and offers several improvements over the current go-to measure. The key differentiators of Phik are:"
},
{
"code": null,
"e": 1829,
"s": 1677,
"text": "it is based on several refinements to Pearson’s χ2 (chi-squared) contingency test — a hypothesis test for independence between two (or more) variables,"
},
{
"code": null,
"e": 1918,
"s": 1829,
"text": "it works consistently between categorical, ordinal, and interval (continuous) variables,"
},
{
"code": null,
"e": 1955,
"s": 1918,
"text": "ti captures non-linear dependencies,"
},
{
"code": null,
"e": 2064,
"s": 1955,
"text": "it reverts to Pearson’s correlation coefficient in the case of a bivariate normal distribution of the input,"
},
{
"code": null,
"e": 2158,
"s": 2064,
"text": "the algorithm contains a built-in noise reduction technique against statistical fluctuations."
},
{
"code": null,
"e": 2748,
"s": 2158,
"text": "The most similar metric to φk is Cramer’s φ, which is a correlation coefficient meant for two categorical variables and is also based on Pearson’s χ2 test statistic. What is important to note is that even though it is a measure used for categorical variables, it can also be used for ordinal and binned interval variables. However, the value of the coefficient is highly dependent on the binning chosen per variable and can therefore be difficult to interpret and compare. That is not the case for φk. Additionally, Cramer’s φ is sensitive to outliers, especially for smaller sample sizes."
},
{
"code": null,
"e": 3066,
"s": 2748,
"text": "In the figure below, you can see a few comparisons presenting the selected three correlation metrics. We can see that φk does a good job at detecting non-linear patterns missed by other coefficients. As you can see, the values of φk are between 0 and 1, so there is no indication of the direction of the relationship."
},
{
"code": null,
"e": 3126,
"s": 3066,
"text": "Naturally, there are also some drawbacks of the new method:"
},
{
"code": null,
"e": 3232,
"s": 3126,
"text": "the calculation of φk is computationally expensive (due to calculation of some integrals under the hood),"
},
{
"code": null,
"e": 3256,
"s": 3232,
"text": "no closed-form formula,"
},
{
"code": null,
"e": 3284,
"s": 3256,
"text": "no indication of direction,"
},
{
"code": null,
"e": 3409,
"s": 3284,
"text": "when working with numeric-only variables, other correlation coefficients will be more precise, especially for small samples."
},
{
"code": null,
"e": 3791,
"s": 3409,
"text": "In this article, I do not want to go much into the details of how to actually calculate the φk. The main reason for that is that the process is more complex than just explaining one formula as in the case of Pearson’s r. That is why I prefer to focus on the practical part ahead, and refer all interested to the source paper (which is written in a nice and easy-to-understand way)."
},
{
"code": null,
"e": 4236,
"s": 3791,
"text": "For a while, I was wondering what would be a good dataset for testing out the new correlation coefficient. And inspiration came unexpectedly while browsing some video game news — a dataset containing all the Pokémon will be perfect for the analysis, as it combines categorical and numerical features. There are no ordinal features in the dataset, but that will not be a problem for presenting how to work with phik. You can find the data here."
},
{
"code": null,
"e": 4288,
"s": 4236,
"text": "As always, the first step is to load the libraries."
},
{
"code": null,
"e": 4534,
"s": 4288,
"text": "Then, we load and prepare the data. We only keep the relevant columns (battle statistics, generation, type and boolean flags indicating whether a Pokémon is legendary or not), as many of the other ones are related to evolutions and other forms."
},
{
"code": null,
"e": 4600,
"s": 4534,
"text": "Now we are ready for exploring the data using the φk coefficient."
},
{
"code": null,
"e": 4892,
"s": 4600,
"text": "Getting the correlation matrix containing the pair-wise φk coefficients is as easy as using the phik_matrix method. By default, the library drops the NaNs from the data for calculating the correlation coefficient. Additionally, we round the results to two decimals, for improved readability."
},
{
"code": null,
"e": 4947,
"s": 4892,
"text": "phik_overview = df.phik_matrix()phik_overview.round(2)"
},
{
"code": null,
"e": 5217,
"s": 4947,
"text": "When we do not provide a list containing the interval columns as an argument, the columns will be selected based on educated guessing. In this case, the is_legendary and related are not interval columns, so we will create an appropriate list and pass it as an argument."
},
{
"code": null,
"e": 5368,
"s": 5217,
"text": "Also, we can manually specify the bins we would like to use for the interval variables. We do not do so, so the bins will be determined automatically."
},
{
"code": null,
"e": 5492,
"s": 5368,
"text": "To make the analysis of the table easier, we can use the plot_correlation_matrix function to plot the results as a heatmap."
},
{
"code": null,
"e": 5687,
"s": 5492,
"text": "We can see that there is some correlation between variables such as defense and hp, or hp and attack. What is more, we can see that there is no correlation between special attack and generation."
},
{
"code": null,
"e": 5895,
"s": 5687,
"text": "When assessing correlations we should not only look at the coefficients but also at their statistical significance. Because in the end, a large correlation may be statistically insignificant, and vice versa."
},
{
"code": null,
"e": 6241,
"s": 5895,
"text": "The heatmap above presents the significance matrix. The color scale indicates the level of significance and it saturates at +/- 5 standard deviations. The relatively high values of the correlation coefficient for the battle stats we mentioned above are statistically significant, while the correlation of special attack versus generation is not."
},
{
"code": null,
"e": 6426,
"s": 6241,
"text": "For more details on how to calculate the statistical significance and what corrections to the “standard” p-value calculation are taken into account, please refer to the original paper."
},
{
"code": null,
"e": 6664,
"s": 6426,
"text": "The global correlation coefficient is a useful measure expressing the total correlation of one variable to all other variables in the dataset. This gives us an indication of how well one variable can be modeled using the other variables."
},
{
"code": null,
"e": 6906,
"s": 6664,
"text": "All variables have pretty high values of the global correlation metric, with the highest one going to defense. We have seen before that there was a strong correlation between defense and some other battle stats, hence the highest score here."
},
{
"code": null,
"e": 7295,
"s": 6906,
"text": "While Pearson’s correlation between two continuous variables is easy to interpret, that is not the case for φk between two variables of mixed types, especially when it concerns categorical variables. That is why the authors provided additional functionality to look at the outliers — excesses, and deficits over the expected frequencies coming from the contingency table of two variables."
},
{
"code": null,
"e": 7415,
"s": 7295,
"text": "We first take a look at a continuous vs. categorical feature. For that example, we selected secondary_type and defense."
},
{
"code": null,
"e": 7465,
"s": 7415,
"text": "Running the code generates the following heatmap:"
},
{
"code": null,
"e": 7662,
"s": 7465,
"text": "Some of the conclusions we can draw from the plot above — rock and steel Pokémon (as secondary type) have significantly higher defense, while the inverse is true for the poison/fairy/flying ones."
},
{
"code": null,
"e": 7754,
"s": 7662,
"text": "Then, we do a similar analysis for two categorical variables — primary and secondary types."
},
{
"code": null,
"e": 8067,
"s": 7754,
"text": "Analyzing this table indicates that are significantly more normal-flying and grass-poison Pokémon than expected, and significantly fewer normal-poison and dragon-bug. From my knowledge of Pokémon, that is indeed the case, and the conclusions from this table represent the actual types of Pokémon in the games."
},
{
"code": null,
"e": 8260,
"s": 8067,
"text": "Above, we have seen four different things we can investigate with the phik library. There is also a convenience function that allows us to generate all of the above with a single line of code."
},
{
"code": null,
"e": 8383,
"s": 8260,
"text": "The function generates a report by pairwise evaluation of all correlations, their significances and outlier significances."
},
{
"code": null,
"e": 8555,
"s": 8383,
"text": "Note: The number of plots can easily explode for a larger dataset. That is why we can tune the correlation and significance thresholds to only plot the relevant variables."
},
{
"code": null,
"e": 8651,
"s": 8555,
"text": "φk is a new correlation coefficient, especially suitable for working with mixed-type variables."
},
{
"code": null,
"e": 8854,
"s": 8651,
"text": "using the coefficient, we can find variable pairs that have (un)expected correlations, and evaluate their statistical significance. We can also interpret the dependencies between each pair of variables."
},
{
"code": null,
"e": 9011,
"s": 8854,
"text": "You can find the code used for this article on my GitHub. Also, any constructive feedback is welcome. You can reach out to me on Twitter or in the comments."
},
{
"code": null,
"e": 9092,
"s": 9011,
"text": "If you liked this article, you might also be interested in one of the following:"
},
{
"code": null,
"e": 9115,
"s": 9092,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9138,
"s": 9115,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9161,
"s": 9138,
"text": "towardsdatascience.com"
}
]
|
How to stop Tkinter Frame from shrinking to fit its contents? | The sizing property of all the widgets in the Tkinter frame is by default set to the size of the widgets themselves. The frame container shrinks or grows automatically to fit the widgets inside it. To stop allowing the frame to shrink or grow the widget, we can use propagate(boolean) method with one of any pack or grid geometry manager. This method stops the frame from propagating the widgets to be resized.
There are two general ways we can define the propagate property,
pack_propagate (False) – If the Frame is defined using the Pack Geometry Manager.
pack_propagate (False) – If the Frame is defined using the Pack Geometry Manager.
grid_propagate (False) – If the Frame is defined using the Grid Geometry Manager.
grid_propagate (False) – If the Frame is defined using the Grid Geometry Manager.
In this example, we will create two entry widget inside a frame which don’t allow the widget to be shrink or fit.
#Import the required Libraries
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
#Create an instance of Tkinter frame
win = Tk()
#Set the geometry of tkinter frame
win.geometry("750x250")
#Define a function to show a message
def submit():
messagebox.showinfo("Success", "Submitted Successfully!")
#Creates top frame
frame1 = LabelFrame(win, width= 400, height= 180, bd=5)
frame1.pack()
#Stop the frame from propagating the widget to be shrink or fit
frame1.pack_propagate(False)
#Create an Entry widget in Frame1
entry1 = ttk.Entry(frame1, width= 40)
entry1.insert(INSERT,"Enter Your Name")
entry1.pack(pady=30)
entry2= ttk.Entry(frame1, width= 40)
entry2.insert(INSERT, "Enter Your Email")
entry2.pack()
#Creates bottom frame for button
frame2 = LabelFrame(win, width= 150, height=100)
frame2.pack()
#Create a Button to enable frame
button1 = ttk.Button(frame2, text="Submit", command= submit)
button1.pack()
win.mainloop()
Run the above code to display a window that contains two frames with widgets defined in it.
In the given output, the window contains a frame with entry widget that doesn’t shrink the widgets defined inside it. | [
{
"code": null,
"e": 1473,
"s": 1062,
"text": "The sizing property of all the widgets in the Tkinter frame is by default set to the size of the widgets themselves. The frame container shrinks or grows automatically to fit the widgets inside it. To stop allowing the frame to shrink or grow the widget, we can use propagate(boolean) method with one of any pack or grid geometry manager. This method stops the frame from propagating the widgets to be resized."
},
{
"code": null,
"e": 1538,
"s": 1473,
"text": "There are two general ways we can define the propagate property,"
},
{
"code": null,
"e": 1620,
"s": 1538,
"text": "pack_propagate (False) – If the Frame is defined using the Pack Geometry Manager."
},
{
"code": null,
"e": 1702,
"s": 1620,
"text": "pack_propagate (False) – If the Frame is defined using the Pack Geometry Manager."
},
{
"code": null,
"e": 1784,
"s": 1702,
"text": "grid_propagate (False) – If the Frame is defined using the Grid Geometry Manager."
},
{
"code": null,
"e": 1866,
"s": 1784,
"text": "grid_propagate (False) – If the Frame is defined using the Grid Geometry Manager."
},
{
"code": null,
"e": 1980,
"s": 1866,
"text": "In this example, we will create two entry widget inside a frame which don’t allow the widget to be shrink or fit."
},
{
"code": null,
"e": 2944,
"s": 1980,
"text": "#Import the required Libraries\nfrom tkinter import *\nfrom tkinter import ttk\nfrom tkinter import messagebox\n\n#Create an instance of Tkinter frame\nwin = Tk()\n\n#Set the geometry of tkinter frame\nwin.geometry(\"750x250\")\n\n#Define a function to show a message\ndef submit():\n messagebox.showinfo(\"Success\", \"Submitted Successfully!\")\n\n#Creates top frame\nframe1 = LabelFrame(win, width= 400, height= 180, bd=5)\nframe1.pack()\n\n#Stop the frame from propagating the widget to be shrink or fit\nframe1.pack_propagate(False)\n\n#Create an Entry widget in Frame1\nentry1 = ttk.Entry(frame1, width= 40)\nentry1.insert(INSERT,\"Enter Your Name\")\nentry1.pack(pady=30)\nentry2= ttk.Entry(frame1, width= 40)\nentry2.insert(INSERT, \"Enter Your Email\")\nentry2.pack()\n\n#Creates bottom frame for button\nframe2 = LabelFrame(win, width= 150, height=100)\nframe2.pack()\n\n#Create a Button to enable frame\nbutton1 = ttk.Button(frame2, text=\"Submit\", command= submit)\nbutton1.pack()\n\nwin.mainloop()"
},
{
"code": null,
"e": 3036,
"s": 2944,
"text": "Run the above code to display a window that contains two frames with widgets defined in it."
},
{
"code": null,
"e": 3154,
"s": 3036,
"text": "In the given output, the window contains a frame with entry widget that doesn’t shrink the widgets defined inside it."
}
]
|
C# | Array.TrueForAll() Method | 08 Jul, 2021
This method is used to determine whether every element in the array matches the conditions defined by the specified predicate.Syntax:
public static bool TrueForAll (T[] array, Predicate<T> match);
Here, T is the type of element of the array.Parameters:
array: It is the one-dimensional, zero-based Array to check against the conditions. match: It is the predicate that defines the conditions to check against the elements.
Return Value: This method returns true if every element in the array matches the conditions defined by the specified predicate otherwise it returns false. If there are no elements in the array, the return value is true.Exception: This method throws ArgumentNullException if the array is null or the match is null.Below programs illustrate the use of Array.TrueForAll(T[], Predicate) Method:Example 1:
CSHARP
// C# program to demonstrate// TrueForAll() methodusing System;using System.Collections.Generic; public class GFG { // Main Methodpublic static void Main(){ try { // Creating and initializing new the String String[] myArr = {"Sun", "Son", "Sue", "Shu"}; // Display the values of the myArr. Console.WriteLine("Initial Array:"); // calling the PrintIndexAndValues() // method to print PrintIndexAndValues(myArr); // getting the bool value // with required condition // using method TrueForAll() bool value = Array.TrueForAll(myArr, element => element.StartsWith("S", StringComparison.Ordinal)); // Checking the condition if (value) Console.Write("Every Element is satisfying condition"); else Console.Write("Every Element is not satisfying condition"); } catch (ArgumentException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); }} // Defining the method// PrintIndexAndValuespublic static void PrintIndexAndValues(String[] myArr){ for (int i = 0; i < myArr.Length; i++) { Console.WriteLine("{0}", myArr[i]); } Console.WriteLine();}}
Initial Array:
Sun
Son
Sue
Shu
Every Element is satisfying condition
Example 2: For ArgumentNullException
CSHARP
// C# program to demonstrate// TrueForAll() method// For ArgumentNullExceptionusing System;using System.Collections.Generic; public class GFG { // Main Methodpublic static void Main(){ try { // Creating and initializing new // the String with a null value String[] myArr = null; // getting the bool value // with required condition // using method TrueForAll() Console.WriteLine("Trying to get the boolean " +"value while myArr is null"); Console.WriteLine(); bool value = Array.TrueForAll(myArr, element => element.StartsWith("S", StringComparison.Ordinal)); // Checking the condition if (value) Console.Write("Every Element is satisfying condition"); else Console.Write("Every Element is not satisfying condition"); } catch (ArgumentException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); }} // Defining the method// PrintIndexAndValuespublic static void PrintIndexAndValues(String[] myArr){ for (int i = 0; i < myArr.Length; i++) { Console.WriteLine("{0}", myArr[i]); } Console.WriteLine();}}
Trying to get the boolean value while myArr is null
Exception Thrown: System.ArgumentNullException
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.array.trueforall?view=netframework-4.7.2
kapoorsagar226
CSharp-Arrays
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Jul, 2021"
},
{
"code": null,
"e": 164,
"s": 28,
"text": "This method is used to determine whether every element in the array matches the conditions defined by the specified predicate.Syntax: "
},
{
"code": null,
"e": 227,
"s": 164,
"text": "public static bool TrueForAll (T[] array, Predicate<T> match);"
},
{
"code": null,
"e": 285,
"s": 227,
"text": "Here, T is the type of element of the array.Parameters: "
},
{
"code": null,
"e": 457,
"s": 285,
"text": "array: It is the one-dimensional, zero-based Array to check against the conditions. match: It is the predicate that defines the conditions to check against the elements. "
},
{
"code": null,
"e": 859,
"s": 457,
"text": "Return Value: This method returns true if every element in the array matches the conditions defined by the specified predicate otherwise it returns false. If there are no elements in the array, the return value is true.Exception: This method throws ArgumentNullException if the array is null or the match is null.Below programs illustrate the use of Array.TrueForAll(T[], Predicate) Method:Example 1: "
},
{
"code": null,
"e": 866,
"s": 859,
"text": "CSHARP"
},
{
"code": "// C# program to demonstrate// TrueForAll() methodusing System;using System.Collections.Generic; public class GFG { // Main Methodpublic static void Main(){ try { // Creating and initializing new the String String[] myArr = {\"Sun\", \"Son\", \"Sue\", \"Shu\"}; // Display the values of the myArr. Console.WriteLine(\"Initial Array:\"); // calling the PrintIndexAndValues() // method to print PrintIndexAndValues(myArr); // getting the bool value // with required condition // using method TrueForAll() bool value = Array.TrueForAll(myArr, element => element.StartsWith(\"S\", StringComparison.Ordinal)); // Checking the condition if (value) Console.Write(\"Every Element is satisfying condition\"); else Console.Write(\"Every Element is not satisfying condition\"); } catch (ArgumentException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); }} // Defining the method// PrintIndexAndValuespublic static void PrintIndexAndValues(String[] myArr){ for (int i = 0; i < myArr.Length; i++) { Console.WriteLine(\"{0}\", myArr[i]); } Console.WriteLine();}}",
"e": 2158,
"s": 866,
"text": null
},
{
"code": null,
"e": 2228,
"s": 2158,
"text": "Initial Array:\nSun\nSon\nSue\nShu\n\nEvery Element is satisfying condition"
},
{
"code": null,
"e": 2268,
"s": 2230,
"text": "Example 2: For ArgumentNullException "
},
{
"code": null,
"e": 2275,
"s": 2268,
"text": "CSHARP"
},
{
"code": "// C# program to demonstrate// TrueForAll() method// For ArgumentNullExceptionusing System;using System.Collections.Generic; public class GFG { // Main Methodpublic static void Main(){ try { // Creating and initializing new // the String with a null value String[] myArr = null; // getting the bool value // with required condition // using method TrueForAll() Console.WriteLine(\"Trying to get the boolean \" +\"value while myArr is null\"); Console.WriteLine(); bool value = Array.TrueForAll(myArr, element => element.StartsWith(\"S\", StringComparison.Ordinal)); // Checking the condition if (value) Console.Write(\"Every Element is satisfying condition\"); else Console.Write(\"Every Element is not satisfying condition\"); } catch (ArgumentException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); }} // Defining the method// PrintIndexAndValuespublic static void PrintIndexAndValues(String[] myArr){ for (int i = 0; i < myArr.Length; i++) { Console.WriteLine(\"{0}\", myArr[i]); } Console.WriteLine();}}",
"e": 3541,
"s": 2275,
"text": null
},
{
"code": null,
"e": 3641,
"s": 3541,
"text": "Trying to get the boolean value while myArr is null\n\nException Thrown: System.ArgumentNullException"
},
{
"code": null,
"e": 3656,
"s": 3643,
"text": "Reference: "
},
{
"code": null,
"e": 3748,
"s": 3656,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.array.trueforall?view=netframework-4.7.2"
},
{
"code": null,
"e": 3765,
"s": 3750,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 3779,
"s": 3765,
"text": "CSharp-Arrays"
},
{
"code": null,
"e": 3793,
"s": 3779,
"text": "CSharp-method"
},
{
"code": null,
"e": 3796,
"s": 3793,
"text": "C#"
}
]
|
How to Execute a .class File in Java? | 02 Dec, 2020
A Java class file is a compiled java file. It is compiled by the Java compiler into bytecode to be executed by the Java Virtual Machine.
1. To compile your .java files, open Terminal (Mac) or Command Prompt (Windows).
2. Navigate to the folder your java file is at.
3. To compile, type
javac <javaFileName>
4. After hitting enter, .class files will appear in the same folder for each .java file.
5. To run the class file, it must have a main method,
java <classname>
6. The result will be displayed in the Terminal or Command Prompt.
Example
Java
// Run a class file in java import java.io.*; class GFG { public static void main(String[] args) { // prints GFG! System.out.println("GFG!"); }}
GFG!
java-basics
Picked
Java
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
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Dec, 2020"
},
{
"code": null,
"e": 165,
"s": 28,
"text": "A Java class file is a compiled java file. It is compiled by the Java compiler into bytecode to be executed by the Java Virtual Machine."
},
{
"code": null,
"e": 246,
"s": 165,
"text": "1. To compile your .java files, open Terminal (Mac) or Command Prompt (Windows)."
},
{
"code": null,
"e": 294,
"s": 246,
"text": "2. Navigate to the folder your java file is at."
},
{
"code": null,
"e": 314,
"s": 294,
"text": "3. To compile, type"
},
{
"code": null,
"e": 335,
"s": 314,
"text": "javac <javaFileName>"
},
{
"code": null,
"e": 424,
"s": 335,
"text": "4. After hitting enter, .class files will appear in the same folder for each .java file."
},
{
"code": null,
"e": 479,
"s": 424,
"text": "5. To run the class file, it must have a main method, "
},
{
"code": null,
"e": 496,
"s": 479,
"text": "java <classname>"
},
{
"code": null,
"e": 563,
"s": 496,
"text": "6. The result will be displayed in the Terminal or Command Prompt."
},
{
"code": null,
"e": 571,
"s": 563,
"text": "Example"
},
{
"code": null,
"e": 576,
"s": 571,
"text": "Java"
},
{
"code": "// Run a class file in java import java.io.*; class GFG { public static void main(String[] args) { // prints GFG! System.out.println(\"GFG!\"); }}",
"e": 748,
"s": 576,
"text": null
},
{
"code": null,
"e": 753,
"s": 748,
"text": "GFG!"
},
{
"code": null,
"e": 765,
"s": 753,
"text": "java-basics"
},
{
"code": null,
"e": 772,
"s": 765,
"text": "Picked"
},
{
"code": null,
"e": 777,
"s": 772,
"text": "Java"
},
{
"code": null,
"e": 782,
"s": 777,
"text": "Java"
},
{
"code": null,
"e": 880,
"s": 782,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 895,
"s": 880,
"text": "Stream In Java"
},
{
"code": null,
"e": 916,
"s": 895,
"text": "Introduction to Java"
},
{
"code": null,
"e": 937,
"s": 916,
"text": "Constructors in Java"
},
{
"code": null,
"e": 956,
"s": 937,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 973,
"s": 956,
"text": "Generics in Java"
},
{
"code": null,
"e": 1003,
"s": 973,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 1029,
"s": 1003,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 1045,
"s": 1029,
"text": "Strings in Java"
},
{
"code": null,
"e": 1082,
"s": 1045,
"text": "Differences between JDK, JRE and JVM"
}
]
|
Matplotlib.axes.Axes.get_position() in Python | 19 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.set_position() function in axes module of matplotlib library is used to Get a copy of the axes rectangle as a Bbox..
Syntax: Axes.get_position(self, original=False)
Parameters:
original : This parameter is used to return the original position if true. Otherwise return the active position.
Return value: This method returns a copy of the axes rectangle as a Bbox.
Below examples illustrate the matplotlib.axes.Axes.get_position() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np x = np.arange(10)y = [2, 4, 6, 14, 15, 16, 17, 16, 18, 20]y2 = [10, 11, 12, 13, 8, 10, 12, 14, 18, 19] fig, ax1 = plt.subplots() ax1.plot(x, y, "go-", label ='Line 1', )ax1.plot(x, y2, "o-", label ='Line 2') chartBox = ax1.get_position()x, y, w, h = chartBox.x0, chartBox.y0, chartBox.width, chartBox.height ax1.text(0, 20, "Bbox - xmin : "+str(x), fontweight ="bold")ax1.text(0, 19, "Bbox - ymin : "+str(round(y, 2)), fontweight ="bold")ax1.text(0, 18, "Bbox - width : "+str(w), fontweight ="bold")ax1.text(0, 17, "Bbox - height : "+str(h), fontweight ="bold")fig.suptitle('matplotlib.axes.Axes.get_position()\function Example\n', fontweight ="bold")plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm Z = np.random.rand(6, 30) fig, ax1 = plt.subplots() ax1.pcolor(Z) chartBox = ax1.get_position()x, y, x1, y1 = chartBox.x0, chartBox.y0, chartBox.x1, chartBox.y1 ax1.text(4, 6.35, "Bbox - xmin : "+str(x), fontweight ="bold")ax1.text(19, 6.35, "Bbox - ymin : "+str(round(y, 2)), fontweight ="bold")ax1.text(4, 6.15, "Bbox - xmax : "+str(x1), fontweight ="bold")ax1.text(19, 6.15, "Bbox - ymax : "+str(y1), fontweight ="bold")fig.suptitle('matplotlib.axes.Axes.get_position()\function Example\n', fontweight ="bold")plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Apr, 2020"
},
{
"code": null,
"e": 328,
"s": 28,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute."
},
{
"code": null,
"e": 454,
"s": 328,
"text": "The Axes.set_position() function in axes module of matplotlib library is used to Get a copy of the axes rectangle as a Bbox.."
},
{
"code": null,
"e": 502,
"s": 454,
"text": "Syntax: Axes.get_position(self, original=False)"
},
{
"code": null,
"e": 514,
"s": 502,
"text": "Parameters:"
},
{
"code": null,
"e": 627,
"s": 514,
"text": "original : This parameter is used to return the original position if true. Otherwise return the active position."
},
{
"code": null,
"e": 701,
"s": 627,
"text": "Return value: This method returns a copy of the axes rectangle as a Bbox."
},
{
"code": null,
"e": 796,
"s": 701,
"text": "Below examples illustrate the matplotlib.axes.Axes.get_position() function in matplotlib.axes:"
},
{
"code": null,
"e": 807,
"s": 796,
"text": "Example 1:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np x = np.arange(10)y = [2, 4, 6, 14, 15, 16, 17, 16, 18, 20]y2 = [10, 11, 12, 13, 8, 10, 12, 14, 18, 19] fig, ax1 = plt.subplots() ax1.plot(x, y, \"go-\", label ='Line 1', )ax1.plot(x, y2, \"o-\", label ='Line 2') chartBox = ax1.get_position()x, y, w, h = chartBox.x0, chartBox.y0, chartBox.width, chartBox.height ax1.text(0, 20, \"Bbox - xmin : \"+str(x), fontweight =\"bold\")ax1.text(0, 19, \"Bbox - ymin : \"+str(round(y, 2)), fontweight =\"bold\")ax1.text(0, 18, \"Bbox - width : \"+str(w), fontweight =\"bold\")ax1.text(0, 17, \"Bbox - height : \"+str(h), fontweight =\"bold\")fig.suptitle('matplotlib.axes.Axes.get_position()\\function Example\\n', fontweight =\"bold\")plt.show()",
"e": 1602,
"s": 807,
"text": null
},
{
"code": null,
"e": 1610,
"s": 1602,
"text": "Output:"
},
{
"code": null,
"e": 1621,
"s": 1610,
"text": "Example 2:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm Z = np.random.rand(6, 30) fig, ax1 = plt.subplots() ax1.pcolor(Z) chartBox = ax1.get_position()x, y, x1, y1 = chartBox.x0, chartBox.y0, chartBox.x1, chartBox.y1 ax1.text(4, 6.35, \"Bbox - xmin : \"+str(x), fontweight =\"bold\")ax1.text(19, 6.35, \"Bbox - ymin : \"+str(round(y, 2)), fontweight =\"bold\")ax1.text(4, 6.15, \"Bbox - xmax : \"+str(x1), fontweight =\"bold\")ax1.text(19, 6.15, \"Bbox - ymax : \"+str(y1), fontweight =\"bold\")fig.suptitle('matplotlib.axes.Axes.get_position()\\function Example\\n', fontweight =\"bold\")plt.show()",
"e": 2313,
"s": 1621,
"text": null
},
{
"code": null,
"e": 2321,
"s": 2313,
"text": "Output:"
},
{
"code": null,
"e": 2339,
"s": 2321,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 2346,
"s": 2339,
"text": "Python"
},
{
"code": null,
"e": 2444,
"s": 2346,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2476,
"s": 2444,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2503,
"s": 2476,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2534,
"s": 2503,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2555,
"s": 2534,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2611,
"s": 2555,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2634,
"s": 2611,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2676,
"s": 2634,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2718,
"s": 2676,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2757,
"s": 2718,
"text": "Python | datetime.timedelta() function"
}
]
|
How to bundle an Angular app for production? | 28 May, 2020
IntroductionBefore deploying the web app, Angular provides a way to check the behavior of the web application with the help of a few CLI-commands. Usually, ng serves command is used to build, watch, and serve the application from local memory. But for deployment, the behavior of the application is seen by running ng build command.
Difference between ng serve and ng build
StepsBefore following the steps to deploy the application, make sure that Angular CLI is already installed in the system if it is not then run the following command.
npm install -g @angular/cli
The very first step would be to bundle up an application for production before its deployment.
Navigate to project directory.cd project-folder
cd project-folder
Run ng build command in Angular CLIng build --prod
ng build --prod
To get the preview of the application, run the following command:ng serve --prodThis starts a local HTTP server with production files. Navigate to http://localhost:4200/ to view the application.With these steps, the application is ready for deployment.
ng serve --prod
This starts a local HTTP server with production files. Navigate to http://localhost:4200/ to view the application.With these steps, the application is ready for deployment.
Approachng build command compiles the Angular app into an output directory named dist/ at the given output path. This command must be executed from within the working directory. The application builder in Angular uses the webpack build tool, with configuration options specified in the workspace configuration file (angular.json) or with a named alternative configuration. A “production” configuration is created by default when you use the CLI to create the project, and you can use that configuration by specifying the —configuration="production" or the --prod="true" option.
The –prod flag activates many optimization flags. One of them is –aot for Ahead Of Time compilation. Your component templates are compiled during the build, so TypeScript can detect more issues in your code. You can compile in dev mode but still activate the –aot flag if you want to see this error before building for prod.
dist/ FolderThe dist folder is the build folder which contains all the files and folders which can be hosted in the server.The dist folder contains the compiled code of your angular application in the format of JavaScript and also the required HTML and CSS files.Inside dist/ folder
Performance: Dynamic applications didn’t always perform that well. Complex SPAs could be laggy and inconvenient to use due to their size.
Steep learning curve: As AngularJS is a versatile instrument, there’s always more than one method to finish any task. This has produced some confusion among engineers.
AngularJS-Misc
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular File Upload
Angular | keyup event
Define ng-if, ng-show and ng-hide
Angular PrimeNG Dropdown Component
What is AOT and JIT Compiler in Angular ?
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
Difference between var, let and const keywords in JavaScript
REST API (Introduction) | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n28 May, 2020"
},
{
"code": null,
"e": 386,
"s": 53,
"text": "IntroductionBefore deploying the web app, Angular provides a way to check the behavior of the web application with the help of a few CLI-commands. Usually, ng serves command is used to build, watch, and serve the application from local memory. But for deployment, the behavior of the application is seen by running ng build command."
},
{
"code": null,
"e": 427,
"s": 386,
"text": "Difference between ng serve and ng build"
},
{
"code": null,
"e": 593,
"s": 427,
"text": "StepsBefore following the steps to deploy the application, make sure that Angular CLI is already installed in the system if it is not then run the following command."
},
{
"code": null,
"e": 621,
"s": 593,
"text": "npm install -g @angular/cli"
},
{
"code": null,
"e": 716,
"s": 621,
"text": "The very first step would be to bundle up an application for production before its deployment."
},
{
"code": null,
"e": 764,
"s": 716,
"text": "Navigate to project directory.cd project-folder"
},
{
"code": null,
"e": 782,
"s": 764,
"text": "cd project-folder"
},
{
"code": null,
"e": 834,
"s": 782,
"text": "Run ng build command in Angular CLIng build --prod "
},
{
"code": null,
"e": 851,
"s": 834,
"text": "ng build --prod "
},
{
"code": null,
"e": 1104,
"s": 851,
"text": "To get the preview of the application, run the following command:ng serve --prodThis starts a local HTTP server with production files. Navigate to http://localhost:4200/ to view the application.With these steps, the application is ready for deployment."
},
{
"code": null,
"e": 1120,
"s": 1104,
"text": "ng serve --prod"
},
{
"code": null,
"e": 1293,
"s": 1120,
"text": "This starts a local HTTP server with production files. Navigate to http://localhost:4200/ to view the application.With these steps, the application is ready for deployment."
},
{
"code": null,
"e": 1871,
"s": 1293,
"text": "Approachng build command compiles the Angular app into an output directory named dist/ at the given output path. This command must be executed from within the working directory. The application builder in Angular uses the webpack build tool, with configuration options specified in the workspace configuration file (angular.json) or with a named alternative configuration. A “production” configuration is created by default when you use the CLI to create the project, and you can use that configuration by specifying the —configuration=\"production\" or the --prod=\"true\" option."
},
{
"code": null,
"e": 2196,
"s": 1871,
"text": "The –prod flag activates many optimization flags. One of them is –aot for Ahead Of Time compilation. Your component templates are compiled during the build, so TypeScript can detect more issues in your code. You can compile in dev mode but still activate the –aot flag if you want to see this error before building for prod."
},
{
"code": null,
"e": 2479,
"s": 2196,
"text": "dist/ FolderThe dist folder is the build folder which contains all the files and folders which can be hosted in the server.The dist folder contains the compiled code of your angular application in the format of JavaScript and also the required HTML and CSS files.Inside dist/ folder"
},
{
"code": null,
"e": 2617,
"s": 2479,
"text": "Performance: Dynamic applications didn’t always perform that well. Complex SPAs could be laggy and inconvenient to use due to their size."
},
{
"code": null,
"e": 2785,
"s": 2617,
"text": "Steep learning curve: As AngularJS is a versatile instrument, there’s always more than one method to finish any task. This has produced some confusion among engineers."
},
{
"code": null,
"e": 2800,
"s": 2785,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 2807,
"s": 2800,
"text": "Picked"
},
{
"code": null,
"e": 2817,
"s": 2807,
"text": "AngularJS"
},
{
"code": null,
"e": 2834,
"s": 2817,
"text": "Web Technologies"
},
{
"code": null,
"e": 2932,
"s": 2834,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2952,
"s": 2932,
"text": "Angular File Upload"
},
{
"code": null,
"e": 2974,
"s": 2952,
"text": "Angular | keyup event"
},
{
"code": null,
"e": 3008,
"s": 2974,
"text": "Define ng-if, ng-show and ng-hide"
},
{
"code": null,
"e": 3043,
"s": 3008,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 3085,
"s": 3043,
"text": "What is AOT and JIT Compiler in Angular ?"
},
{
"code": null,
"e": 3118,
"s": 3085,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3161,
"s": 3118,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 3223,
"s": 3161,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3284,
"s": 3223,
"text": "Difference between var, let and const keywords in JavaScript"
}
]
|
Minimum spanning tree cost of given Graphs | 08 Jun, 2022
Given an undirected graph of V nodes (V > 2) named V1, V2, V3, ..., Vn. Two nodes Vi and Vj are connected to each other if and only if 0 < | i – j | ≤ 2. Each edge between any vertex pair (Vi, Vj) is assigned a weight i + j. The task is to find the cost of the minimum spanning tree of such graph with V nodes.Examples:
Input: V = 4
Output: 13Input: V = 5 Output: 21
Approach: Starting with a graph with minimum nodes (i.e. 3 nodes), the cost of the minimum spanning tree will be 7. Now for every node i starting from the fourth node which can be added to this graph, ith node can only be connected to (i – 1)th and (i – 2)th node and the minimum spanning tree will only include the node with the minimum weight so the newly added edge will have the weight i + (i – 2).
So addition of fourth node will increase the overall weight as 7 + (4 + 2) = 13 Similarly adding fifth node, weight = 13 + (5 + 3) = 21 ... For nth node, weight = weight + (n + (n – 2)).
This can be generalized as weight = V2 – V + 1 where V is the total nodes in the graph.Below is the implementation of the above approach:
C++
Java
C#
Python3
PHP
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns the minimum cost// of the spanning tree for the required graphint getMinCost(int Vertices){ int cost = 0; // Calculating cost of MST cost = (Vertices * Vertices) - Vertices + 1; return cost;} // Driver codeint main(){ int V = 5; cout << getMinCost(V); return 0;}
// Java implementation of the approachclass GfG{ // Function that returns the minimum cost// of the spanning tree for the required graphstatic int getMinCost(int Vertices){ int cost = 0; // Calculating cost of MST cost = (Vertices * Vertices) - Vertices + 1; return cost;} // Driver codepublic static void main(String[] args){ int V = 5; System.out.println(getMinCost(V));}} // This code is contributed by// Prerna Saini.
// C# implementation of the above approachusing System; class GfG{ // Function that returns the minimum cost // of the spanning tree for the required graph static int getMinCost(int Vertices) { int cost = 0; // Calculating cost of MST cost = (Vertices * Vertices) - Vertices + 1; return cost; } // Driver code public static void Main() { int V = 5; Console.WriteLine(getMinCost(V)); }} // This code is contributed by Ryuga
# python3 implementation of the approach # Function that returns the minimum cost# of the spanning tree for the required graphdef getMinCost( Vertices): cost = 0 # Calculating cost of MST cost = (Vertices * Vertices) - Vertices + 1 return cost # Driver codeif __name__ == "__main__": V = 5 print (getMinCost(V))
<?php// PHP implementation of the approach// Function that returns the minimum cost// of the spanning tree for the required graphfunction getMinCost($Vertices){ $cost = 0; // Calculating cost of MST $cost = ($Vertices * $Vertices) - $Vertices + 1; return $cost;} // Driver code$V = 5;echo getMinCost($V); #This Code is contributed by ajit..?>
<script> // Javascript implementation of the approach // Function that returns the minimum cost// of the spanning tree for the required graphfunction getMinCost(Vertices){ var cost = 0; // Calculating cost of MST cost = (Vertices * Vertices) - Vertices + 1; return cost;} // Driver codevar V = 5;document.write( getMinCost(V)); // This code is contributed by rrrtnx.</script>
21
Time Complexity: O(1)Auxiliary Space: O(1)
prerna saini
ankthon
jit_t
ukasp
rrrtnx
pushpeshrajdx01
Graph Minimum Spanning Tree
math
Minimum Spanning Tree
Graph
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n08 Jun, 2022"
},
{
"code": null,
"e": 376,
"s": 54,
"text": "Given an undirected graph of V nodes (V > 2) named V1, V2, V3, ..., Vn. Two nodes Vi and Vj are connected to each other if and only if 0 < | i – j | ≤ 2. Each edge between any vertex pair (Vi, Vj) is assigned a weight i + j. The task is to find the cost of the minimum spanning tree of such graph with V nodes.Examples: "
},
{
"code": null,
"e": 391,
"s": 376,
"text": "Input: V = 4 "
},
{
"code": null,
"e": 427,
"s": 391,
"text": "Output: 13Input: V = 5 Output: 21 "
},
{
"code": null,
"e": 834,
"s": 429,
"text": "Approach: Starting with a graph with minimum nodes (i.e. 3 nodes), the cost of the minimum spanning tree will be 7. Now for every node i starting from the fourth node which can be added to this graph, ith node can only be connected to (i – 1)th and (i – 2)th node and the minimum spanning tree will only include the node with the minimum weight so the newly added edge will have the weight i + (i – 2). "
},
{
"code": null,
"e": 1023,
"s": 834,
"text": "So addition of fourth node will increase the overall weight as 7 + (4 + 2) = 13 Similarly adding fifth node, weight = 13 + (5 + 3) = 21 ... For nth node, weight = weight + (n + (n – 2)). "
},
{
"code": null,
"e": 1163,
"s": 1023,
"text": "This can be generalized as weight = V2 – V + 1 where V is the total nodes in the graph.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1167,
"s": 1163,
"text": "C++"
},
{
"code": null,
"e": 1172,
"s": 1167,
"text": "Java"
},
{
"code": null,
"e": 1175,
"s": 1172,
"text": "C#"
},
{
"code": null,
"e": 1183,
"s": 1175,
"text": "Python3"
},
{
"code": null,
"e": 1187,
"s": 1183,
"text": "PHP"
},
{
"code": null,
"e": 1198,
"s": 1187,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns the minimum cost// of the spanning tree for the required graphint getMinCost(int Vertices){ int cost = 0; // Calculating cost of MST cost = (Vertices * Vertices) - Vertices + 1; return cost;} // Driver codeint main(){ int V = 5; cout << getMinCost(V); return 0;}",
"e": 1592,
"s": 1198,
"text": null
},
{
"code": "// Java implementation of the approachclass GfG{ // Function that returns the minimum cost// of the spanning tree for the required graphstatic int getMinCost(int Vertices){ int cost = 0; // Calculating cost of MST cost = (Vertices * Vertices) - Vertices + 1; return cost;} // Driver codepublic static void main(String[] args){ int V = 5; System.out.println(getMinCost(V));}} // This code is contributed by// Prerna Saini.",
"e": 2034,
"s": 1592,
"text": null
},
{
"code": "// C# implementation of the above approachusing System; class GfG{ // Function that returns the minimum cost // of the spanning tree for the required graph static int getMinCost(int Vertices) { int cost = 0; // Calculating cost of MST cost = (Vertices * Vertices) - Vertices + 1; return cost; } // Driver code public static void Main() { int V = 5; Console.WriteLine(getMinCost(V)); }} // This code is contributed by Ryuga",
"e": 2542,
"s": 2034,
"text": null
},
{
"code": "# python3 implementation of the approach # Function that returns the minimum cost# of the spanning tree for the required graphdef getMinCost( Vertices): cost = 0 # Calculating cost of MST cost = (Vertices * Vertices) - Vertices + 1 return cost # Driver codeif __name__ == \"__main__\": V = 5 print (getMinCost(V))",
"e": 2879,
"s": 2542,
"text": null
},
{
"code": "<?php// PHP implementation of the approach// Function that returns the minimum cost// of the spanning tree for the required graphfunction getMinCost($Vertices){ $cost = 0; // Calculating cost of MST $cost = ($Vertices * $Vertices) - $Vertices + 1; return $cost;} // Driver code$V = 5;echo getMinCost($V); #This Code is contributed by ajit..?>",
"e": 3236,
"s": 2879,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function that returns the minimum cost// of the spanning tree for the required graphfunction getMinCost(Vertices){ var cost = 0; // Calculating cost of MST cost = (Vertices * Vertices) - Vertices + 1; return cost;} // Driver codevar V = 5;document.write( getMinCost(V)); // This code is contributed by rrrtnx.</script>",
"e": 3626,
"s": 3236,
"text": null
},
{
"code": null,
"e": 3629,
"s": 3626,
"text": "21"
},
{
"code": null,
"e": 3674,
"s": 3631,
"text": "Time Complexity: O(1)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 3687,
"s": 3674,
"text": "prerna saini"
},
{
"code": null,
"e": 3695,
"s": 3687,
"text": "ankthon"
},
{
"code": null,
"e": 3701,
"s": 3695,
"text": "jit_t"
},
{
"code": null,
"e": 3707,
"s": 3701,
"text": "ukasp"
},
{
"code": null,
"e": 3714,
"s": 3707,
"text": "rrrtnx"
},
{
"code": null,
"e": 3730,
"s": 3714,
"text": "pushpeshrajdx01"
},
{
"code": null,
"e": 3758,
"s": 3730,
"text": "Graph Minimum Spanning Tree"
},
{
"code": null,
"e": 3763,
"s": 3758,
"text": "math"
},
{
"code": null,
"e": 3785,
"s": 3763,
"text": "Minimum Spanning Tree"
},
{
"code": null,
"e": 3791,
"s": 3785,
"text": "Graph"
},
{
"code": null,
"e": 3797,
"s": 3791,
"text": "Graph"
}
]
|
How to check an HTML element is empty using jQuery ? | 03 Aug, 2021
Given an HTML document and select an element from the HTML document and check that element is empty or not. There are two methods used to solve this problem which are discussed below:
Method 1: Using the “:empty” selector: The element to be checked using is() method. The is() method is used to check if one of the selected elements matches to the selector element. This method can be used on this element to test if it is empty by using “:empty” selector. The “:empty” selector is used to select all the elements that have no children. It will return true if the element is empty, otherwise, return false.
Syntax:
$('#elementSelector').is(':empty')
Example:
<!DOCTYPE html><html> <head> <title> How to check an HTML element is empty using jQuery ? </title> <script src= "https://code.jquery.com/jquery-3.3.1.min.js"> </script> <style> #empty { background-color: green; height: 50px; border: solid; } #not-empty { background-color: lightgreen; height: 50px; border: solid; text-align: center; } </style></head> <body> <h1 style="color: green"> GeeksForGeeks </h1> <b> How to check if an HTML element is empty using jQuery? </b> <p> Click on the button to check if the paragraph elements are empty. </p> <p>The div below is empty.</p> <div id="empty"></div> <p>The div below is not empty.</p> <div id="not-empty">This element has something!</div> <p> First div is empty: <span class="output1"></span> </p> <p> Second div element is empty: <span class="output2"></span> </p> <button onclick="checkifEmpty()"> Check if empty </button> <script> function checkifEmpty() { if ($('#empty').is(':empty')) { document.querySelector('.output1').textContent = true; } else { document.querySelector('.output1').textContent = false; } if ($('#not-empty').is(':empty')) { document.querySelector('.output2').textContent = true; } else { document.querySelector('.output2').textContent = false; } }; </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
Method 2: Using the length property: The length property is used on this element to determine its length. It finds the number of object in a jQuery element. A length of 0 means the element has no other elements in it. Any value other than 0 means that some element is present. This can be used to check if an element is empty or not.
Syntax:
$('#elementSelector').length
Example:
<!DOCTYPE html><html> <head> <title> How to check if an HTML element is empty using jQuery? </title> <script src= "https://code.jquery.com/jquery-3.3.1.min.js"> </script> <style> #empty { background-color: green; height: 50px; border: solid; } #not-empty { background-color: lightgreen; height: 50px; border: solid; text-align: center; } </style></head> <body> <h1 style="color: green"> GeeksForGeeks </h1> <b> How to check if an HTML element is empty using jQuery? </b> <p> Click on the button to check if the paragraph elements are empty. </p> <p>The div below is empty.</p> <div id="empty"></div> <p>The div below is not empty.</p> <div id="not-empty"> This element has something! </div> <p> First div is empty: <span class="output1"></span> </p> <p> Second div element is empty: <span class="output2"></span> </p> <button onclick="checkifEmpty()"> Check if empty </button> <script> function checkifEmpty() { if ($('#empty').length) { document.querySelector('.output1').textContent = true; } else { document.querySelector('.output1').textContent = false; } if ($('#non-empty').length) { document.querySelector('.output2').textContent = true; } else { document.querySelector('.output2').textContent = false; } }; </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.
jQuery-Misc
Picked
JQuery
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Form validation using jQuery
jQuery | children() with Examples
Scroll to the top of the page using JavaScript/jQuery
How to Dynamically Add/Remove Table Rows using jQuery ?
How to get the value in an input text box using jQuery ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Aug, 2021"
},
{
"code": null,
"e": 212,
"s": 28,
"text": "Given an HTML document and select an element from the HTML document and check that element is empty or not. There are two methods used to solve this problem which are discussed below:"
},
{
"code": null,
"e": 635,
"s": 212,
"text": "Method 1: Using the “:empty” selector: The element to be checked using is() method. The is() method is used to check if one of the selected elements matches to the selector element. This method can be used on this element to test if it is empty by using “:empty” selector. The “:empty” selector is used to select all the elements that have no children. It will return true if the element is empty, otherwise, return false."
},
{
"code": null,
"e": 643,
"s": 635,
"text": "Syntax:"
},
{
"code": null,
"e": 678,
"s": 643,
"text": "$('#elementSelector').is(':empty')"
},
{
"code": null,
"e": 687,
"s": 678,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to check an HTML element is empty using jQuery ? </title> <script src= \"https://code.jquery.com/jquery-3.3.1.min.js\"> </script> <style> #empty { background-color: green; height: 50px; border: solid; } #not-empty { background-color: lightgreen; height: 50px; border: solid; text-align: center; } </style></head> <body> <h1 style=\"color: green\"> GeeksForGeeks </h1> <b> How to check if an HTML element is empty using jQuery? </b> <p> Click on the button to check if the paragraph elements are empty. </p> <p>The div below is empty.</p> <div id=\"empty\"></div> <p>The div below is not empty.</p> <div id=\"not-empty\">This element has something!</div> <p> First div is empty: <span class=\"output1\"></span> </p> <p> Second div element is empty: <span class=\"output2\"></span> </p> <button onclick=\"checkifEmpty()\"> Check if empty </button> <script> function checkifEmpty() { if ($('#empty').is(':empty')) { document.querySelector('.output1').textContent = true; } else { document.querySelector('.output1').textContent = false; } if ($('#not-empty').is(':empty')) { document.querySelector('.output2').textContent = true; } else { document.querySelector('.output2').textContent = false; } }; </script></body> </html> ",
"e": 2458,
"s": 687,
"text": null
},
{
"code": null,
"e": 2466,
"s": 2458,
"text": "Output:"
},
{
"code": null,
"e": 2494,
"s": 2466,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 2521,
"s": 2494,
"text": "After clicking the button:"
},
{
"code": null,
"e": 2855,
"s": 2521,
"text": "Method 2: Using the length property: The length property is used on this element to determine its length. It finds the number of object in a jQuery element. A length of 0 means the element has no other elements in it. Any value other than 0 means that some element is present. This can be used to check if an element is empty or not."
},
{
"code": null,
"e": 2863,
"s": 2855,
"text": "Syntax:"
},
{
"code": null,
"e": 2892,
"s": 2863,
"text": "$('#elementSelector').length"
},
{
"code": null,
"e": 2901,
"s": 2892,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to check if an HTML element is empty using jQuery? </title> <script src= \"https://code.jquery.com/jquery-3.3.1.min.js\"> </script> <style> #empty { background-color: green; height: 50px; border: solid; } #not-empty { background-color: lightgreen; height: 50px; border: solid; text-align: center; } </style></head> <body> <h1 style=\"color: green\"> GeeksForGeeks </h1> <b> How to check if an HTML element is empty using jQuery? </b> <p> Click on the button to check if the paragraph elements are empty. </p> <p>The div below is empty.</p> <div id=\"empty\"></div> <p>The div below is not empty.</p> <div id=\"not-empty\"> This element has something! </div> <p> First div is empty: <span class=\"output1\"></span> </p> <p> Second div element is empty: <span class=\"output2\"></span> </p> <button onclick=\"checkifEmpty()\"> Check if empty </button> <script> function checkifEmpty() { if ($('#empty').length) { document.querySelector('.output1').textContent = true; } else { document.querySelector('.output1').textContent = false; } if ($('#non-empty').length) { document.querySelector('.output2').textContent = true; } else { document.querySelector('.output2').textContent = false; } }; </script></body> </html> ",
"e": 4661,
"s": 2901,
"text": null
},
{
"code": null,
"e": 4669,
"s": 4661,
"text": "Output:"
},
{
"code": null,
"e": 4697,
"s": 4669,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 4724,
"s": 4697,
"text": "After clicking the button:"
},
{
"code": null,
"e": 4992,
"s": 4724,
"text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples."
},
{
"code": null,
"e": 5004,
"s": 4992,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 5011,
"s": 5004,
"text": "Picked"
},
{
"code": null,
"e": 5018,
"s": 5011,
"text": "JQuery"
},
{
"code": null,
"e": 5035,
"s": 5018,
"text": "Web Technologies"
},
{
"code": null,
"e": 5062,
"s": 5035,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 5160,
"s": 5062,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5189,
"s": 5160,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 5223,
"s": 5189,
"text": "jQuery | children() with Examples"
},
{
"code": null,
"e": 5277,
"s": 5223,
"text": "Scroll to the top of the page using JavaScript/jQuery"
},
{
"code": null,
"e": 5333,
"s": 5277,
"text": "How to Dynamically Add/Remove Table Rows using jQuery ?"
},
{
"code": null,
"e": 5390,
"s": 5333,
"text": "How to get the value in an input text box using jQuery ?"
},
{
"code": null,
"e": 5423,
"s": 5390,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 5485,
"s": 5423,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5546,
"s": 5485,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5596,
"s": 5546,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
Node.js authentication using Passportjs and passport-local-mongoose | 14 Oct, 2021
Passport is the authentication middleware for Node. It is designed to serve a singular purpose which is to authenticate requests. It is not practical to store user password as the original string in the database but it is a good practice to hash the password and then store them into the database. But with passport-local-mongoose you don’t have to hash the password using the crypto module, passport-local-mongoose will do everything for you. If you use passport-local-mongoose this module will auto-generate salt and hash fields in the DB. You will not have a field for the password, instead, you will have salt and hash.
Why salting of password is needed
If the user simply hashes their password and if two users in the database have the same password, then they’ll have the same hash. And if any one of the passwords is hacked then the hacker can access every account using the same password because users with the same password will have the same hash fields.So before we hash it, we prepend a unique string. Not a secret, just something unique. so the hash is completely different for every salt.
Steps to perform the operation
First let’s generate an express app, then install the needed modules
> npm install passport passport-local mongoose passport-local-mongoose --save
1.First create a directory structure as below :
--model
----user.js
--route
----user.js
--app.js
2.Create model/user.js file which defines user schema
// importing modulesvar mongoose = require('mongoose');var Schema = mongoose.Schema;var passportLocalMongoose = require('passport-local-mongoose'); var UserSchema = new Schema({ email: {type: String, required:true, unique:true}, username : {type: String, unique: true, required:true},}); // plugin for passport-local-mongooseUserSchema.plugin(passportLocalMongoose); // export userschema module.exports = mongoose.model("User", UserSchema);
Note that here in this schema we did not add any field for password unlike we do normally. This is because passport-local-mongoose doesn’t need it. Here we did not add any methods to hash our password or to compare our passwords as we do normally for authentication because passport-local-mongoose will do all that for us.
3.Configure Passport/Passport-Local in app.js :
In app.js first, you have to initialize the passport
app.use(passport.initialize());app.use(passport.session());
The passport will maintain persistent login sessions. In order for persistent sessions to work in the passport, the authenticated user must be serialized to the session and deserialized when subsequent requests are made. With passport-local-mongoose it is
passport.serializeUser(User.serializeUser());passport.deserializeUser(User.deserializeUser());
The serialize and deserialize code can be slightly different if you are not using passport-local-mongoose with the passport.
Now we have to define the strategies for passport. For passport local mongoose the code is
const User = require('./models/user'); const LocalStrategy = require('passport-local').Strategy;passport.use(new LocalStrategy(User.authenticate()));
If you are using only passport without passport-local-mongoose the local strategy can be quite different i.e.) you will have to write code to compare passwords and all. Here just this 2 lines are enough
4.Create route/user.js file :
First import the user-schema along with other necessary modules
// importing modules const express = require('express'); const router = express.Router(); // importing User Schema const User = require('../model/user');
5.For registering :
Now for registering the code should be
router.post('/login', function(req, res) { Users=new User({email: req.body.email, username : req.body.username}); User.register(Users, req.body.password, function(err, user) { if (err) { res.json({success:false, message:"Your account could not be saved. Error: ", err}) }else{ res.json({success: true, message: "Your account has been saved"}) } });});
See in the above code we did not define our password in New user. Instead, we use the password with the User.Register() which is a passport-local-mongoose function. Now if you check your database for your saved user, it will be like below
{
"_id" : ObjectId("5ca8b66535947f4c1e93c4f1"),
"username" : "username you gave",
"email" : "email you gave",
"salt" : "4c8f6e009c4523b23553d9479e25254b266c3b7dd2dbc6d4aaace01851c9687c",
"hash" : "337de0df58406b25499b18f54229b9dd595b70e998fd02c7866d06d2a6b25870d23650
cdda829974a46e3166e535f1aeb6bc7ef182565009b1dcf57a64205b5548f6974b77c2e3a3c6aec5360d
55f9fcd3ffd6fb99dce21aab021aced72881d3720f6a0975bfece4922282bb748e0412955e0afa2fb8c9
f5055cac0fb01a4a2288af2ce2a6563ed9b47852727749c7fe031b6b7fbb726196dbdfeeb6766d5cba6a
055f66eeacce685daef8b6c1aed0108df511c92d49150efb6473ee71c5149dd06bfb4f73cb60f9815af0
1e02fde8d8ed822bb3a55f040237cf80de0b1534de6bbafcb53f882c6eb03de4b4aa307828974eb51261
661efb5155e68ad0e593c0f5fab7d690c2257df4369e9d5ac7e2fc93b5b014260c6f8fbb01034b3f85ec
f11e086e9bf860f959d0e2104a1f825d286c99d3fc6f62505d1fde8601345c699ea08dcc071e5547835c
16957d3830998a10762ebd143dc557d6a96e4b88312e1e4c51622fef3939656c992508e47ddc148696df
3152af76286d636d4814a0dc608f72cd507c617feb77cbba36c5b017492df5f28a7a3f3b7881caf6fb4a
9d6231eca6edbeec4eb1436f1e45c27b9c2bfceccf3a9b42840f40c65fe499091ba6ebeb764b5d815a43
d73a888fdb58f821fbe5f7d92e20ff8d7c98e8164b4f10d5528fddbcc7737fd21b12d571355cc605eb36
21f5f266f8e38683deb05a6de43114",
"__v" : 0
}
You can notice that there is no field for password at all, instead passport-local-mongoose created salt and hash for you, that too you didn’t have to define salt and hash fields in your schema. Passport-local-mongoose will keep your username unique, ie if username already exist it will give “UserExistsError”.
5.For login :
Now for login
userController.doLogin = function(req, res) { if(!req.body.username){ res.json({success: false, message: "Username was not given"}) } else { if(!req.body.password){ res.json({success: false, message: "Password was not given"}) }else{ passport.authenticate('local', function (err, user, info) { if(err){ res.json({success: false, message: err}) } else{ if (! user) { res.json({success: false, message: 'username or password incorrect'}) } else{ req.login(user, function(err){ if(err){ res.json({success: false, message: err}) }else{ const token = jwt.sign({userId : user._id, username:user.username}, secretkey, {expiresIn: '24h'}) res.json({success:true, message:"Authentication successful", token: token }); } }) } } })(req, res); } }};
6.Resetting or changing passwords :
You can reset or change passwords using 2 simple functions in passport-local-mongoose. They are setPassword function and changePassword functions. Normally setPassword is used when the user forgot the password and changePassword is used when the user wants to change the password.
for setPassword code is
// user is your result from userschema using mongoose id
user.setPassword(req.body.password, function(err, user){ ..
For changePassword
// user is your result from userschema using mongoose id
user.changePassword(req.body.oldpassword, req.body.newpassword, function(err) ...
You can directly call them in your router files
nidhi_biet
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
JWT Authentication with Node.js
Installation of Node.js on Windows
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n14 Oct, 2021"
},
{
"code": null,
"e": 678,
"s": 54,
"text": "Passport is the authentication middleware for Node. It is designed to serve a singular purpose which is to authenticate requests. It is not practical to store user password as the original string in the database but it is a good practice to hash the password and then store them into the database. But with passport-local-mongoose you don’t have to hash the password using the crypto module, passport-local-mongoose will do everything for you. If you use passport-local-mongoose this module will auto-generate salt and hash fields in the DB. You will not have a field for the password, instead, you will have salt and hash."
},
{
"code": null,
"e": 712,
"s": 678,
"text": "Why salting of password is needed"
},
{
"code": null,
"e": 1157,
"s": 712,
"text": "If the user simply hashes their password and if two users in the database have the same password, then they’ll have the same hash. And if any one of the passwords is hacked then the hacker can access every account using the same password because users with the same password will have the same hash fields.So before we hash it, we prepend a unique string. Not a secret, just something unique. so the hash is completely different for every salt."
},
{
"code": null,
"e": 1188,
"s": 1157,
"text": "Steps to perform the operation"
},
{
"code": null,
"e": 1257,
"s": 1188,
"text": "First let’s generate an express app, then install the needed modules"
},
{
"code": null,
"e": 1336,
"s": 1257,
"text": "> npm install passport passport-local mongoose passport-local-mongoose --save\n"
},
{
"code": null,
"e": 1384,
"s": 1336,
"text": "1.First create a directory structure as below :"
},
{
"code": null,
"e": 1434,
"s": 1384,
"text": "--model\n----user.js\n--route\n----user.js\n--app.js\n"
},
{
"code": null,
"e": 1488,
"s": 1434,
"text": "2.Create model/user.js file which defines user schema"
},
{
"code": "// importing modulesvar mongoose = require('mongoose');var Schema = mongoose.Schema;var passportLocalMongoose = require('passport-local-mongoose'); var UserSchema = new Schema({ email: {type: String, required:true, unique:true}, username : {type: String, unique: true, required:true},}); // plugin for passport-local-mongooseUserSchema.plugin(passportLocalMongoose); // export userschema module.exports = mongoose.model(\"User\", UserSchema);",
"e": 1943,
"s": 1488,
"text": null
},
{
"code": null,
"e": 2266,
"s": 1943,
"text": "Note that here in this schema we did not add any field for password unlike we do normally. This is because passport-local-mongoose doesn’t need it. Here we did not add any methods to hash our password or to compare our passwords as we do normally for authentication because passport-local-mongoose will do all that for us."
},
{
"code": null,
"e": 2314,
"s": 2266,
"text": "3.Configure Passport/Passport-Local in app.js :"
},
{
"code": null,
"e": 2367,
"s": 2314,
"text": "In app.js first, you have to initialize the passport"
},
{
"code": "app.use(passport.initialize());app.use(passport.session());",
"e": 2427,
"s": 2367,
"text": null
},
{
"code": null,
"e": 2683,
"s": 2427,
"text": "The passport will maintain persistent login sessions. In order for persistent sessions to work in the passport, the authenticated user must be serialized to the session and deserialized when subsequent requests are made. With passport-local-mongoose it is"
},
{
"code": "passport.serializeUser(User.serializeUser());passport.deserializeUser(User.deserializeUser());",
"e": 2778,
"s": 2683,
"text": null
},
{
"code": null,
"e": 2903,
"s": 2778,
"text": "The serialize and deserialize code can be slightly different if you are not using passport-local-mongoose with the passport."
},
{
"code": null,
"e": 2994,
"s": 2903,
"text": "Now we have to define the strategies for passport. For passport local mongoose the code is"
},
{
"code": "const User = require('./models/user'); const LocalStrategy = require('passport-local').Strategy;passport.use(new LocalStrategy(User.authenticate()));",
"e": 3145,
"s": 2994,
"text": null
},
{
"code": null,
"e": 3348,
"s": 3145,
"text": "If you are using only passport without passport-local-mongoose the local strategy can be quite different i.e.) you will have to write code to compare passwords and all. Here just this 2 lines are enough"
},
{
"code": null,
"e": 3378,
"s": 3348,
"text": "4.Create route/user.js file :"
},
{
"code": null,
"e": 3442,
"s": 3378,
"text": "First import the user-schema along with other necessary modules"
},
{
"code": "// importing modules const express = require('express'); const router = express.Router(); // importing User Schema const User = require('../model/user');",
"e": 3600,
"s": 3442,
"text": null
},
{
"code": null,
"e": 3620,
"s": 3600,
"text": "5.For registering :"
},
{
"code": null,
"e": 3659,
"s": 3620,
"text": "Now for registering the code should be"
},
{
"code": "router.post('/login', function(req, res) { Users=new User({email: req.body.email, username : req.body.username}); User.register(Users, req.body.password, function(err, user) { if (err) { res.json({success:false, message:\"Your account could not be saved. Error: \", err}) }else{ res.json({success: true, message: \"Your account has been saved\"}) } });});",
"e": 4129,
"s": 3659,
"text": null
},
{
"code": null,
"e": 4368,
"s": 4129,
"text": "See in the above code we did not define our password in New user. Instead, we use the password with the User.Register() which is a passport-local-mongoose function. Now if you check your database for your saved user, it will be like below"
},
{
"code": null,
"e": 5641,
"s": 4368,
"text": "{\n \"_id\" : ObjectId(\"5ca8b66535947f4c1e93c4f1\"),\n \"username\" : \"username you gave\",\n \"email\" : \"email you gave\",\n \"salt\" : \"4c8f6e009c4523b23553d9479e25254b266c3b7dd2dbc6d4aaace01851c9687c\",\n \"hash\" : \"337de0df58406b25499b18f54229b9dd595b70e998fd02c7866d06d2a6b25870d23650\ncdda829974a46e3166e535f1aeb6bc7ef182565009b1dcf57a64205b5548f6974b77c2e3a3c6aec5360d\n55f9fcd3ffd6fb99dce21aab021aced72881d3720f6a0975bfece4922282bb748e0412955e0afa2fb8c9\nf5055cac0fb01a4a2288af2ce2a6563ed9b47852727749c7fe031b6b7fbb726196dbdfeeb6766d5cba6a\n055f66eeacce685daef8b6c1aed0108df511c92d49150efb6473ee71c5149dd06bfb4f73cb60f9815af0\n1e02fde8d8ed822bb3a55f040237cf80de0b1534de6bbafcb53f882c6eb03de4b4aa307828974eb51261\n661efb5155e68ad0e593c0f5fab7d690c2257df4369e9d5ac7e2fc93b5b014260c6f8fbb01034b3f85ec\nf11e086e9bf860f959d0e2104a1f825d286c99d3fc6f62505d1fde8601345c699ea08dcc071e5547835c\n16957d3830998a10762ebd143dc557d6a96e4b88312e1e4c51622fef3939656c992508e47ddc148696df\n3152af76286d636d4814a0dc608f72cd507c617feb77cbba36c5b017492df5f28a7a3f3b7881caf6fb4a\n9d6231eca6edbeec4eb1436f1e45c27b9c2bfceccf3a9b42840f40c65fe499091ba6ebeb764b5d815a43\nd73a888fdb58f821fbe5f7d92e20ff8d7c98e8164b4f10d5528fddbcc7737fd21b12d571355cc605eb36\n21f5f266f8e38683deb05a6de43114\",\n \"__v\" : 0\n}\n"
},
{
"code": null,
"e": 5952,
"s": 5641,
"text": "You can notice that there is no field for password at all, instead passport-local-mongoose created salt and hash for you, that too you didn’t have to define salt and hash fields in your schema. Passport-local-mongoose will keep your username unique, ie if username already exist it will give “UserExistsError”."
},
{
"code": null,
"e": 5966,
"s": 5952,
"text": "5.For login :"
},
{
"code": null,
"e": 5980,
"s": 5966,
"text": "Now for login"
},
{
"code": "userController.doLogin = function(req, res) { if(!req.body.username){ res.json({success: false, message: \"Username was not given\"}) } else { if(!req.body.password){ res.json({success: false, message: \"Password was not given\"}) }else{ passport.authenticate('local', function (err, user, info) { if(err){ res.json({success: false, message: err}) } else{ if (! user) { res.json({success: false, message: 'username or password incorrect'}) } else{ req.login(user, function(err){ if(err){ res.json({success: false, message: err}) }else{ const token = jwt.sign({userId : user._id, username:user.username}, secretkey, {expiresIn: '24h'}) res.json({success:true, message:\"Authentication successful\", token: token }); } }) } } })(req, res); } }};",
"e": 6989,
"s": 5980,
"text": null
},
{
"code": null,
"e": 7025,
"s": 6989,
"text": "6.Resetting or changing passwords :"
},
{
"code": null,
"e": 7306,
"s": 7025,
"text": "You can reset or change passwords using 2 simple functions in passport-local-mongoose. They are setPassword function and changePassword functions. Normally setPassword is used when the user forgot the password and changePassword is used when the user wants to change the password."
},
{
"code": null,
"e": 7330,
"s": 7306,
"text": "for setPassword code is"
},
{
"code": null,
"e": 7449,
"s": 7330,
"text": "// user is your result from userschema using mongoose id\n user.setPassword(req.body.password, function(err, user){ ..\n"
},
{
"code": null,
"e": 7468,
"s": 7449,
"text": "For changePassword"
},
{
"code": null,
"e": 7610,
"s": 7468,
"text": "// user is your result from userschema using mongoose id\n user.changePassword(req.body.oldpassword, req.body.newpassword, function(err) ...\n"
},
{
"code": null,
"e": 7658,
"s": 7610,
"text": "You can directly call them in your router files"
},
{
"code": null,
"e": 7669,
"s": 7658,
"text": "nidhi_biet"
},
{
"code": null,
"e": 7677,
"s": 7669,
"text": "Node.js"
},
{
"code": null,
"e": 7694,
"s": 7677,
"text": "Web Technologies"
},
{
"code": null,
"e": 7792,
"s": 7694,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7822,
"s": 7792,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 7876,
"s": 7822,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 7916,
"s": 7876,
"text": "Mongoose | findByIdAndUpdate() Function"
},
{
"code": null,
"e": 7948,
"s": 7916,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 7983,
"s": 7948,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 8045,
"s": 7983,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 8106,
"s": 8045,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 8156,
"s": 8106,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 8199,
"s": 8156,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
What is Latency? | 13 Sep, 2021
What is Latency?
Being simple latency means whenever you have given input to the system and the total time period it takes to give output so that particular time period/interval is known as latency.
Actually, latency is the in-between handling time of computers, as some of you may think that whenever some system connects with another system it happens directly but no it isn’t, the signal or data follows the proper traceroute for reaching its final destination.
Nowadays fiber optic cables are used for transmitting the signals/data from one place to another with the speed of light but obviously before reaching to the final destiny the data/signal has to pass from many checkpoints or posts and follow a proper traceroute so it takes some time to get respond from the receiver and that total round of time is known as latency.
If you want to know the fastest possible network connection you could have from one place to another then we will suppose light as a medium because light just takes 100milli seconds(approx.) to take a round of earth. So according to the data if you let light as a medium then you can send 20 packets per second across the other sides of the world.
What is Ping?
To make you all more clear with that we will use ping here, ping is nothing just a concept or a solution to check the value of latency generating there in the connection between the systems. Ping checks the value of latency by just sending 4 packets of data to the address provided by the user to check the ping and then calculates the total time when the response comes to it, that total time is called latency.
Ping is checked up for windows from command prompt and for MAC from terminal using the syntax “ping<space>website name”.
Example –Let’s take a real-world example, so here we will ping up 2 websites one near me that is in India named “Tata Consultancy Service” and one overseas that is “Goldman Sachs”, let’s see what happens.
TCS ping with respect to UP(India)
Goldman Sachs ping with respect to UP(India)
Now as you can observe that the maximum latency for “Tata Consultancy Service” is coming up to 44milli seconds and for “Goldman Sachs” the maximum latency is 53milli seconds, this is because of the location from where the ping is being originated to be measured. You can also say that the ping of any particular website is directly proportional to the distance.
Some common reasons for latency :
Transmission Medium –The material/nature of the medium through which data or signal is to be transmitted affects the latency.Low Memory Space –The low memory space creates a problem for OS for maintaining the RAM needs.Propagation –The amount of time signals takes to transmit the data from one source to another.Multiple Routers –As I have discussed before that data travels a full traceroute means it travels from one router to another router that increases the latency, etc.
Transmission Medium –The material/nature of the medium through which data or signal is to be transmitted affects the latency.
Low Memory Space –The low memory space creates a problem for OS for maintaining the RAM needs.
Propagation –The amount of time signals takes to transmit the data from one source to another.
Multiple Routers –As I have discussed before that data travels a full traceroute means it travels from one router to another router that increases the latency, etc.
Methods to reduce latency are as follows :Increase Internet Speed & Bandwidth –To run the internet smoothly, you’ll need a network connection speed of at least 15mbps. Now, when it comes to bandwidth, if other members are playing online games, live streaming, or video calling, it will have an impact on your performance, so you’ll need a lot of it to handle everything.
HTTP/2 –It reduces the amount of time it takes for a signal to travel between the receiver and the sender by reducing the signal’s path or route.CDN –If you use a CDN, it will cache all of the data or resources near the user from around the world, allowing signals to retrieve data from nearby resources rather than going to the origin.Be close to your router –Signals flow wirelessly from one router to the next, but they can be interrupted or resisted by objects such as walls, furniture, and so on. Place your system in an area of your home with good connectivity.Upgrade Broadband Package –Sometimes the broadband connection provider is a problem, so if you find a better deal than the one you’re currently using, switch.Restart Your Router –If your router has been on for a long time, restart it to refresh it and relieve the constant strain on it.Close Background Running Application –If you’re using Amazon Prime, Netflix, Hotstar, YouTube, or live streaming, turn them off because they significantly slow down your system’s ping rate.Play Games On Local Server –To ensure good connectivity, always try to play online world games on your local servers.Use Ethernet Cable –Using a wired connection for internet connectivity is always a good option, but you will be the only one who can use the internet; others will be unable to do so. Actually, it’s beneficial because the signals have access to your system’s exact clear path through the wire, which means they don’t have to travel everywhere and encounter obstacles, reducing latency.
HTTP/2 –It reduces the amount of time it takes for a signal to travel between the receiver and the sender by reducing the signal’s path or route.
CDN –If you use a CDN, it will cache all of the data or resources near the user from around the world, allowing signals to retrieve data from nearby resources rather than going to the origin.
Be close to your router –Signals flow wirelessly from one router to the next, but they can be interrupted or resisted by objects such as walls, furniture, and so on. Place your system in an area of your home with good connectivity.
Upgrade Broadband Package –Sometimes the broadband connection provider is a problem, so if you find a better deal than the one you’re currently using, switch.
Restart Your Router –If your router has been on for a long time, restart it to refresh it and relieve the constant strain on it.
Close Background Running Application –If you’re using Amazon Prime, Netflix, Hotstar, YouTube, or live streaming, turn them off because they significantly slow down your system’s ping rate.
Play Games On Local Server –To ensure good connectivity, always try to play online world games on your local servers.
Use Ethernet Cable –Using a wired connection for internet connectivity is always a good option, but you will be the only one who can use the internet; others will be unable to do so. Actually, it’s beneficial because the signals have access to your system’s exact clear path through the wire, which means they don’t have to travel everywhere and encounter obstacles, reducing latency.
There are numerous other tricks and methods for reducing latency that you can find on YouTube and try at your own risk.
Picked
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Sep, 2021"
},
{
"code": null,
"e": 45,
"s": 28,
"text": "What is Latency?"
},
{
"code": null,
"e": 227,
"s": 45,
"text": "Being simple latency means whenever you have given input to the system and the total time period it takes to give output so that particular time period/interval is known as latency."
},
{
"code": null,
"e": 493,
"s": 227,
"text": "Actually, latency is the in-between handling time of computers, as some of you may think that whenever some system connects with another system it happens directly but no it isn’t, the signal or data follows the proper traceroute for reaching its final destination."
},
{
"code": null,
"e": 860,
"s": 493,
"text": "Nowadays fiber optic cables are used for transmitting the signals/data from one place to another with the speed of light but obviously before reaching to the final destiny the data/signal has to pass from many checkpoints or posts and follow a proper traceroute so it takes some time to get respond from the receiver and that total round of time is known as latency."
},
{
"code": null,
"e": 1208,
"s": 860,
"text": "If you want to know the fastest possible network connection you could have from one place to another then we will suppose light as a medium because light just takes 100milli seconds(approx.) to take a round of earth. So according to the data if you let light as a medium then you can send 20 packets per second across the other sides of the world."
},
{
"code": null,
"e": 1222,
"s": 1208,
"text": "What is Ping?"
},
{
"code": null,
"e": 1635,
"s": 1222,
"text": "To make you all more clear with that we will use ping here, ping is nothing just a concept or a solution to check the value of latency generating there in the connection between the systems. Ping checks the value of latency by just sending 4 packets of data to the address provided by the user to check the ping and then calculates the total time when the response comes to it, that total time is called latency."
},
{
"code": null,
"e": 1756,
"s": 1635,
"text": "Ping is checked up for windows from command prompt and for MAC from terminal using the syntax “ping<space>website name”."
},
{
"code": null,
"e": 1961,
"s": 1756,
"text": "Example –Let’s take a real-world example, so here we will ping up 2 websites one near me that is in India named “Tata Consultancy Service” and one overseas that is “Goldman Sachs”, let’s see what happens."
},
{
"code": null,
"e": 1996,
"s": 1961,
"text": "TCS ping with respect to UP(India)"
},
{
"code": null,
"e": 2042,
"s": 1996,
"text": "Goldman Sachs ping with respect to UP(India) "
},
{
"code": null,
"e": 2405,
"s": 2042,
"text": "Now as you can observe that the maximum latency for “Tata Consultancy Service” is coming up to 44milli seconds and for “Goldman Sachs” the maximum latency is 53milli seconds, this is because of the location from where the ping is being originated to be measured. You can also say that the ping of any particular website is directly proportional to the distance. "
},
{
"code": null,
"e": 2439,
"s": 2405,
"text": "Some common reasons for latency :"
},
{
"code": null,
"e": 2917,
"s": 2439,
"text": "Transmission Medium –The material/nature of the medium through which data or signal is to be transmitted affects the latency.Low Memory Space –The low memory space creates a problem for OS for maintaining the RAM needs.Propagation –The amount of time signals takes to transmit the data from one source to another.Multiple Routers –As I have discussed before that data travels a full traceroute means it travels from one router to another router that increases the latency, etc."
},
{
"code": null,
"e": 3043,
"s": 2917,
"text": "Transmission Medium –The material/nature of the medium through which data or signal is to be transmitted affects the latency."
},
{
"code": null,
"e": 3138,
"s": 3043,
"text": "Low Memory Space –The low memory space creates a problem for OS for maintaining the RAM needs."
},
{
"code": null,
"e": 3233,
"s": 3138,
"text": "Propagation –The amount of time signals takes to transmit the data from one source to another."
},
{
"code": null,
"e": 3398,
"s": 3233,
"text": "Multiple Routers –As I have discussed before that data travels a full traceroute means it travels from one router to another router that increases the latency, etc."
},
{
"code": null,
"e": 3769,
"s": 3398,
"text": "Methods to reduce latency are as follows :Increase Internet Speed & Bandwidth –To run the internet smoothly, you’ll need a network connection speed of at least 15mbps. Now, when it comes to bandwidth, if other members are playing online games, live streaming, or video calling, it will have an impact on your performance, so you’ll need a lot of it to handle everything."
},
{
"code": null,
"e": 5313,
"s": 3769,
"text": "HTTP/2 –It reduces the amount of time it takes for a signal to travel between the receiver and the sender by reducing the signal’s path or route.CDN –If you use a CDN, it will cache all of the data or resources near the user from around the world, allowing signals to retrieve data from nearby resources rather than going to the origin.Be close to your router –Signals flow wirelessly from one router to the next, but they can be interrupted or resisted by objects such as walls, furniture, and so on. Place your system in an area of your home with good connectivity.Upgrade Broadband Package –Sometimes the broadband connection provider is a problem, so if you find a better deal than the one you’re currently using, switch.Restart Your Router –If your router has been on for a long time, restart it to refresh it and relieve the constant strain on it.Close Background Running Application –If you’re using Amazon Prime, Netflix, Hotstar, YouTube, or live streaming, turn them off because they significantly slow down your system’s ping rate.Play Games On Local Server –To ensure good connectivity, always try to play online world games on your local servers.Use Ethernet Cable –Using a wired connection for internet connectivity is always a good option, but you will be the only one who can use the internet; others will be unable to do so. Actually, it’s beneficial because the signals have access to your system’s exact clear path through the wire, which means they don’t have to travel everywhere and encounter obstacles, reducing latency."
},
{
"code": null,
"e": 5459,
"s": 5313,
"text": "HTTP/2 –It reduces the amount of time it takes for a signal to travel between the receiver and the sender by reducing the signal’s path or route."
},
{
"code": null,
"e": 5651,
"s": 5459,
"text": "CDN –If you use a CDN, it will cache all of the data or resources near the user from around the world, allowing signals to retrieve data from nearby resources rather than going to the origin."
},
{
"code": null,
"e": 5883,
"s": 5651,
"text": "Be close to your router –Signals flow wirelessly from one router to the next, but they can be interrupted or resisted by objects such as walls, furniture, and so on. Place your system in an area of your home with good connectivity."
},
{
"code": null,
"e": 6042,
"s": 5883,
"text": "Upgrade Broadband Package –Sometimes the broadband connection provider is a problem, so if you find a better deal than the one you’re currently using, switch."
},
{
"code": null,
"e": 6171,
"s": 6042,
"text": "Restart Your Router –If your router has been on for a long time, restart it to refresh it and relieve the constant strain on it."
},
{
"code": null,
"e": 6361,
"s": 6171,
"text": "Close Background Running Application –If you’re using Amazon Prime, Netflix, Hotstar, YouTube, or live streaming, turn them off because they significantly slow down your system’s ping rate."
},
{
"code": null,
"e": 6479,
"s": 6361,
"text": "Play Games On Local Server –To ensure good connectivity, always try to play online world games on your local servers."
},
{
"code": null,
"e": 6864,
"s": 6479,
"text": "Use Ethernet Cable –Using a wired connection for internet connectivity is always a good option, but you will be the only one who can use the internet; others will be unable to do so. Actually, it’s beneficial because the signals have access to your system’s exact clear path through the wire, which means they don’t have to travel everywhere and encounter obstacles, reducing latency."
},
{
"code": null,
"e": 6984,
"s": 6864,
"text": "There are numerous other tricks and methods for reducing latency that you can find on YouTube and try at your own risk."
},
{
"code": null,
"e": 6991,
"s": 6984,
"text": "Picked"
},
{
"code": null,
"e": 7009,
"s": 6991,
"text": "Computer Networks"
},
{
"code": null,
"e": 7027,
"s": 7009,
"text": "Computer Networks"
}
]
|
Change one element in the given array to make it an Arithmetic Progression | 30 May, 2022
Given an array which is an original arithmetic progression with one element changed. The task is to make it an arithmetic progression again. If there are many such possible sequences, return any one of them. The length of the array will always be greater than 2. Examples:
Input : arr = [1, 3, 4, 7] Output : arr = [1, 3, 5, 7] The common difference for the arithmetic progression is 2, so the resulting arithmetic progression is [1, 3, 5, 7]. Input : arr = [1, 3, 7] Output : arr = [-1, 3, 7] The common difference can be either 2 or 3 or 4. Hence the resulting array can be either [1, 3, 5], [-1, 3, 7] or [1, 4, 7]. As any one can be chosen, [-1, 3, 7] is returned as the output.
Approach: The key components of an Arithmetic Progression are initial term and the common difference. So our task is to find these two values to know the actual Arithmetic Progression.
If the length of the array is 3, take the common difference as the difference between any two elements.
Otherwise, try to find the common difference using the first four elements.Check if the first three elements are in arithmetic progression using the formula a[1] – a[0] = a[2] – a[1]. If they are in arithmetic progression, the common difference d = a[1] – a[0] and the initial term would be a[0]Check if the 2nd, 3rd and 4th elements are in arithmetic progression using the formula a[2] – a[1] = a[3] – a[2]. If they are in arithmetic progression, the common difference d = a[2] – a[1], which means that the first element has been changed, so initial term is a[0] = a[1] – dIn both of the above cases, we have checked if the first element or fourth element has been changed. If both the cases are false, then it means that first or fourth element was not changed. So the common difference can be taken as d = (a[3] – a[0])/3 and the initial term = a[0]
Check if the first three elements are in arithmetic progression using the formula a[1] – a[0] = a[2] – a[1]. If they are in arithmetic progression, the common difference d = a[1] – a[0] and the initial term would be a[0]
Check if the 2nd, 3rd and 4th elements are in arithmetic progression using the formula a[2] – a[1] = a[3] – a[2]. If they are in arithmetic progression, the common difference d = a[2] – a[1], which means that the first element has been changed, so initial term is a[0] = a[1] – d
In both of the above cases, we have checked if the first element or fourth element has been changed. If both the cases are false, then it means that first or fourth element was not changed. So the common difference can be taken as d = (a[3] – a[0])/3 and the initial term = a[0]
Print all the elements using the initial term and common difference.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to change one element of an array such// that the resulting array is in arithmetic progression.#include <bits/stdc++.h>using namespace std; // Finds the initial term and common difference and// prints the resulting sequence.void makeAP(int arr[], int n){ int initial_term, common_difference; if (n == 3) { common_difference = arr[2] - arr[1]; initial_term = arr[1] - common_difference; } else if ((arr[1] - arr[0]) == arr[2] - arr[1]) { // Check if the first three elements are in // arithmetic progression initial_term = arr[0]; common_difference = arr[1] - arr[0]; } else if ((arr[2] - arr[1]) == (arr[3] - arr[2])) { // Check if the first element is not // in arithmetic progression common_difference = arr[2] - arr[1]; initial_term = arr[1] - common_difference; } else { // The first and fourth element are // in arithmetic progression common_difference = (arr[3] - arr[0]) / 3; initial_term = arr[0]; } // Print the arithmetic progression for (int i = 0; i < n; i++) cout << initial_term + (i * common_difference) << " "; cout << endl;} // Driver Programint main(){ int arr[] = { 1, 3, 7 }; int n = sizeof(arr) / sizeof(arr[0]); makeAP(arr, n); return 0;}
// Java program to change one element of an array such// that the resulting array is in arithmetic progression.import java.util.Arrays; class AP { static void makeAP(int arr[], int n) { int initial_term, common_difference; // Finds the initial term and common difference and // prints the resulting array. if (n == 3) { common_difference = arr[2] - arr[1]; initial_term = arr[1] - common_difference; } else if ((arr[1] - arr[0]) == arr[2] - arr[1]) { // Check if the first three elements are in // arithmetic progression initial_term = arr[0]; common_difference = arr[1] - arr[0]; } else if ((arr[2] - arr[1]) == (arr[3] - arr[2])) { // Check if the first element is not // in arithmetic progression common_difference = arr[2] - arr[1]; initial_term = arr[1] - common_difference; } else { // The first and fourth element are // in arithmetic progression common_difference = (arr[3] - arr[0]) / 3; initial_term = arr[0]; } // Print the arithmetic progression for (int i = 0; i < n; i++) System.out.print(initial_term + (i * common_difference) + " "); System.out.println(); } // Driver code public static void main(String[] args) { int arr[] = { 1, 3, 7 }; int n = arr.length; makeAP(arr, n); }}
# Python program to change one element of an array such# that the resulting array is in arithmetic progression.def makeAP(arr, n): initial_term, common_difference = 0, 0 if (n == 3): common_difference = arr[2] - arr[1] initial_term = arr[1] - common_difference elif((arr[1] - arr[0]) == arr[2] - arr[1]): # Check if the first three elements are in # arithmetic progression initial_term = arr[0] common_difference = arr[1] - arr[0] elif((arr[2] - arr[1]) == (arr[3] - arr[2])): # Check if the first element is not # in arithmetic progression common_difference = arr[2] - arr[1] initial_term = arr[1] - common_difference else: # The first and fourth element are # in arithmetic progression common_difference = (arr[3] - arr[0]) / 3 initial_term = arr[0] # Print the arithmetic progression for i in range(n): print(int(initial_term+ (i * common_difference)), end = " ") print() # Driver codearr = [1, 3, 7]n = len(arr)makeAP(arr, n)
// C# program to change one element of an array such// that the resulting array is in arithmetic progression.using System; public class AP{ static void makeAP(int []arr, int n) { int initial_term, common_difference; // Finds the initial term and common difference and // prints the resulting array. if (n == 3) { common_difference = arr[2] - arr[1]; initial_term = arr[1] - common_difference; } else if ((arr[1] - arr[0]) == arr[2] - arr[1]) { // Check if the first three elements are in // arithmetic progression initial_term = arr[0]; common_difference = arr[1] - arr[0]; } else if ((arr[2] - arr[1]) == (arr[3] - arr[2])) { // Check if the first element is not // in arithmetic progression common_difference = arr[2] - arr[1]; initial_term = arr[1] - common_difference; } else { // The first and fourth element are // in arithmetic progression common_difference = (arr[3] - arr[0]) / 3; initial_term = arr[0]; } // Print the arithmetic progression for (int i = 0; i < n; i++) Console.Write(initial_term + (i * common_difference) + " "); Console.WriteLine(); } // Driver code public static void Main(String[] args) { int []arr = { 1, 3, 7 }; int n = arr.Length; makeAP(arr, n); }} // This code contributed by Rajput-Ji
<script> // JavaScript program to change one element of an array such// that the resulting array is in arithmetic progression.function makeAP(arr, n){ let initial_term = 0, common_difference = 0 if (n == 3){ common_difference = arr[2] - arr[1] initial_term = arr[1] - common_difference } else if((arr[1] - arr[0]) == arr[2] - arr[1]){ // Check if the first three elements are in // arithmetic progression initial_term = arr[0] common_difference = arr[1] - arr[0] } else if((arr[2] - arr[1]) == (arr[3] - arr[2])){ // Check if the first element is not // in arithmetic progression common_difference = arr[2] - arr[1] initial_term = arr[1] - common_difference } else{ // The first and fourth element are // in arithmetic progression common_difference = Math.floor((arr[3] - arr[0]) / 3) initial_term = arr[0] } // Print the arithmetic progression for(let i=0;i<n;i++){ document.write(initial_term+(i * common_difference)," ") } document.write("</br>")} // Driver codelet arr = [1, 3, 7]let n = arr.lengthmakeAP(arr, n) // This code is contributed by shinjanpatra </script>
-1 3 7
Time Complexity: O(N), where N is the number of elements in the array.
Auxiliary Space: O(1)
Rajput-Ji
shinjanpatra
vansikasharma1329
arithmetic progression
Arrays
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Search, insert and delete in an unsorted array
Window Sliding Technique
Chocolate Distribution Problem
Find duplicates in O(n) time and O(1) extra space | Set 1
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Coin Change | DP-7 | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 May, 2022"
},
{
"code": null,
"e": 325,
"s": 52,
"text": "Given an array which is an original arithmetic progression with one element changed. The task is to make it an arithmetic progression again. If there are many such possible sequences, return any one of them. The length of the array will always be greater than 2. Examples:"
},
{
"code": null,
"e": 735,
"s": 325,
"text": "Input : arr = [1, 3, 4, 7] Output : arr = [1, 3, 5, 7] The common difference for the arithmetic progression is 2, so the resulting arithmetic progression is [1, 3, 5, 7]. Input : arr = [1, 3, 7] Output : arr = [-1, 3, 7] The common difference can be either 2 or 3 or 4. Hence the resulting array can be either [1, 3, 5], [-1, 3, 7] or [1, 4, 7]. As any one can be chosen, [-1, 3, 7] is returned as the output."
},
{
"code": null,
"e": 920,
"s": 735,
"text": "Approach: The key components of an Arithmetic Progression are initial term and the common difference. So our task is to find these two values to know the actual Arithmetic Progression."
},
{
"code": null,
"e": 1024,
"s": 920,
"text": "If the length of the array is 3, take the common difference as the difference between any two elements."
},
{
"code": null,
"e": 1877,
"s": 1024,
"text": "Otherwise, try to find the common difference using the first four elements.Check if the first three elements are in arithmetic progression using the formula a[1] – a[0] = a[2] – a[1]. If they are in arithmetic progression, the common difference d = a[1] – a[0] and the initial term would be a[0]Check if the 2nd, 3rd and 4th elements are in arithmetic progression using the formula a[2] – a[1] = a[3] – a[2]. If they are in arithmetic progression, the common difference d = a[2] – a[1], which means that the first element has been changed, so initial term is a[0] = a[1] – dIn both of the above cases, we have checked if the first element or fourth element has been changed. If both the cases are false, then it means that first or fourth element was not changed. So the common difference can be taken as d = (a[3] – a[0])/3 and the initial term = a[0]"
},
{
"code": null,
"e": 2098,
"s": 1877,
"text": "Check if the first three elements are in arithmetic progression using the formula a[1] – a[0] = a[2] – a[1]. If they are in arithmetic progression, the common difference d = a[1] – a[0] and the initial term would be a[0]"
},
{
"code": null,
"e": 2378,
"s": 2098,
"text": "Check if the 2nd, 3rd and 4th elements are in arithmetic progression using the formula a[2] – a[1] = a[3] – a[2]. If they are in arithmetic progression, the common difference d = a[2] – a[1], which means that the first element has been changed, so initial term is a[0] = a[1] – d"
},
{
"code": null,
"e": 2657,
"s": 2378,
"text": "In both of the above cases, we have checked if the first element or fourth element has been changed. If both the cases are false, then it means that first or fourth element was not changed. So the common difference can be taken as d = (a[3] – a[0])/3 and the initial term = a[0]"
},
{
"code": null,
"e": 2726,
"s": 2657,
"text": "Print all the elements using the initial term and common difference."
},
{
"code": null,
"e": 2778,
"s": 2726,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 2782,
"s": 2778,
"text": "C++"
},
{
"code": null,
"e": 2787,
"s": 2782,
"text": "Java"
},
{
"code": null,
"e": 2795,
"s": 2787,
"text": "Python3"
},
{
"code": null,
"e": 2798,
"s": 2795,
"text": "C#"
},
{
"code": null,
"e": 2809,
"s": 2798,
"text": "Javascript"
},
{
"code": "// C++ program to change one element of an array such// that the resulting array is in arithmetic progression.#include <bits/stdc++.h>using namespace std; // Finds the initial term and common difference and// prints the resulting sequence.void makeAP(int arr[], int n){ int initial_term, common_difference; if (n == 3) { common_difference = arr[2] - arr[1]; initial_term = arr[1] - common_difference; } else if ((arr[1] - arr[0]) == arr[2] - arr[1]) { // Check if the first three elements are in // arithmetic progression initial_term = arr[0]; common_difference = arr[1] - arr[0]; } else if ((arr[2] - arr[1]) == (arr[3] - arr[2])) { // Check if the first element is not // in arithmetic progression common_difference = arr[2] - arr[1]; initial_term = arr[1] - common_difference; } else { // The first and fourth element are // in arithmetic progression common_difference = (arr[3] - arr[0]) / 3; initial_term = arr[0]; } // Print the arithmetic progression for (int i = 0; i < n; i++) cout << initial_term + (i * common_difference) << \" \"; cout << endl;} // Driver Programint main(){ int arr[] = { 1, 3, 7 }; int n = sizeof(arr) / sizeof(arr[0]); makeAP(arr, n); return 0;}",
"e": 4166,
"s": 2809,
"text": null
},
{
"code": "// Java program to change one element of an array such// that the resulting array is in arithmetic progression.import java.util.Arrays; class AP { static void makeAP(int arr[], int n) { int initial_term, common_difference; // Finds the initial term and common difference and // prints the resulting array. if (n == 3) { common_difference = arr[2] - arr[1]; initial_term = arr[1] - common_difference; } else if ((arr[1] - arr[0]) == arr[2] - arr[1]) { // Check if the first three elements are in // arithmetic progression initial_term = arr[0]; common_difference = arr[1] - arr[0]; } else if ((arr[2] - arr[1]) == (arr[3] - arr[2])) { // Check if the first element is not // in arithmetic progression common_difference = arr[2] - arr[1]; initial_term = arr[1] - common_difference; } else { // The first and fourth element are // in arithmetic progression common_difference = (arr[3] - arr[0]) / 3; initial_term = arr[0]; } // Print the arithmetic progression for (int i = 0; i < n; i++) System.out.print(initial_term + (i * common_difference) + \" \"); System.out.println(); } // Driver code public static void main(String[] args) { int arr[] = { 1, 3, 7 }; int n = arr.length; makeAP(arr, n); }}",
"e": 5706,
"s": 4166,
"text": null
},
{
"code": "# Python program to change one element of an array such# that the resulting array is in arithmetic progression.def makeAP(arr, n): initial_term, common_difference = 0, 0 if (n == 3): common_difference = arr[2] - arr[1] initial_term = arr[1] - common_difference elif((arr[1] - arr[0]) == arr[2] - arr[1]): # Check if the first three elements are in # arithmetic progression initial_term = arr[0] common_difference = arr[1] - arr[0] elif((arr[2] - arr[1]) == (arr[3] - arr[2])): # Check if the first element is not # in arithmetic progression common_difference = arr[2] - arr[1] initial_term = arr[1] - common_difference else: # The first and fourth element are # in arithmetic progression common_difference = (arr[3] - arr[0]) / 3 initial_term = arr[0] # Print the arithmetic progression for i in range(n): print(int(initial_term+ (i * common_difference)), end = \" \") print() # Driver codearr = [1, 3, 7]n = len(arr)makeAP(arr, n)",
"e": 6804,
"s": 5706,
"text": null
},
{
"code": "// C# program to change one element of an array such// that the resulting array is in arithmetic progression.using System; public class AP{ static void makeAP(int []arr, int n) { int initial_term, common_difference; // Finds the initial term and common difference and // prints the resulting array. if (n == 3) { common_difference = arr[2] - arr[1]; initial_term = arr[1] - common_difference; } else if ((arr[1] - arr[0]) == arr[2] - arr[1]) { // Check if the first three elements are in // arithmetic progression initial_term = arr[0]; common_difference = arr[1] - arr[0]; } else if ((arr[2] - arr[1]) == (arr[3] - arr[2])) { // Check if the first element is not // in arithmetic progression common_difference = arr[2] - arr[1]; initial_term = arr[1] - common_difference; } else { // The first and fourth element are // in arithmetic progression common_difference = (arr[3] - arr[0]) / 3; initial_term = arr[0]; } // Print the arithmetic progression for (int i = 0; i < n; i++) Console.Write(initial_term + (i * common_difference) + \" \"); Console.WriteLine(); } // Driver code public static void Main(String[] args) { int []arr = { 1, 3, 7 }; int n = arr.Length; makeAP(arr, n); }} // This code contributed by Rajput-Ji",
"e": 8389,
"s": 6804,
"text": null
},
{
"code": "<script> // JavaScript program to change one element of an array such// that the resulting array is in arithmetic progression.function makeAP(arr, n){ let initial_term = 0, common_difference = 0 if (n == 3){ common_difference = arr[2] - arr[1] initial_term = arr[1] - common_difference } else if((arr[1] - arr[0]) == arr[2] - arr[1]){ // Check if the first three elements are in // arithmetic progression initial_term = arr[0] common_difference = arr[1] - arr[0] } else if((arr[2] - arr[1]) == (arr[3] - arr[2])){ // Check if the first element is not // in arithmetic progression common_difference = arr[2] - arr[1] initial_term = arr[1] - common_difference } else{ // The first and fourth element are // in arithmetic progression common_difference = Math.floor((arr[3] - arr[0]) / 3) initial_term = arr[0] } // Print the arithmetic progression for(let i=0;i<n;i++){ document.write(initial_term+(i * common_difference),\" \") } document.write(\"</br>\")} // Driver codelet arr = [1, 3, 7]let n = arr.lengthmakeAP(arr, n) // This code is contributed by shinjanpatra </script>",
"e": 9627,
"s": 8389,
"text": null
},
{
"code": null,
"e": 9634,
"s": 9627,
"text": "-1 3 7"
},
{
"code": null,
"e": 9705,
"s": 9634,
"text": "Time Complexity: O(N), where N is the number of elements in the array."
},
{
"code": null,
"e": 9727,
"s": 9705,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 9737,
"s": 9727,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 9750,
"s": 9737,
"text": "shinjanpatra"
},
{
"code": null,
"e": 9768,
"s": 9750,
"text": "vansikasharma1329"
},
{
"code": null,
"e": 9791,
"s": 9768,
"text": "arithmetic progression"
},
{
"code": null,
"e": 9798,
"s": 9791,
"text": "Arrays"
},
{
"code": null,
"e": 9811,
"s": 9798,
"text": "Mathematical"
},
{
"code": null,
"e": 9818,
"s": 9811,
"text": "Arrays"
},
{
"code": null,
"e": 9831,
"s": 9818,
"text": "Mathematical"
},
{
"code": null,
"e": 9929,
"s": 9831,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9961,
"s": 9929,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 10008,
"s": 9961,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 10033,
"s": 10008,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 10064,
"s": 10033,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 10122,
"s": 10064,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 10152,
"s": 10122,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 10195,
"s": 10152,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 10255,
"s": 10195,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 10270,
"s": 10255,
"text": "C++ Data Types"
}
]
|
Python program for Longest Increasing Subsequence | 08 Jun, 2022
The Longest Increasing Subsequence (LIS) problem is to find the length of the longest subsequence of a given sequence such that all elements of the subsequence are sorted in increasing order. For example, the length of LIS for {10, 22, 9, 33, 21, 50, 41, 60, 80} is 6 and LIS is {10, 22, 33, 50, 60, 80}. More Examples:
Input : arr[] = {3, 10, 2, 1, 20}
Output : Length of LIS = 3
The longest increasing subsequence is 3, 10, 20
Input : arr[] = {3, 2}
Output : Length of LIS = 1
The longest increasing subsequences are {3} and {2}
Input : arr[] = {50, 3, 10, 7, 40, 80}
Output : Length of LIS = 4
The longest increasing subsequence is {3, 7, 40, 80}
Optimal Substructure: Let arr[0..n-1] be the input array and L(i) be the length of the LIS ending at index i such that arr[i] is the last element of the LIS. Then, L(i) can be recursively written as: L(i) = 1 + max( L(j) ) where 0 < j < i and arr[j] < arr[i]; or L(i) = 1, if no such j exists. To find the LIS for a given array, we need to return max(L(i)) where 0 < i < n. Thus, we see the LIS problem satisfies the optimal substructure property as the main problem can be solved using solutions to subproblems. Following is a simple recursive implementation of the LIS problem. It follows the recursive structure discussed above.
Python
# A naive Python implementation of LIS problem """ To make use of recursive calls, this function must return two things: 1) Length of LIS ending with element arr[n-1]. We use max_ending_here for this purpose 2) Overall maximum as the LIS may end with an element before arr[n-1] max_ref is used this purpose. The value of LIS of full array of size n is stored in * max_ref which is our final result """ # global variable to store the maximumglobal maximum def _lis(arr, n ): # to allow the access of global variable global maximum # Base Case if n == 1 : return 1 # maxEndingHere is the length of LIS ending with arr[n-1] maxEndingHere = 1 """Recursively get all LIS ending with arr[0], arr[1]..arr[n-2] IF arr[n-1] is smaller than arr[n-1], and max ending with arr[n-1] needs to be updated, then update it""" for i in xrange(1, n): res = _lis(arr, i) if arr[i-1] < arr[n-1] and res + 1 > maxEndingHere: maxEndingHere = res + 1 # Compare maxEndingHere with overall maximum. And # update the overall maximum if needed maximum = max(maximum, maxEndingHere) return maxEndingHere def lis(arr): # to allow the access of global variable global maximum # length of arr n = len(arr) # maximum variable holds the result maximum = 1 # The function _lis() stores its result in maximum _lis(arr, n) return maximum # Driver program to test the above functionarr = [10, 22, 9, 33, 21, 50, 41, 60]n = len(arr)print "Length of lis is ", lis(arr) # This code is contributed by NIKHIL KUMAR SINGH
Length of lis is 5
Time Complexity: O(2n)
Auxiliary Space: O(1)
Overlapping Subproblems: Considering the above implementation, following is recursion tree for an array of size 4. lis(n) gives us the length of LIS for arr[].
lis(4)
/ |
lis(3) lis(2) lis(1)
/ /
lis(2) lis(1) lis(1)
/
lis(1)
We can see that there are many subproblems which are solved again and again. So this problem has Overlapping Substructure property and recomputation of same subproblems can be avoided by either using Memoization or Tabulation. Following is a tabluated implementation for the LIS problem.
Python
# Dynamic programming Python implementation of LIS problem # lis returns length of the longest increasing subsequence# in arr of size ndef lis(arr): n = len(arr) # Declare the list (array) for LIS and initialize LIS # values for all indexes lis = [1]*n # Compute optimized LIS values in bottom up manner for i in range (1, n): for j in range(0, i): if arr[i] > arr[j] and lis[i]< lis[j] + 1 : lis[i] = lis[j]+1 # Initialize maximum to 0 to get the maximum of all # LIS maximum = 0 # Pick maximum of all LIS values for i in range(n): maximum = max(maximum, lis[i]) return maximum# end of lis function # Driver program to test above functionarr = [10, 22, 9, 33, 21, 50, 41, 60]print "Length of lis is", lis(arr)# This code is contributed by Nikhil Kumar Singh
Length of lis is 5
Time Complexity: O(n2)
Auxiliary space: O(n)
Please refer complete article on Dynamic Programming | Set 3 (Longest Increasing Subsequence) for more details!
ManasChhabra2
simmytarika5
chandramauliguptach
LIS
Dynamic Programming
Python Programs
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Subset Sum Problem | DP-25
Longest Palindromic Substring | Set 1
Floyd Warshall Algorithm | DP-16
Coin Change | DP-7
Matrix Chain Multiplication | DP-8
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": 54,
"s": 26,
"text": "\n08 Jun, 2022"
},
{
"code": null,
"e": 375,
"s": 54,
"text": "The Longest Increasing Subsequence (LIS) problem is to find the length of the longest subsequence of a given sequence such that all elements of the subsequence are sorted in increasing order. For example, the length of LIS for {10, 22, 9, 33, 21, 50, 41, 60, 80} is 6 and LIS is {10, 22, 33, 50, 60, 80}. More Examples:"
},
{
"code": null,
"e": 709,
"s": 375,
"text": "Input : arr[] = {3, 10, 2, 1, 20}\nOutput : Length of LIS = 3\nThe longest increasing subsequence is 3, 10, 20\n\nInput : arr[] = {3, 2}\nOutput : Length of LIS = 1\nThe longest increasing subsequences are {3} and {2}\n\nInput : arr[] = {50, 3, 10, 7, 40, 80}\nOutput : Length of LIS = 4\nThe longest increasing subsequence is {3, 7, 40, 80}"
},
{
"code": null,
"e": 1342,
"s": 709,
"text": "Optimal Substructure: Let arr[0..n-1] be the input array and L(i) be the length of the LIS ending at index i such that arr[i] is the last element of the LIS. Then, L(i) can be recursively written as: L(i) = 1 + max( L(j) ) where 0 < j < i and arr[j] < arr[i]; or L(i) = 1, if no such j exists. To find the LIS for a given array, we need to return max(L(i)) where 0 < i < n. Thus, we see the LIS problem satisfies the optimal substructure property as the main problem can be solved using solutions to subproblems. Following is a simple recursive implementation of the LIS problem. It follows the recursive structure discussed above. "
},
{
"code": null,
"e": 1349,
"s": 1342,
"text": "Python"
},
{
"code": "# A naive Python implementation of LIS problem \"\"\" To make use of recursive calls, this function must return two things: 1) Length of LIS ending with element arr[n-1]. We use max_ending_here for this purpose 2) Overall maximum as the LIS may end with an element before arr[n-1] max_ref is used this purpose. The value of LIS of full array of size n is stored in * max_ref which is our final result \"\"\" # global variable to store the maximumglobal maximum def _lis(arr, n ): # to allow the access of global variable global maximum # Base Case if n == 1 : return 1 # maxEndingHere is the length of LIS ending with arr[n-1] maxEndingHere = 1 \"\"\"Recursively get all LIS ending with arr[0], arr[1]..arr[n-2] IF arr[n-1] is smaller than arr[n-1], and max ending with arr[n-1] needs to be updated, then update it\"\"\" for i in xrange(1, n): res = _lis(arr, i) if arr[i-1] < arr[n-1] and res + 1 > maxEndingHere: maxEndingHere = res + 1 # Compare maxEndingHere with overall maximum. And # update the overall maximum if needed maximum = max(maximum, maxEndingHere) return maxEndingHere def lis(arr): # to allow the access of global variable global maximum # length of arr n = len(arr) # maximum variable holds the result maximum = 1 # The function _lis() stores its result in maximum _lis(arr, n) return maximum # Driver program to test the above functionarr = [10, 22, 9, 33, 21, 50, 41, 60]n = len(arr)print \"Length of lis is \", lis(arr) # This code is contributed by NIKHIL KUMAR SINGH",
"e": 2946,
"s": 1349,
"text": null
},
{
"code": null,
"e": 2966,
"s": 2946,
"text": "Length of lis is 5"
},
{
"code": null,
"e": 2989,
"s": 2966,
"text": "Time Complexity: O(2n)"
},
{
"code": null,
"e": 3011,
"s": 2989,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 3171,
"s": 3011,
"text": "Overlapping Subproblems: Considering the above implementation, following is recursion tree for an array of size 4. lis(n) gives us the length of LIS for arr[]."
},
{
"code": null,
"e": 3303,
"s": 3171,
"text": " lis(4)\n / | \n lis(3) lis(2) lis(1)\n / /\n lis(2) lis(1) lis(1)\n /\nlis(1)"
},
{
"code": null,
"e": 3592,
"s": 3303,
"text": "We can see that there are many subproblems which are solved again and again. So this problem has Overlapping Substructure property and recomputation of same subproblems can be avoided by either using Memoization or Tabulation. Following is a tabluated implementation for the LIS problem. "
},
{
"code": null,
"e": 3599,
"s": 3592,
"text": "Python"
},
{
"code": "# Dynamic programming Python implementation of LIS problem # lis returns length of the longest increasing subsequence# in arr of size ndef lis(arr): n = len(arr) # Declare the list (array) for LIS and initialize LIS # values for all indexes lis = [1]*n # Compute optimized LIS values in bottom up manner for i in range (1, n): for j in range(0, i): if arr[i] > arr[j] and lis[i]< lis[j] + 1 : lis[i] = lis[j]+1 # Initialize maximum to 0 to get the maximum of all # LIS maximum = 0 # Pick maximum of all LIS values for i in range(n): maximum = max(maximum, lis[i]) return maximum# end of lis function # Driver program to test above functionarr = [10, 22, 9, 33, 21, 50, 41, 60]print \"Length of lis is\", lis(arr)# This code is contributed by Nikhil Kumar Singh",
"e": 4439,
"s": 3599,
"text": null
},
{
"code": null,
"e": 4458,
"s": 4439,
"text": "Length of lis is 5"
},
{
"code": null,
"e": 4481,
"s": 4458,
"text": "Time Complexity: O(n2)"
},
{
"code": null,
"e": 4503,
"s": 4481,
"text": "Auxiliary space: O(n)"
},
{
"code": null,
"e": 4615,
"s": 4503,
"text": "Please refer complete article on Dynamic Programming | Set 3 (Longest Increasing Subsequence) for more details!"
},
{
"code": null,
"e": 4629,
"s": 4615,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 4642,
"s": 4629,
"text": "simmytarika5"
},
{
"code": null,
"e": 4662,
"s": 4642,
"text": "chandramauliguptach"
},
{
"code": null,
"e": 4666,
"s": 4662,
"text": "LIS"
},
{
"code": null,
"e": 4686,
"s": 4666,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 4702,
"s": 4686,
"text": "Python Programs"
},
{
"code": null,
"e": 4722,
"s": 4702,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 4820,
"s": 4722,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4847,
"s": 4820,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 4885,
"s": 4847,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 4918,
"s": 4885,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 4937,
"s": 4918,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 4972,
"s": 4937,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 5015,
"s": 4972,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 5037,
"s": 5015,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 5076,
"s": 5037,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 5114,
"s": 5076,
"text": "Python | Convert a list to dictionary"
}
]
|
Dynamic Styling in ElectronJS | 29 May, 2020
ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime.
To make desktop applications more attractive and engaging for the users, developers in addition to the pre-defined CSS would also like to provide a feature wherein the user can control the look and feel of the application and change the styling of the application dynamically during execution. For example, changing the theme of the application, adding animations to elements on the fly, etc. Electron provides a way by which we can successfully add Dynamic styling to the contents of the page using the Instance methods and events of the built-in BrowserWindow object and the webContents property. This tutorial will demonstrate how to add dynamic styling to the contents of the page in Electron.
We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system.
Project Structure:
Example: We will start by building the basic Electron Application by following the given steps.
Step 1: Navigate to an Empty Directory to setup the project, and run the following command,npm initTo generate the package.json file. Install Electron using npm if it is not installed.npm install electron --saveThis command will also create the package-lock.json file and install the required node_modules dependencies. Once Electron has been successfully installed, Open the package.json file and perform the necessary changes under the scripts key.package.json:{
"name": "electron-dynamic",
"version": "1.0.0",
"description": "Dynamic Styling in Electron",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"keywords": [
"electron"
],
"author": "Radhesh Khanna",
"license": "ISC",
"dependencies": {
"electron": "^8.3.0"
}
}
npm init
To generate the package.json file. Install Electron using npm if it is not installed.
npm install electron --save
This command will also create the package-lock.json file and install the required node_modules dependencies. Once Electron has been successfully installed, Open the package.json file and perform the necessary changes under the scripts key.package.json:
{
"name": "electron-dynamic",
"version": "1.0.0",
"description": "Dynamic Styling in Electron",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"keywords": [
"electron"
],
"author": "Radhesh Khanna",
"license": "ISC",
"dependencies": {
"electron": "^8.3.0"
}
}
Step 2: Create a main.js file according to the project structure. This file is the Main Process and acts as an entry point into the application. Copy the Boilerplate code for the main.js file as given in the following link. We have modified the code to suit our project needs.main.js:const { app, BrowserWindow } = require('electron') function createWindow () { // Create the browser window. const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // Load the index.html of the app. win.loadFile('src/index.html') // Open the DevTools. win.webContents.openDevTools()} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.// This method is equivalent to 'app.on('ready', function())'app.whenReady().then(createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the // app when the dock icon is clicked and there are no // other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() }}) // In this file, you can include the rest of your // app's specific main process code. You can also // put them in separate files and require them here.
main.js:
const { app, BrowserWindow } = require('electron') function createWindow () { // Create the browser window. const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // Load the index.html of the app. win.loadFile('src/index.html') // Open the DevTools. win.webContents.openDevTools()} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.// This method is equivalent to 'app.on('ready', function())'app.whenReady().then(createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the // app when the dock icon is clicked and there are no // other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() }}) // In this file, you can include the rest of your // app's specific main process code. You can also // put them in separate files and require them here.
Step 3: Create the index.html file, the index.js file and the index.css file within the src directory. We will also copy the boilerplate code for the index.html file from the above-mentioned link. We have modified the code to suit our project needs.index.html:<!DOCTYPE html><!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>Hello World!</title> <!-- https://electronjs.org/docs/tutorial /security#csp-meta-tag --> <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" /> <link rel="stylesheet" type="text/css" href="index.css"> </head> <body> <h1>Hello World!</h1> We are using node <script> document.write(process.versions.node) </script>, Chrome <script> document.write(process.versions.chrome) </script>, and Electron <script> document.write(process.versions.electron) </script>. <!-- Adding Individual Renderer Process JS File --> <script src="index.js"></script> </body></html>
index.html:
<!DOCTYPE html><!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>Hello World!</title> <!-- https://electronjs.org/docs/tutorial /security#csp-meta-tag --> <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" /> <link rel="stylesheet" type="text/css" href="index.css"> </head> <body> <h1>Hello World!</h1> We are using node <script> document.write(process.versions.node) </script>, Chrome <script> document.write(process.versions.chrome) </script>, and Electron <script> document.write(process.versions.electron) </script>. <!-- Adding Individual Renderer Process JS File --> <script src="index.js"></script> </body></html>
Output: At this point, our basic Electron Application is set up. To launch the Electron Application, run the Command:npm start
npm start
Dynamic Styling in Electron: The BrowserWindow Instance and webContents Property are part of the Main Process. To import and use BrowserWindow in the Renderer Process, we will be using Electron remote module. The webContents.insertCSS(css, options) Instance method Injects CSS dynamically into the current BrowserWindow page contents and returns a unique key for the inserted stylesheet. This method returns a Promise and it resolves to a String which represents the unique Key for the inserted CSS into the BrowserWindow page contents. The same unique Key can be later used to remove the CSS from the page contents using the webContents.removeInsertedCSS() method. It takes in the following parameters.
CSS: String This value should not be empty. The css String consists of the CSS that you want to apply to the contents of the BrowserWindow page. The css String follows all the same rules as that of CSS3 except that it is declared in a String.
options: Object (Optional) It takes in the following parameters,CSSOrigin: String (Optional) Values can be either user or author. Setting the value as user enables the developer to prevent external websites from overriding the CSS set by the developer. Default value is author.
CSSOrigin: String (Optional) Values can be either user or author. Setting the value as user enables the developer to prevent external websites from overriding the CSS set by the developer. Default value is author.
The webContents.removeInsertedCSS(key) Instance method removes the Inserted CSS from the current page contents based on the unique Key representing the stylesheet which was returned by the webContents.insertCSS() method. It returns a void Promise and it resolves when the Removal of the CSS was successful.
To get the current BrowserWindow Instance in the Renderer Process, we can use some of the Static Methods provided by the BrowserWindow object.
BrowserWindow.getAllWindows(): This method returns an Array of active/opened BrowserWindow Instances. In this application, we have only one active BrowserWindow Instance and it can be directly refered from the Array as shown in the code.
BrowserWindow.getFocusedWindow(): This method returns the BrowserWindow Instance which is focused in the Application. If no current BrowserWindow Instance is found, it returns null. In this application, we only have one active BrowserWindow Instance and it can be directly referred using this method as shown in the code.
index.html: Add the following snippet in that file.
<h3>Dynamic Styling in Electron</h3> <button id="style">Change Theme of Page</button> <button id="clear">Revert to Original</button>
Note: At this point, the index.css file is empty.index.js: Add the following snippet in that file.
const electron = require('electron');// Importing BrowserWindow from Main Processconst BrowserWindow = electron.remote.BrowserWindow; var style = document.getElementById('style');let win = BrowserWindow.getFocusedWindow();// let win = BrowserWindow.getAllWindows()[0];var cssKey = undefined; var css = "body { background-color: #000000; color: white; }" style.addEventListener('click', () => { win.webContents.insertCSS(css, { cssOrigin: 'author' }).then(result => { console.log('CSS Added Successfully') console.log('Unique Key Returned ', result) cssKey = result; }).catch(error => { console.log(error); });}); var clear = document.getElementById('clear');clear.addEventListener('click', () => { if (cssKey) { win.webContents.removeInsertedCSS(cssKey) .then(console.log('CSS Removed Successfully')).catch(error => { console.log(error); }); }});
Output:
Note: If we have specified an external Stylesheet such as the index.css file or used inline-styling within the HTML document then the webContents.insertCSS() Instance method will add CSS in addition to the already existing styles. It will not be able to overwrite or change the CSS defined in the external Stylesheet or the inline-styling, if any, for the current BrowserWindow contents.
index.css: Add the following snippet in that file.
html, body { background-color: lightgray;}
The background-color property is defined in the index.css file and we are also dynamically setting it in the index.js file in the webContents.insertCSS() method with a different value. Hence as per behavior, there should be no change in the background color of the BrowserWindow page. If we run the above code in addition to this code snippet, we should see the following Output:
Output:
ElectronJS
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 May, 2020"
},
{
"code": null,
"e": 328,
"s": 28,
"text": "ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime."
},
{
"code": null,
"e": 1026,
"s": 328,
"text": "To make desktop applications more attractive and engaging for the users, developers in addition to the pre-defined CSS would also like to provide a feature wherein the user can control the look and feel of the application and change the styling of the application dynamically during execution. For example, changing the theme of the application, adding animations to elements on the fly, etc. Electron provides a way by which we can successfully add Dynamic styling to the contents of the page using the Instance methods and events of the built-in BrowserWindow object and the webContents property. This tutorial will demonstrate how to add dynamic styling to the contents of the page in Electron."
},
{
"code": null,
"e": 1196,
"s": 1026,
"text": "We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system."
},
{
"code": null,
"e": 1215,
"s": 1196,
"text": "Project Structure:"
},
{
"code": null,
"e": 1311,
"s": 1215,
"text": "Example: We will start by building the basic Electron Application by following the given steps."
},
{
"code": null,
"e": 2081,
"s": 1311,
"text": "Step 1: Navigate to an Empty Directory to setup the project, and run the following command,npm initTo generate the package.json file. Install Electron using npm if it is not installed.npm install electron --saveThis command will also create the package-lock.json file and install the required node_modules dependencies. Once Electron has been successfully installed, Open the package.json file and perform the necessary changes under the scripts key.package.json:{\n \"name\": \"electron-dynamic\",\n \"version\": \"1.0.0\",\n \"description\": \"Dynamic Styling in Electron\",\n \"main\": \"main.js\",\n \"scripts\": {\n \"start\": \"electron .\"\n },\n \"keywords\": [\n \"electron\"\n ],\n \"author\": \"Radhesh Khanna\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"electron\": \"^8.3.0\"\n }\n}\n"
},
{
"code": null,
"e": 2090,
"s": 2081,
"text": "npm init"
},
{
"code": null,
"e": 2176,
"s": 2090,
"text": "To generate the package.json file. Install Electron using npm if it is not installed."
},
{
"code": null,
"e": 2204,
"s": 2176,
"text": "npm install electron --save"
},
{
"code": null,
"e": 2457,
"s": 2204,
"text": "This command will also create the package-lock.json file and install the required node_modules dependencies. Once Electron has been successfully installed, Open the package.json file and perform the necessary changes under the scripts key.package.json:"
},
{
"code": null,
"e": 2764,
"s": 2457,
"text": "{\n \"name\": \"electron-dynamic\",\n \"version\": \"1.0.0\",\n \"description\": \"Dynamic Styling in Electron\",\n \"main\": \"main.js\",\n \"scripts\": {\n \"start\": \"electron .\"\n },\n \"keywords\": [\n \"electron\"\n ],\n \"author\": \"Radhesh Khanna\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"electron\": \"^8.3.0\"\n }\n}\n"
},
{
"code": null,
"e": 4326,
"s": 2764,
"text": "Step 2: Create a main.js file according to the project structure. This file is the Main Process and acts as an entry point into the application. Copy the Boilerplate code for the main.js file as given in the following link. We have modified the code to suit our project needs.main.js:const { app, BrowserWindow } = require('electron') function createWindow () { // Create the browser window. const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // Load the index.html of the app. win.loadFile('src/index.html') // Open the DevTools. win.webContents.openDevTools()} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.// This method is equivalent to 'app.on('ready', function())'app.whenReady().then(createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the // app when the dock icon is clicked and there are no // other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() }}) // In this file, you can include the rest of your // app's specific main process code. You can also // put them in separate files and require them here."
},
{
"code": null,
"e": 4335,
"s": 4326,
"text": "main.js:"
},
{
"code": "const { app, BrowserWindow } = require('electron') function createWindow () { // Create the browser window. const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // Load the index.html of the app. win.loadFile('src/index.html') // Open the DevTools. win.webContents.openDevTools()} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.// This method is equivalent to 'app.on('ready', function())'app.whenReady().then(createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the // app when the dock icon is clicked and there are no // other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() }}) // In this file, you can include the rest of your // app's specific main process code. You can also // put them in separate files and require them here.",
"e": 5613,
"s": 4335,
"text": null
},
{
"code": null,
"e": 6648,
"s": 5613,
"text": "Step 3: Create the index.html file, the index.js file and the index.css file within the src directory. We will also copy the boilerplate code for the index.html file from the above-mentioned link. We have modified the code to suit our project needs.index.html:<!DOCTYPE html><!DOCTYPE html><html> <head> <meta charset=\"UTF-8\"> <title>Hello World!</title> <!-- https://electronjs.org/docs/tutorial /security#csp-meta-tag --> <meta http-equiv=\"Content-Security-Policy\" content=\"script-src 'self' 'unsafe-inline';\" /> <link rel=\"stylesheet\" type=\"text/css\" href=\"index.css\"> </head> <body> <h1>Hello World!</h1> We are using node <script> document.write(process.versions.node) </script>, Chrome <script> document.write(process.versions.chrome) </script>, and Electron <script> document.write(process.versions.electron) </script>. <!-- Adding Individual Renderer Process JS File --> <script src=\"index.js\"></script> </body></html>"
},
{
"code": null,
"e": 6660,
"s": 6648,
"text": "index.html:"
},
{
"code": "<!DOCTYPE html><!DOCTYPE html><html> <head> <meta charset=\"UTF-8\"> <title>Hello World!</title> <!-- https://electronjs.org/docs/tutorial /security#csp-meta-tag --> <meta http-equiv=\"Content-Security-Policy\" content=\"script-src 'self' 'unsafe-inline';\" /> <link rel=\"stylesheet\" type=\"text/css\" href=\"index.css\"> </head> <body> <h1>Hello World!</h1> We are using node <script> document.write(process.versions.node) </script>, Chrome <script> document.write(process.versions.chrome) </script>, and Electron <script> document.write(process.versions.electron) </script>. <!-- Adding Individual Renderer Process JS File --> <script src=\"index.js\"></script> </body></html>",
"e": 7435,
"s": 6660,
"text": null
},
{
"code": null,
"e": 7562,
"s": 7435,
"text": "Output: At this point, our basic Electron Application is set up. To launch the Electron Application, run the Command:npm start"
},
{
"code": null,
"e": 7572,
"s": 7562,
"text": "npm start"
},
{
"code": null,
"e": 8276,
"s": 7572,
"text": "Dynamic Styling in Electron: The BrowserWindow Instance and webContents Property are part of the Main Process. To import and use BrowserWindow in the Renderer Process, we will be using Electron remote module. The webContents.insertCSS(css, options) Instance method Injects CSS dynamically into the current BrowserWindow page contents and returns a unique key for the inserted stylesheet. This method returns a Promise and it resolves to a String which represents the unique Key for the inserted CSS into the BrowserWindow page contents. The same unique Key can be later used to remove the CSS from the page contents using the webContents.removeInsertedCSS() method. It takes in the following parameters."
},
{
"code": null,
"e": 8519,
"s": 8276,
"text": "CSS: String This value should not be empty. The css String consists of the CSS that you want to apply to the contents of the BrowserWindow page. The css String follows all the same rules as that of CSS3 except that it is declared in a String."
},
{
"code": null,
"e": 8797,
"s": 8519,
"text": "options: Object (Optional) It takes in the following parameters,CSSOrigin: String (Optional) Values can be either user or author. Setting the value as user enables the developer to prevent external websites from overriding the CSS set by the developer. Default value is author."
},
{
"code": null,
"e": 9011,
"s": 8797,
"text": "CSSOrigin: String (Optional) Values can be either user or author. Setting the value as user enables the developer to prevent external websites from overriding the CSS set by the developer. Default value is author."
},
{
"code": null,
"e": 9318,
"s": 9011,
"text": "The webContents.removeInsertedCSS(key) Instance method removes the Inserted CSS from the current page contents based on the unique Key representing the stylesheet which was returned by the webContents.insertCSS() method. It returns a void Promise and it resolves when the Removal of the CSS was successful."
},
{
"code": null,
"e": 9461,
"s": 9318,
"text": "To get the current BrowserWindow Instance in the Renderer Process, we can use some of the Static Methods provided by the BrowserWindow object."
},
{
"code": null,
"e": 9699,
"s": 9461,
"text": "BrowserWindow.getAllWindows(): This method returns an Array of active/opened BrowserWindow Instances. In this application, we have only one active BrowserWindow Instance and it can be directly refered from the Array as shown in the code."
},
{
"code": null,
"e": 10021,
"s": 9699,
"text": "BrowserWindow.getFocusedWindow(): This method returns the BrowserWindow Instance which is focused in the Application. If no current BrowserWindow Instance is found, it returns null. In this application, we only have one active BrowserWindow Instance and it can be directly referred using this method as shown in the code."
},
{
"code": null,
"e": 10073,
"s": 10021,
"text": "index.html: Add the following snippet in that file."
},
{
"code": "<h3>Dynamic Styling in Electron</h3> <button id=\"style\">Change Theme of Page</button> <button id=\"clear\">Revert to Original</button>",
"e": 10212,
"s": 10073,
"text": null
},
{
"code": null,
"e": 10311,
"s": 10212,
"text": "Note: At this point, the index.css file is empty.index.js: Add the following snippet in that file."
},
{
"code": "const electron = require('electron');// Importing BrowserWindow from Main Processconst BrowserWindow = electron.remote.BrowserWindow; var style = document.getElementById('style');let win = BrowserWindow.getFocusedWindow();// let win = BrowserWindow.getAllWindows()[0];var cssKey = undefined; var css = \"body { background-color: #000000; color: white; }\" style.addEventListener('click', () => { win.webContents.insertCSS(css, { cssOrigin: 'author' }).then(result => { console.log('CSS Added Successfully') console.log('Unique Key Returned ', result) cssKey = result; }).catch(error => { console.log(error); });}); var clear = document.getElementById('clear');clear.addEventListener('click', () => { if (cssKey) { win.webContents.removeInsertedCSS(cssKey) .then(console.log('CSS Removed Successfully')).catch(error => { console.log(error); }); }});",
"e": 11259,
"s": 10311,
"text": null
},
{
"code": null,
"e": 11267,
"s": 11259,
"text": "Output:"
},
{
"code": null,
"e": 11655,
"s": 11267,
"text": "Note: If we have specified an external Stylesheet such as the index.css file or used inline-styling within the HTML document then the webContents.insertCSS() Instance method will add CSS in addition to the already existing styles. It will not be able to overwrite or change the CSS defined in the external Stylesheet or the inline-styling, if any, for the current BrowserWindow contents."
},
{
"code": null,
"e": 11706,
"s": 11655,
"text": "index.css: Add the following snippet in that file."
},
{
"code": "html, body { background-color: lightgray;}",
"e": 11752,
"s": 11706,
"text": null
},
{
"code": null,
"e": 12132,
"s": 11752,
"text": "The background-color property is defined in the index.css file and we are also dynamically setting it in the index.js file in the webContents.insertCSS() method with a different value. Hence as per behavior, there should be no change in the background color of the BrowserWindow page. If we run the above code in addition to this code snippet, we should see the following Output:"
},
{
"code": null,
"e": 12140,
"s": 12132,
"text": "Output:"
},
{
"code": null,
"e": 12151,
"s": 12140,
"text": "ElectronJS"
},
{
"code": null,
"e": 12162,
"s": 12151,
"text": "JavaScript"
},
{
"code": null,
"e": 12179,
"s": 12162,
"text": "Web Technologies"
}
]
|
whoami command in Linux with example | 18 Feb, 2021
whoami command is used both in Unix Operating System and as well as in Windows Operating System.
It is basically the concatenation of the strings “who”,”am”,”i” as whoami.
It displays the username of the current user when this command is invoked.
It is similar as running the id command with the options -un.
The earliest versions were created in 2.9 BSD as a convenience form for who am i, the Berkeley Unix who command’s way of printing just the logged in user’s identity. The GNU version was written by Richard Mlynarik and is part of the GNU Core Utilities (coreutils).
Syntax:
geekforgeeks@HP~: whoami
Output :
geekforgeeks
Example :
Options of Whoami
Syntax:
geekforgeeks@HP~: whoami [OPTION]
1. –help Option :It gives the help message and exit.Syntax :
geekforgeeks@HP~: whoami --help
Example :2. –version Option :It gives the version information and exit.Syntax:
geekforgeeks@HP~: whoami --version
Example :
Commands related to whoami command are as follows :1. w — Show who is logged on and what they are doing.2. who — Report which users are logged in to the system.Linux Tutorials | About the user and the terminal | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersLinux Tutorials | About the user and the terminal | 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:35 / 2:30•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=WnjofnvIIvg" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
linux-command
Linux-system-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ZIP command in Linux with examples
tar command in Linux with examples
curl command in Linux with Examples
SORT command in Linux/Unix with examples
'crontab' in Linux with Examples
Tail command in Linux with examples
Conditional Statements | Shell Script
TCP Server-Client implementation in C
Docker - COPY Instruction
scp command in Linux with Examples | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n18 Feb, 2021"
},
{
"code": null,
"e": 150,
"s": 53,
"text": "whoami command is used both in Unix Operating System and as well as in Windows Operating System."
},
{
"code": null,
"e": 225,
"s": 150,
"text": "It is basically the concatenation of the strings “who”,”am”,”i” as whoami."
},
{
"code": null,
"e": 300,
"s": 225,
"text": "It displays the username of the current user when this command is invoked."
},
{
"code": null,
"e": 362,
"s": 300,
"text": "It is similar as running the id command with the options -un."
},
{
"code": null,
"e": 627,
"s": 362,
"text": "The earliest versions were created in 2.9 BSD as a convenience form for who am i, the Berkeley Unix who command’s way of printing just the logged in user’s identity. The GNU version was written by Richard Mlynarik and is part of the GNU Core Utilities (coreutils)."
},
{
"code": null,
"e": 635,
"s": 627,
"text": "Syntax:"
},
{
"code": null,
"e": 661,
"s": 635,
"text": "geekforgeeks@HP~: whoami\n"
},
{
"code": null,
"e": 670,
"s": 661,
"text": "Output :"
},
{
"code": null,
"e": 684,
"s": 670,
"text": "geekforgeeks\n"
},
{
"code": null,
"e": 694,
"s": 684,
"text": "Example :"
},
{
"code": null,
"e": 712,
"s": 694,
"text": "Options of Whoami"
},
{
"code": null,
"e": 720,
"s": 712,
"text": "Syntax:"
},
{
"code": null,
"e": 755,
"s": 720,
"text": "geekforgeeks@HP~: whoami [OPTION]\n"
},
{
"code": null,
"e": 816,
"s": 755,
"text": "1. –help Option :It gives the help message and exit.Syntax :"
},
{
"code": null,
"e": 849,
"s": 816,
"text": "geekforgeeks@HP~: whoami --help\n"
},
{
"code": null,
"e": 928,
"s": 849,
"text": "Example :2. –version Option :It gives the version information and exit.Syntax:"
},
{
"code": null,
"e": 964,
"s": 928,
"text": "geekforgeeks@HP~: whoami --version\n"
},
{
"code": null,
"e": 974,
"s": 964,
"text": "Example :"
},
{
"code": null,
"e": 2050,
"s": 974,
"text": "Commands related to whoami command are as follows :1. w — Show who is logged on and what they are doing.2. who — Report which users are logged in to the system.Linux Tutorials | About the user and the terminal | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersLinux Tutorials | About the user and the terminal | 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:35 / 2:30•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=WnjofnvIIvg\" 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": 2064,
"s": 2050,
"text": "linux-command"
},
{
"code": null,
"e": 2086,
"s": 2064,
"text": "Linux-system-commands"
},
{
"code": null,
"e": 2097,
"s": 2086,
"text": "Linux-Unix"
},
{
"code": null,
"e": 2195,
"s": 2097,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2230,
"s": 2195,
"text": "ZIP command in Linux with examples"
},
{
"code": null,
"e": 2265,
"s": 2230,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 2301,
"s": 2265,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 2342,
"s": 2301,
"text": "SORT command in Linux/Unix with examples"
},
{
"code": null,
"e": 2375,
"s": 2342,
"text": "'crontab' in Linux with Examples"
},
{
"code": null,
"e": 2411,
"s": 2375,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 2449,
"s": 2411,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 2487,
"s": 2449,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 2513,
"s": 2487,
"text": "Docker - COPY Instruction"
}
]
|
Print all combinations of points that can compose a given number | 13 Jun, 2022
You can win three kinds of basketball points, 1 point, 2 points, and 3 points. Given a total score of n, print out all the combinations to compose n.
Examples:
For n = 1, the program should print following:
1
For n = 2, the program should print following:
1 1
2
For n = 3, the program should print following:
1 1 1
1 2
2 1
3
For n = 4, the program should print following:
1 1 1 1
1 1 2
1 2 1
1 3
2 1 1
2 2
3 1
and so on ...
Algorithm:
In the first position, we can have three numbers 1 or 2 or 3.First, put 1 at the first position and recursively call for n-1.Then put 2 at the first position and recursively call for n-2.Then put 3 at the first position and recursively call for n-3.If n becomes 0 then we have formed a combination that composes n, so print the current combination.
In the first position, we can have three numbers 1 or 2 or 3.
First, put 1 at the first position and recursively call for n-1.
Then put 2 at the first position and recursively call for n-2.
Then put 3 at the first position and recursively call for n-3.
If n becomes 0 then we have formed a combination that composes n, so print the current combination.
Below is a generalized implementation. In the below implementation, we can change MAX_POINT if there are higher points (more than 3) in the basketball game.
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to Print all// combinations of points that// can compose a given number#define MAX_POINT 3#define ARR_SIZE 100#include <bits/stdc++.h>using namespace std; /* Utility function to print array arr[] */void printArray(int arr[], int arr_size); /* The function prints all combinations of numbers 1, 2, ...MAX_POINTthat sum up to n.i is used in recursion keep track of index in arr[] where nextelement is to be added. Initial value of i must be passed as 0 */void printCompositions(int n, int i){ /* array must be static as we want to keep track of values stored in arr[] using current calls of printCompositions() in function call stack*/ static int arr[ARR_SIZE]; if (n == 0) { printArray(arr, i); } else if(n > 0) { int k; for (k = 1; k <= MAX_POINT; k++) { arr[i]= k; printCompositions(n-k, i+1); } }} /* UTILITY FUNCTIONS *//* Utility function to print array arr[] */void printArray(int arr[], int arr_size){ int i; for (i = 0; i < arr_size; i++) cout<<arr[i]<<" "; cout<<endl;} /* Driver code */int main(){ int n = 5; cout<<"Different compositions formed by 1, 2 and 3 of "<<n<<" are\n"; printCompositions(n, 0); return 0;} // This code is contributed by rathbhupendra
// C program to Print all// combinations of points that// can compose a given number#define MAX_POINT 3#define ARR_SIZE 100#include<stdio.h> /* Utility function to print array arr[] */void printArray(int arr[], int arr_size); /* The function prints all combinations of numbers 1, 2, ...MAX_POINTthat sum up to n.i is used in recursion keep track of index in arr[] where nextelement is to be added. Initial value of i must be passed as 0 */void printCompositions(int n, int i){ /* array must be static as we want to keep track of values stored in arr[] using current calls of printCompositions() in function call stack*/ static int arr[ARR_SIZE]; if (n == 0) { printArray(arr, i); } else if(n > 0) { int k; for (k = 1; k <= MAX_POINT; k++) { arr[i]= k; printCompositions(n-k, i+1); } }} /* UTILITY FUNCTIONS *//* Utility function to print array arr[] */void printArray(int arr[], int arr_size){ int i; for (i = 0; i < arr_size; i++) printf("%d ", arr[i]); printf("\n");} /* Driver function to test above functions */int main(){ int n = 5; printf("Different compositions formed by 1, 2 and 3 of %d are\n", n); printCompositions(n, 0); getchar(); return 0;}
// Java program to Print all// combinations of points that// can compose a given numberimport java.io.*; class GFG{ // Function prints all combinations of numbers 1, 2, ...MAX_POINT // that sum up to n. // i is used in recursion keep track of index in arr[] where next // element is to be added. Initial value of i must be passed as 0 static void printCompositions(int arr[], int n, int i) { int MAX_POINT = 3; if (n == 0) { printArray(arr, i); } else if(n > 0) { for (int k = 1; k <= MAX_POINT; k++) { arr[i]= k; printCompositions(arr, n-k, i+1); } } } // Utility function to print array arr[] static void printArray(int arr[], int m) { for (int i = 0; i < m; i++) System.out.print(arr[i] + " "); System.out.println(); } // Driver program public static void main (String[] args) { int n = 5; int size = 100; int[] arr = new int[size]; System.out.println("Different compositions formed by 1, 2 and 3 of "+ n + " are"); printCompositions(arr, n, 0); }} // Contributed by Pramod Kumar
# Python3 program to Print all combinations# of points that can compose a given numberMAX_POINT = 3;ARR_SIZE = 100; arr = [0] * ARR_SIZE; # The function prints all combinations# of numbers 1, 2, ...MAX_POINT that sum# up to n. i is used in recursion keep# track of index in arr[] where next# element is to be added. Initial value# of i must be passed as 0def printCompositions(n, i): # array must be static as we # want to keep track of values # stored in arr[] using current # calls of printCompositions() in # function call stack*/ if (n == 0): printArray(arr, i); elif(n > 0): for k in range(1,MAX_POINT + 1): arr[i] = k; printCompositions(n - k, i + 1); # UTILITY FUNCTIONS */# Utility function to print array arr[] */def printArray(arr, arr_size): for i in range(arr_size): print(arr[i], end = " "); print(); # Driver Coden = 5;print("Different compositions formed " + "by 1, 2 and 3 of", n, " are");printCompositions(n, 0); # This code is contributed by mits
// C# program to Print all// combinations of points that// can compose a given numberusing System; class GFG { // Function prints all combinations of numbers // 1, 2, ...MAX_POINT that sum up to n. i is // used in recursion keep track of index in // arr[] where next element is to be added. // Initial value of i must be passed as 0 static void printCompositions(int[] arr, int n, int i) { int MAX_POINT = 3; if (n == 0) { printArray(arr, i); } else if (n > 0) { for (int k = 1; k <= MAX_POINT; k++) { arr[i] = k; printCompositions(arr, n - k, i + 1); } } } // Utility function to print array arr[] static void printArray(int[] arr, int m) { for (int i = 0; i < m; i++) Console.Write(arr[i] + " "); Console.WriteLine(); } // Driver program public static void Main() { int n = 5; int size = 100; int[] arr = new int[size]; Console.WriteLine("Different compositions formed" + " by 1, 2 and 3 of " + n + " are"); printCompositions(arr, n, 0); }} // Contributed by Sam007
<?php// PHP program to Print all// combinations of points that// can compose a given number$MAX_POINT = 3;$ARR_SIZE = 100; $arr = array($ARR_SIZE); /* The function prints all combinationsof numbers 1, 2, ...MAX_POINT that sumup to n. i is used in recursion keeptrack of index in arr[] where nextelement is to be added. Initial valueof i must be passed as 0 */function printCompositions($n, $i){ global $arr, $MAX_POINT, $ARR_SIZE; /* array must be static as we want to keep track of values stored in arr[] using current calls of printCompositions() in function call stack*/ if ($n == 0) { printArray($arr, $i); } else if($n > 0) { for ($k = 1; $k <= $MAX_POINT; $k++) { $arr[$i] = $k; printCompositions($n - $k, $i + 1); } }} /* UTILITY FUNCTIONS *//* Utility function to print array arr[] */function printArray($arr, $arr_size){ for ($i = 0; $i < $arr_size; $i++) echo $arr[$i]." "; echo "\n";} // Driver Code$n = 5; echo "Different compositions formed" . " by 1, 2 and 3 of ".$n." are\n";printCompositions($n, 0); // This code is contributed by mits?>
<script> // Javascript program to print all// combinations of points that// can compose a given number // Function prints all combinations of numbers// 1, 2, ...MAX_POlet that sum up to n.// i is used in recursion keep track of index// in arr[] where next element is to be added.// Initial value of i must be passed as 0function printCompositions(arr, n, i){ let MAX_POINT = 3; if (n == 0) { printArray(arr, i); } else if(n > 0) { for(let k = 1; k <= MAX_POINT; k++) { arr[i] = k; printCompositions(arr, n - k, i + 1); } }} // Utility function to print array arr[]function printArray(arr, m){ for(let i = 0; i < m; i++) document.write(arr[i] + " "); document.write("<br/>");} // Driver codelet n = 5;let size = 100;let arr = new Array(size).fill(0); document.write("Different compositions formed " + "by 1, 2 and 3 of "+ n + " are" + "<br/>");printCompositions(arr, n, 0); // This code is contributed by avijitmondal1998 </script>
Output:
Different compositions formed by 1, 2 and 3 of 5 are
1 1 1 1 1
1 1 1 2
1 1 2 1
1 1 3
1 2 1 1
1 2 2
1 3 1
2 1 1 1
2 1 2
2 2 1
2 3
3 1 1
3 2
Time Complexity:O(n)
Space Complexity:O(n)
Please write comments if you find any bug in above code/algorithm, or find other ways to solve the same problem.
Mithun Kumar
rathbhupendra
avijitmondal1998
Rakhi Singh
varshagumber28
simranarora5sos
akashish__
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Find minimum number of coins that make a given value
Algorithm to solve Rubik's Cube
Minimum number of jumps to reach end
The Knight's tour problem | Backtracking-1
Modulo Operator (%) in C/C++ with Examples
Modulo 10^9+7 (1000000007)
Program for factorial of a number | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 205,
"s": 54,
"text": "You can win three kinds of basketball points, 1 point, 2 points, and 3 points. Given a total score of n, print out all the combinations to compose n. "
},
{
"code": null,
"e": 215,
"s": 205,
"text": "Examples:"
},
{
"code": null,
"e": 484,
"s": 215,
"text": "For n = 1, the program should print following:\n1\n\nFor n = 2, the program should print following:\n1 1\n2\n\nFor n = 3, the program should print following:\n1 1 1\n1 2\n2 1 \n3\n\nFor n = 4, the program should print following:\n1 1 1 1\n1 1 2\n1 2 1\n1 3\n2 1 1\n2 2\n3 1\n\nand so on ..."
},
{
"code": null,
"e": 496,
"s": 484,
"text": "Algorithm: "
},
{
"code": null,
"e": 845,
"s": 496,
"text": "In the first position, we can have three numbers 1 or 2 or 3.First, put 1 at the first position and recursively call for n-1.Then put 2 at the first position and recursively call for n-2.Then put 3 at the first position and recursively call for n-3.If n becomes 0 then we have formed a combination that composes n, so print the current combination."
},
{
"code": null,
"e": 907,
"s": 845,
"text": "In the first position, we can have three numbers 1 or 2 or 3."
},
{
"code": null,
"e": 972,
"s": 907,
"text": "First, put 1 at the first position and recursively call for n-1."
},
{
"code": null,
"e": 1035,
"s": 972,
"text": "Then put 2 at the first position and recursively call for n-2."
},
{
"code": null,
"e": 1098,
"s": 1035,
"text": "Then put 3 at the first position and recursively call for n-3."
},
{
"code": null,
"e": 1198,
"s": 1098,
"text": "If n becomes 0 then we have formed a combination that composes n, so print the current combination."
},
{
"code": null,
"e": 1357,
"s": 1198,
"text": "Below is a generalized implementation. In the below implementation, we can change MAX_POINT if there are higher points (more than 3) in the basketball game. "
},
{
"code": null,
"e": 1361,
"s": 1357,
"text": "C++"
},
{
"code": null,
"e": 1363,
"s": 1361,
"text": "C"
},
{
"code": null,
"e": 1368,
"s": 1363,
"text": "Java"
},
{
"code": null,
"e": 1376,
"s": 1368,
"text": "Python3"
},
{
"code": null,
"e": 1379,
"s": 1376,
"text": "C#"
},
{
"code": null,
"e": 1383,
"s": 1379,
"text": "PHP"
},
{
"code": null,
"e": 1394,
"s": 1383,
"text": "Javascript"
},
{
"code": "// C++ program to Print all// combinations of points that// can compose a given number#define MAX_POINT 3#define ARR_SIZE 100#include <bits/stdc++.h>using namespace std; /* Utility function to print array arr[] */void printArray(int arr[], int arr_size); /* The function prints all combinations of numbers 1, 2, ...MAX_POINTthat sum up to n.i is used in recursion keep track of index in arr[] where nextelement is to be added. Initial value of i must be passed as 0 */void printCompositions(int n, int i){ /* array must be static as we want to keep track of values stored in arr[] using current calls of printCompositions() in function call stack*/ static int arr[ARR_SIZE]; if (n == 0) { printArray(arr, i); } else if(n > 0) { int k; for (k = 1; k <= MAX_POINT; k++) { arr[i]= k; printCompositions(n-k, i+1); } }} /* UTILITY FUNCTIONS *//* Utility function to print array arr[] */void printArray(int arr[], int arr_size){ int i; for (i = 0; i < arr_size; i++) cout<<arr[i]<<\" \"; cout<<endl;} /* Driver code */int main(){ int n = 5; cout<<\"Different compositions formed by 1, 2 and 3 of \"<<n<<\" are\\n\"; printCompositions(n, 0); return 0;} // This code is contributed by rathbhupendra",
"e": 2704,
"s": 1394,
"text": null
},
{
"code": "// C program to Print all// combinations of points that// can compose a given number#define MAX_POINT 3#define ARR_SIZE 100#include<stdio.h> /* Utility function to print array arr[] */void printArray(int arr[], int arr_size); /* The function prints all combinations of numbers 1, 2, ...MAX_POINTthat sum up to n.i is used in recursion keep track of index in arr[] where nextelement is to be added. Initial value of i must be passed as 0 */void printCompositions(int n, int i){ /* array must be static as we want to keep track of values stored in arr[] using current calls of printCompositions() in function call stack*/ static int arr[ARR_SIZE]; if (n == 0) { printArray(arr, i); } else if(n > 0) { int k; for (k = 1; k <= MAX_POINT; k++) { arr[i]= k; printCompositions(n-k, i+1); } }} /* UTILITY FUNCTIONS *//* Utility function to print array arr[] */void printArray(int arr[], int arr_size){ int i; for (i = 0; i < arr_size; i++) printf(\"%d \", arr[i]); printf(\"\\n\");} /* Driver function to test above functions */int main(){ int n = 5; printf(\"Different compositions formed by 1, 2 and 3 of %d are\\n\", n); printCompositions(n, 0); getchar(); return 0;}",
"e": 3985,
"s": 2704,
"text": null
},
{
"code": "// Java program to Print all// combinations of points that// can compose a given numberimport java.io.*; class GFG{ // Function prints all combinations of numbers 1, 2, ...MAX_POINT // that sum up to n. // i is used in recursion keep track of index in arr[] where next // element is to be added. Initial value of i must be passed as 0 static void printCompositions(int arr[], int n, int i) { int MAX_POINT = 3; if (n == 0) { printArray(arr, i); } else if(n > 0) { for (int k = 1; k <= MAX_POINT; k++) { arr[i]= k; printCompositions(arr, n-k, i+1); } } } // Utility function to print array arr[] static void printArray(int arr[], int m) { for (int i = 0; i < m; i++) System.out.print(arr[i] + \" \"); System.out.println(); } // Driver program public static void main (String[] args) { int n = 5; int size = 100; int[] arr = new int[size]; System.out.println(\"Different compositions formed by 1, 2 and 3 of \"+ n + \" are\"); printCompositions(arr, n, 0); }} // Contributed by Pramod Kumar",
"e": 5211,
"s": 3985,
"text": null
},
{
"code": "# Python3 program to Print all combinations# of points that can compose a given numberMAX_POINT = 3;ARR_SIZE = 100; arr = [0] * ARR_SIZE; # The function prints all combinations# of numbers 1, 2, ...MAX_POINT that sum# up to n. i is used in recursion keep# track of index in arr[] where next# element is to be added. Initial value# of i must be passed as 0def printCompositions(n, i): # array must be static as we # want to keep track of values # stored in arr[] using current # calls of printCompositions() in # function call stack*/ if (n == 0): printArray(arr, i); elif(n > 0): for k in range(1,MAX_POINT + 1): arr[i] = k; printCompositions(n - k, i + 1); # UTILITY FUNCTIONS */# Utility function to print array arr[] */def printArray(arr, arr_size): for i in range(arr_size): print(arr[i], end = \" \"); print(); # Driver Coden = 5;print(\"Different compositions formed \" + \"by 1, 2 and 3 of\", n, \" are\");printCompositions(n, 0); # This code is contributed by mits",
"e": 6259,
"s": 5211,
"text": null
},
{
"code": "// C# program to Print all// combinations of points that// can compose a given numberusing System; class GFG { // Function prints all combinations of numbers // 1, 2, ...MAX_POINT that sum up to n. i is // used in recursion keep track of index in // arr[] where next element is to be added. // Initial value of i must be passed as 0 static void printCompositions(int[] arr, int n, int i) { int MAX_POINT = 3; if (n == 0) { printArray(arr, i); } else if (n > 0) { for (int k = 1; k <= MAX_POINT; k++) { arr[i] = k; printCompositions(arr, n - k, i + 1); } } } // Utility function to print array arr[] static void printArray(int[] arr, int m) { for (int i = 0; i < m; i++) Console.Write(arr[i] + \" \"); Console.WriteLine(); } // Driver program public static void Main() { int n = 5; int size = 100; int[] arr = new int[size]; Console.WriteLine(\"Different compositions formed\" + \" by 1, 2 and 3 of \" + n + \" are\"); printCompositions(arr, n, 0); }} // Contributed by Sam007",
"e": 7468,
"s": 6259,
"text": null
},
{
"code": "<?php// PHP program to Print all// combinations of points that// can compose a given number$MAX_POINT = 3;$ARR_SIZE = 100; $arr = array($ARR_SIZE); /* The function prints all combinationsof numbers 1, 2, ...MAX_POINT that sumup to n. i is used in recursion keeptrack of index in arr[] where nextelement is to be added. Initial valueof i must be passed as 0 */function printCompositions($n, $i){ global $arr, $MAX_POINT, $ARR_SIZE; /* array must be static as we want to keep track of values stored in arr[] using current calls of printCompositions() in function call stack*/ if ($n == 0) { printArray($arr, $i); } else if($n > 0) { for ($k = 1; $k <= $MAX_POINT; $k++) { $arr[$i] = $k; printCompositions($n - $k, $i + 1); } }} /* UTILITY FUNCTIONS *//* Utility function to print array arr[] */function printArray($arr, $arr_size){ for ($i = 0; $i < $arr_size; $i++) echo $arr[$i].\" \"; echo \"\\n\";} // Driver Code$n = 5; echo \"Different compositions formed\" . \" by 1, 2 and 3 of \".$n.\" are\\n\";printCompositions($n, 0); // This code is contributed by mits?>",
"e": 8630,
"s": 7468,
"text": null
},
{
"code": "<script> // Javascript program to print all// combinations of points that// can compose a given number // Function prints all combinations of numbers// 1, 2, ...MAX_POlet that sum up to n.// i is used in recursion keep track of index// in arr[] where next element is to be added.// Initial value of i must be passed as 0function printCompositions(arr, n, i){ let MAX_POINT = 3; if (n == 0) { printArray(arr, i); } else if(n > 0) { for(let k = 1; k <= MAX_POINT; k++) { arr[i] = k; printCompositions(arr, n - k, i + 1); } }} // Utility function to print array arr[]function printArray(arr, m){ for(let i = 0; i < m; i++) document.write(arr[i] + \" \"); document.write(\"<br/>\");} // Driver codelet n = 5;let size = 100;let arr = new Array(size).fill(0); document.write(\"Different compositions formed \" + \"by 1, 2 and 3 of \"+ n + \" are\" + \"<br/>\");printCompositions(arr, n, 0); // This code is contributed by avijitmondal1998 </script>",
"e": 9668,
"s": 8630,
"text": null
},
{
"code": null,
"e": 9677,
"s": 9668,
"text": "Output: "
},
{
"code": null,
"e": 9829,
"s": 9677,
"text": "Different compositions formed by 1, 2 and 3 of 5 are\n1 1 1 1 1 \n1 1 1 2 \n1 1 2 1 \n1 1 3 \n1 2 1 1 \n1 2 2 \n1 3 1 \n2 1 1 1 \n2 1 2 \n2 2 1 \n2 3 \n3 1 1 \n3 2 "
},
{
"code": null,
"e": 9850,
"s": 9829,
"text": "Time Complexity:O(n)"
},
{
"code": null,
"e": 9872,
"s": 9850,
"text": "Space Complexity:O(n)"
},
{
"code": null,
"e": 9986,
"s": 9872,
"text": "Please write comments if you find any bug in above code/algorithm, or find other ways to solve the same problem. "
},
{
"code": null,
"e": 9999,
"s": 9986,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 10013,
"s": 9999,
"text": "rathbhupendra"
},
{
"code": null,
"e": 10030,
"s": 10013,
"text": "avijitmondal1998"
},
{
"code": null,
"e": 10042,
"s": 10030,
"text": "Rakhi Singh"
},
{
"code": null,
"e": 10057,
"s": 10042,
"text": "varshagumber28"
},
{
"code": null,
"e": 10073,
"s": 10057,
"text": "simranarora5sos"
},
{
"code": null,
"e": 10084,
"s": 10073,
"text": "akashish__"
},
{
"code": null,
"e": 10097,
"s": 10084,
"text": "Mathematical"
},
{
"code": null,
"e": 10110,
"s": 10097,
"text": "Mathematical"
},
{
"code": null,
"e": 10208,
"s": 10110,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10232,
"s": 10208,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 10253,
"s": 10232,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 10267,
"s": 10253,
"text": "Prime Numbers"
},
{
"code": null,
"e": 10320,
"s": 10267,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 10352,
"s": 10320,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 10389,
"s": 10352,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 10432,
"s": 10389,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 10475,
"s": 10432,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 10502,
"s": 10475,
"text": "Modulo 10^9+7 (1000000007)"
}
]
|
JPA - Advanced Mappings | JPA is a library which is released with java specification. Therefore, it supports all object oriented concepts for entity persistence. Till now we are done with the basics of object relational mapping. This chapter takes you through the advanced mappings between objects and relational entities.
Inheritance is the core concept of object oriented language, therefore we can use inheritance relationships or strategies between entities. JPA support three types of inheritance strategies such as SINGLE_TABLE, JOINED_TABLE, and TABLE_PER_CONCRETE_CLASS.
Let us consider an example of Staff, TeachingStaff, NonTeachingStaff classes and their relationships as follows:
In the above shown diagram Staff is an entity and TeachingStaff and NonTeachingStaff are the sub entities of Staff. Here we will discuss the above example in all three strategies of inheritance.
Single-Table strategy takes all classes fields (both super and sub classes) and map them down into a single table known as SINGLE_TABLE strategy. Here discriminator value plays key role in differentiating the values of three entities in one table.
Let us consider the above example, TeachingStaff and NonTeachingStaff are the sub classes of class Staff. Remind the concept of inheritance (is a mechanism of inheriting the properties of super class by sub class) and therefore sid, sname are the fields which belongs to both TeachingStaff and NonTeachingStaff. Create a JPA project. All the modules of this project as follows:
Create a package named ‘com.tutorialspoint.eclipselink.entity’ under ‘src’ package. Create a new java class named Staff.java under given package. The Staff entity class is shown as follows:
package com.tutorialspoint.eclipselink.entity;
import java.io.Serializable;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
@Entity
@Table
@Inheritance( strategy = InheritanceType.SINGLE_TABLE )
@DiscriminatorColumn( name = "type" )
public class Staff implements Serializable {
@Id
@GeneratedValue( strategy = GenerationType.AUTO )
private int sid;
private String sname;
public Staff( int sid, String sname ) {
super( );
this.sid = sid;
this.sname = sname;
}
public Staff( ) {
super( );
}
public int getSid( ) {
return sid;
}
public void setSid( int sid ) {
this.sid = sid;
}
public String getSname( ) {
return sname;
}
public void setSname( String sname ) {
this.sname = sname;
}
}
In the above code @DescriminatorColumn specifies the field name (type) and the values of it shows the remaining (Teaching and NonTeachingStaff) fields.
Create a subclass (class) to Staff class named TeachingStaff.java under the com.tutorialspoint.eclipselink.entity package. The TeachingStaff Entity class is shown as follows:
package com.tutorialspoint.eclipselink.entity;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
@Entity
@DiscriminatorValue( value="TS" )
public class TeachingStaff extends Staff {
private String qualification;
private String subjectexpertise;
public TeachingStaff( int sid, String sname,
String qualification,String subjectexpertise ) {
super( sid, sname );
this.qualification = qualification;
this.subjectexpertise = subjectexpertise;
}
public TeachingStaff( ) {
super( );
}
public String getQualification( ){
return qualification;
}
public void setQualification( String qualification ){
this.qualification = qualification;
}
public String getSubjectexpertise( ) {
return subjectexpertise;
}
public void setSubjectexpertise( String subjectexpertise ){
this.subjectexpertise = subjectexpertise;
}
}
Create a subclass (class) to Staff class named NonTeachingStaff.java under the com.tutorialspoint.eclipselink.entity package. The NonTeachingStaff Entity class is shown as follows:
package com.tutorialspoint.eclipselink.entity;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
@Entity
@DiscriminatorValue( value = "NS" )
public class NonTeachingStaff extends Staff {
private String areaexpertise;
public NonTeachingStaff( int sid, String sname, String areaexpertise ) {
super( sid, sname );
this.areaexpertise = areaexpertise;
}
public NonTeachingStaff( ) {
super( );
}
public String getAreaexpertise( ) {
return areaexpertise;
}
public void setAreaexpertise( String areaexpertise ){
this.areaexpertise = areaexpertise;
}
}
Persistence.xml file contains the configuration information of database and registration information of entity classes. The xml file is shown as follows:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="Eclipselink_JPA" transaction-type="RESOURCE_LOCAL">
<class>com.tutorialspoint.eclipselink.entity.Staff</class>
<class>com.tutorialspoint.eclipselink.entity.NonTeachingStaff</class>
<class>com.tutorialspoint.eclipselink.entity.TeachingStaff</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpadb"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="eclipselink.logging.level" value="FINE"/>
<property name="eclipselink.ddl-generation" value="create-tables"/>
</properties>
</persistence-unit>
</persistence>
Service classes are the implementation part of business component. Create a package under ‘src’ package named ‘com.tutorialspoint.eclipselink.service’.
Create a class named SaveClient.java under the given package to store Staff, TeachingStaff, and NonTeachingStaff class fields. The SaveClient class is shown as follows:
package com.tutorialspoint.eclipselink.service;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import com.tutorialspoint.eclipselink.entity.NonTeachingStaff;
import com.tutorialspoint.eclipselink.entity.TeachingStaff;
public class SaveClient {
public static void main( String[ ] args ) {
EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
EntityManager entitymanager = emfactory.createEntityManager( );
entitymanager.getTransaction( ).begin( );
//Teaching staff entity
TeachingStaff ts1=new TeachingStaff(1,"Gopal","MSc MEd","Maths");
TeachingStaff ts2=new TeachingStaff(2, "Manisha", "BSc BEd", "English");
//Non-Teaching Staff entity
NonTeachingStaff nts1=new NonTeachingStaff(3, "Satish", "Accounts");
NonTeachingStaff nts2=new NonTeachingStaff(4, "Krishna", "Office Admin");
//storing all entities
entitymanager.persist(ts1);
entitymanager.persist(ts2);
entitymanager.persist(nts1);
entitymanager.persist(nts2);
entitymanager.getTransaction().commit();
entitymanager.close();
emfactory.close();
}
}
After compilation and execution of the above program you will get notifications in the console panel of Eclipse IDE. Check MySQL workbench for output. The output in a tabular format is shown as follows:
Finally you will get single table which contains all three class’s fields and differs with discriminator column named ‘Type’ (field).
Joined table strategy is to share the referenced column which contains unique values to join the table and make easy transactions. Let us consider the same example as above.
Create a JPA Project. All the project modules shown as follows:
Create a package named ‘com.tutorialspoint.eclipselink.entity’ under ‘src’ package. Create a new java class named Staff.java under given package. The Staff entity class is shown as follows:
package com.tutorialspoint.eclipselink.entity;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
@Entity
@Table
@Inheritance( strategy = InheritanceType.JOINED )
public class Staff implements Serializable {
@Id
@GeneratedValue( strategy = GenerationType.AUTO )
private int sid;
private String sname;
public Staff( int sid, String sname ) {
super( );
this.sid = sid;
this.sname = sname;
}
public Staff( ) {
super( );
}
public int getSid( ) {
return sid;
}
public void setSid( int sid ) {
this.sid = sid;
}
public String getSname( ) {
return sname;
}
public void setSname( String sname ) {
this.sname = sname;
}
}
Create a subclass (class) to Staff class named TeachingStaff.java under the com.tutorialspoint.eclipselink.entity package. The TeachingStaff Entity class is shown as follows:
package com.tutorialspoint.eclipselink.entity;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
@Entity
@PrimaryKeyJoinColumn(referencedColumnName="sid")
public class TeachingStaff extends Staff {
private String qualification;
private String subjectexpertise;
public TeachingStaff( int sid, String sname,
String qualification,String subjectexpertise ) {
super( sid, sname );
this.qualification = qualification;
this.subjectexpertise = subjectexpertise;
}
public TeachingStaff( ) {
super( );
}
public String getQualification( ){
return qualification;
}
public void setQualification( String qualification ){
this.qualification = qualification;
}
public String getSubjectexpertise( ) {
return subjectexpertise;
}
public void setSubjectexpertise( String subjectexpertise ){
this.subjectexpertise = subjectexpertise;
}
}
Create a subclass (class) to Staff class named NonTeachingStaff.java under the com.tutorialspoint.eclipselink.entity package. The NonTeachingStaff Entity class is shown as follows:
package com.tutorialspoint.eclipselink.entity;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
@Entity
@PrimaryKeyJoinColumn(referencedColumnName="sid")
public class NonTeachingStaff extends Staff {
private String areaexpertise;
public NonTeachingStaff( int sid, String sname, String areaexpertise ) {
super( sid, sname );
this.areaexpertise = areaexpertise;
}
public NonTeachingStaff( ) {
super( );
}
public String getAreaexpertise( ) {
return areaexpertise;
}
public void setAreaexpertise( String areaexpertise ) {
this.areaexpertise = areaexpertise;
}
}
Persistence.xml file contains the configuration information of database and registration information of entity classes. The xml file is shown as follows:
<?xml version = "1.0" encoding = "UTF-8"?>
<persistence version = "2.0" xmlns = "http://java.sun.com/xml/ns/persistence"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name = "Eclipselink_JPA" transaction-type = "RESOURCE_LOCAL">
<class>com.tutorialspoint.eclipselink.entity.Staff</class>
<class>com.tutorialspoint.eclipselink.entity.NonTeachingStaff</class>
<class>com.tutorialspoint.eclipselink.entity.TeachingStaff</class>
<properties>
<property name = "javax.persistence.jdbc.url" value = "jdbc:mysql://localhost:3306/jpadb"/>
<property name = "javax.persistence.jdbc.user" value = "root"/>
<property name = "javax.persistence.jdbc.password" value = "root"/>
<property name = "javax.persistence.jdbc.driver" value = "com.mysql.jdbc.Driver"/>
<property name = "eclipselink.logging.level" value = "FINE"/>
<property name = "eclipselink.ddl-generation" value = "create-tables"/>
</properties>
</persistence-unit>
</persistence>
Service classes are the implementation part of business component. Create a package under ‘src’ package named ‘com.tutorialspoint.eclipselink.service’.
Create a class named SaveClient.java under the given package to store Staff, TeachingStaff, and NonTeachingStaff class fields. Then SaveClient class as follows:
package com.tutorialspoint.eclipselink.service;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import com.tutorialspoint.eclipselink.entity.NonTeachingStaff;
import com.tutorialspoint.eclipselink.entity.TeachingStaff;
public class SaveClient {
public static void main( String[ ] args ) {
EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
EntityManager entitymanager = emfactory.createEntityManager( );
entitymanager.getTransaction( ).begin( );
//Teaching staff entity
TeachingStaff ts1 = new TeachingStaff(1,"Gopal","MSc MEd","Maths");
TeachingStaff ts2 = new TeachingStaff(2, "Manisha", "BSc BEd", "English");
//Non-Teaching Staff entity
NonTeachingStaff nts1 = new NonTeachingStaff(3, "Satish", "Accounts");
NonTeachingStaff nts2 = new NonTeachingStaff(4, "Krishna", "Office Admin");
//storing all entities
entitymanager.persist(ts1);
entitymanager.persist(ts2);
entitymanager.persist(nts1);
entitymanager.persist(nts2);
entitymanager.getTransaction().commit();
entitymanager.close();
emfactory.close();
}
}
After compilation and execution of the above program you will get notifications in the console panel of Eclipse IDE. For output check MySQL workbench as follows:
Here three tables are created and the result of staff table in a tabular format is shown as follows:
The result of TeachingStaff table in a tabular format is shown as follows:
In the above table sid is the foreign key (reference field form staff table) The result of NonTeachingStaff table in tabular format is shown as follows:
Finally the three tables are created using their fields respectively and SID field is shared by all three tables. In staff table SID is primary key, in remaining (TeachingStaff and NonTeachingStaff) tables SID is foreign key.
Table per class strategy is to create a table for each sub entity. The staff table will be created but it will contain null records. The field values of Staff table must be shared by TeachingStaff and NonTeachingStaff tables.
Let us consider the same example as above. All modules of this project are shown as follows:
Create a package named ‘com.tutorialspoint.eclipselink.entity’ under ‘src’ package. Create a new java class named Staff.java under given package. The Staff entity class is shown as follows:
package com.tutorialspoint.eclipselink.entity;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
@Entity
@Table
@Inheritance( strategy = InheritanceType.TABLE_PER_CLASS )
public class Staff implements Serializable {
@Id
@GeneratedValue( strategy = GenerationType.AUTO )
private int sid;
private String sname;
public Staff( int sid, String sname ) {
super( );
this.sid = sid;
this.sname = sname;
}
public Staff( ) {
super( );
}
public int getSid( ) {
return sid;
}
public void setSid( int sid ) {
this.sid = sid;
}
public String getSname( ) {
return sname;
}
public void setSname( String sname ) {
this.sname = sname;
}
}
Create a subclass (class) to Staff class named TeachingStaff.java under the com.tutorialspoint.eclipselink.entity package. The TeachingStaff Entity class is shown as follows:
package com.tutorialspoint.eclipselink.entity;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
@Entity
public class TeachingStaff extends Staff {
private String qualification;
private String subjectexpertise;
public TeachingStaff( int sid, String sname, String qualification, String subjectexpertise ) {
super( sid, sname );
this.qualification = qualification;
this.subjectexpertise = subjectexpertise;
}
public TeachingStaff( ) {
super( );
}
public String getQualification( ){
return qualification;
}
public void setQualification( String qualification ) {
this.qualification = qualification;
}
public String getSubjectexpertise( ) {
return subjectexpertise;
}
public void setSubjectexpertise( String subjectexpertise ){
this.subjectexpertise = subjectexpertise;
}
}
Create a subclass (class) to Staff class named NonTeachingStaff.java under the com.tutorialspoint.eclipselink.entity package. The NonTeachingStaff Entity class is shown as follows:
package com.tutorialspoint.eclipselink.entity;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
@Entity
public class NonTeachingStaff extends Staff {
private String areaexpertise;
public NonTeachingStaff( int sid, String sname, String areaexpertise ) {
super( sid, sname );
this.areaexpertise = areaexpertise;
}
public NonTeachingStaff( ) {
super( );
}
public String getAreaexpertise( ) {
return areaexpertise;
}
public void setAreaexpertise( String areaexpertise ) {
this.areaexpertise = areaexpertise;
}
}
Persistence.xml file contains the configuration information of database and registration information of entity classes. The xml file is shown as follows:
<?xml version="1.0" encoding = "UTF-8"?>
<persistence version = "2.0" xmlns = "http://java.sun.com/xml/ns/persistence"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name = "Eclipselink_JPA" transaction-type = "RESOURCE_LOCAL">
<class>com.tutorialspoint.eclipselink.entity.Staff</class>
<class>com.tutorialspoint.eclipselink.entity.NonTeachingStaff</class>
<class>com.tutorialspoint.eclipselink.entity.TeachingStaff</class>
<properties>
<property name = "javax.persistence.jdbc.url" value = "jdbc:mysql://localhost:3306/jpadb"/>
<property name = "javax.persistence.jdbc.user" value = "root"/>
<property name = "javax.persistence.jdbc.password" value = "root"/>
<property name = "javax.persistence.jdbc.driver" value = "com.mysql.jdbc.Driver"/>
<property name = "eclipselink.logging.level" value = "FINE"/>
<property name = "eclipselink.ddl-generation" value="create-tables"/>
</properties>
</persistence-unit>
</persistence>
Service classes are the implementation part of business component. Create a package under ‘src’ package named ‘com.tutorialspoint.eclipselink.service’.
Create a class named SaveClient.java under the given package to store Staff, TeachingStaff, and NonTeachingStaff class fields. The SaveClient class is shown as follows:
package com.tutorialspoint.eclipselink.service;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import com.tutorialspoint.eclipselink.entity.NonTeachingStaff;
import com.tutorialspoint.eclipselink.entity.TeachingStaff;
public class SaveClient {
public static void main( String[ ] args ) {
EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
EntityManager entitymanager = emfactory.createEntityManager( );
entitymanager.getTransaction( ).begin( );
//Teaching staff entity
TeachingStaff ts1 = new TeachingStaff(1,"Gopal","MSc MEd","Maths");
TeachingStaff ts2 = new TeachingStaff(2, "Manisha", "BSc BEd", "English");
//Non-Teaching Staff entity
NonTeachingStaff nts1 = new NonTeachingStaff(3, "Satish", "Accounts");
NonTeachingStaff nts2 = new NonTeachingStaff(4, "Krishna", "Office Admin");
//storing all entities
entitymanager.persist(ts1);
entitymanager.persist(ts2);
entitymanager.persist(nts1);
entitymanager.persist(nts2);
entitymanager.getTransaction().commit();
entitymanager.close();
emfactory.close();
}
}
After compilation and execution of the above program you will get notifications in the console panel of Eclipse IDE. For output, check MySQL workbench as follows:
Here the three tables are created and the Staff table contains null records.
The result of TeachingStaff in a tabular format is shown as follows:
The above table TeachingStaff contains fields of both Staff and TeachingStaff Entities.
The result of NonTeachingStaff in a tabular format is shown as follows:
The above table NonTeachingStaff contains fields of both Staff and NonTeachingStaff Entities. | [
{
"code": null,
"e": 2170,
"s": 1873,
"text": "JPA is a library which is released with java specification. Therefore, it supports all object oriented concepts for entity persistence. Till now we are done with the basics of object relational mapping. This chapter takes you through the advanced mappings between objects and relational entities."
},
{
"code": null,
"e": 2426,
"s": 2170,
"text": "Inheritance is the core concept of object oriented language, therefore we can use inheritance relationships or strategies between entities. JPA support three types of inheritance strategies such as SINGLE_TABLE, JOINED_TABLE, and TABLE_PER_CONCRETE_CLASS."
},
{
"code": null,
"e": 2539,
"s": 2426,
"text": "Let us consider an example of Staff, TeachingStaff, NonTeachingStaff classes and their relationships as follows:"
},
{
"code": null,
"e": 2734,
"s": 2539,
"text": "In the above shown diagram Staff is an entity and TeachingStaff and NonTeachingStaff are the sub entities of Staff. Here we will discuss the above example in all three strategies of inheritance."
},
{
"code": null,
"e": 2982,
"s": 2734,
"text": "Single-Table strategy takes all classes fields (both super and sub classes) and map them down into a single table known as SINGLE_TABLE strategy. Here discriminator value plays key role in differentiating the values of three entities in one table."
},
{
"code": null,
"e": 3360,
"s": 2982,
"text": "Let us consider the above example, TeachingStaff and NonTeachingStaff are the sub classes of class Staff. Remind the concept of inheritance (is a mechanism of inheriting the properties of super class by sub class) and therefore sid, sname are the fields which belongs to both TeachingStaff and NonTeachingStaff. Create a JPA project. All the modules of this project as follows:"
},
{
"code": null,
"e": 3550,
"s": 3360,
"text": "Create a package named ‘com.tutorialspoint.eclipselink.entity’ under ‘src’ package. Create a new java class named Staff.java under given package. The Staff entity class is shown as follows:"
},
{
"code": null,
"e": 4615,
"s": 3550,
"text": "package com.tutorialspoint.eclipselink.entity;\n\nimport java.io.Serializable;\n\nimport javax.persistence.DiscriminatorColumn;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Inheritance;\nimport javax.persistence.InheritanceType;\nimport javax.persistence.Table;\n\n@Entity\n@Table\n@Inheritance( strategy = InheritanceType.SINGLE_TABLE )\n@DiscriminatorColumn( name = \"type\" )\n\npublic class Staff implements Serializable {\n @Id\n @GeneratedValue( strategy = GenerationType.AUTO )\n \n private int sid;\n private String sname;\n \n public Staff( int sid, String sname ) {\n super( );\n this.sid = sid;\n this.sname = sname;\n }\n \n public Staff( ) {\n super( );\n }\n \n public int getSid( ) {\n return sid;\n }\n \n public void setSid( int sid ) {\n this.sid = sid;\n }\n \n public String getSname( ) {\n return sname;\n }\n \n public void setSname( String sname ) {\n this.sname = sname;\n }\n}"
},
{
"code": null,
"e": 4767,
"s": 4615,
"text": "In the above code @DescriminatorColumn specifies the field name (type) and the values of it shows the remaining (Teaching and NonTeachingStaff) fields."
},
{
"code": null,
"e": 4942,
"s": 4767,
"text": "Create a subclass (class) to Staff class named TeachingStaff.java under the com.tutorialspoint.eclipselink.entity package. The TeachingStaff Entity class is shown as follows:"
},
{
"code": null,
"e": 5878,
"s": 4942,
"text": "package com.tutorialspoint.eclipselink.entity;\n\nimport javax.persistence.DiscriminatorValue;\nimport javax.persistence.Entity;\n\n@Entity\n@DiscriminatorValue( value=\"TS\" )\npublic class TeachingStaff extends Staff {\n\n private String qualification;\n private String subjectexpertise;\n\n public TeachingStaff( int sid, String sname, \n \n String qualification,String subjectexpertise ) {\n super( sid, sname );\n this.qualification = qualification;\n this.subjectexpertise = subjectexpertise;\n }\n\n public TeachingStaff( ) {\n super( );\n }\n\n public String getQualification( ){\n return qualification;\n }\n\n public void setQualification( String qualification ){\n this.qualification = qualification;\n }\n\n public String getSubjectexpertise( ) {\n return subjectexpertise;\n }\n\n public void setSubjectexpertise( String subjectexpertise ){\n this.subjectexpertise = subjectexpertise;\n }\n}"
},
{
"code": null,
"e": 6059,
"s": 5878,
"text": "Create a subclass (class) to Staff class named NonTeachingStaff.java under the com.tutorialspoint.eclipselink.entity package. The NonTeachingStaff Entity class is shown as follows:"
},
{
"code": null,
"e": 6695,
"s": 6059,
"text": "package com.tutorialspoint.eclipselink.entity;\n\nimport javax.persistence.DiscriminatorValue;\nimport javax.persistence.Entity;\n\n@Entity\n@DiscriminatorValue( value = \"NS\" )\n\npublic class NonTeachingStaff extends Staff {\n private String areaexpertise;\n\n public NonTeachingStaff( int sid, String sname, String areaexpertise ) {\n super( sid, sname );\n this.areaexpertise = areaexpertise;\n }\n\n public NonTeachingStaff( ) {\n super( );\n }\n\n public String getAreaexpertise( ) {\n return areaexpertise;\n }\n\n public void setAreaexpertise( String areaexpertise ){\n this.areaexpertise = areaexpertise;\n }\n}"
},
{
"code": null,
"e": 6849,
"s": 6695,
"text": "Persistence.xml file contains the configuration information of database and registration information of entity classes. The xml file is shown as follows:"
},
{
"code": null,
"e": 8008,
"s": 6849,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<persistence version=\"2.0\" xmlns=\"http://java.sun.com/xml/ns/persistence\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence \n http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd\">\n\n <persistence-unit name=\"Eclipselink_JPA\" transaction-type=\"RESOURCE_LOCAL\">\n \n <class>com.tutorialspoint.eclipselink.entity.Staff</class>\n <class>com.tutorialspoint.eclipselink.entity.NonTeachingStaff</class>\n <class>com.tutorialspoint.eclipselink.entity.TeachingStaff</class>\n \n <properties>\n <property name=\"javax.persistence.jdbc.url\" value=\"jdbc:mysql://localhost:3306/jpadb\"/>\n <property name=\"javax.persistence.jdbc.user\" value=\"root\"/>\n <property name=\"javax.persistence.jdbc.password\" value=\"root\"/>\n <property name=\"javax.persistence.jdbc.driver\" value=\"com.mysql.jdbc.Driver\"/>\n <property name=\"eclipselink.logging.level\" value=\"FINE\"/>\n <property name=\"eclipselink.ddl-generation\" value=\"create-tables\"/>\n </properties>\n \n </persistence-unit>\n</persistence>"
},
{
"code": null,
"e": 8160,
"s": 8008,
"text": "Service classes are the implementation part of business component. Create a package under ‘src’ package named ‘com.tutorialspoint.eclipselink.service’."
},
{
"code": null,
"e": 8329,
"s": 8160,
"text": "Create a class named SaveClient.java under the given package to store Staff, TeachingStaff, and NonTeachingStaff class fields. The SaveClient class is shown as follows:"
},
{
"code": null,
"e": 9592,
"s": 8329,
"text": "package com.tutorialspoint.eclipselink.service;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport com.tutorialspoint.eclipselink.entity.NonTeachingStaff;\nimport com.tutorialspoint.eclipselink.entity.TeachingStaff;\n\npublic class SaveClient {\n\n public static void main( String[ ] args ) {\n \n EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( \"Eclipselink_JPA\" );\n EntityManager entitymanager = emfactory.createEntityManager( );\n entitymanager.getTransaction( ).begin( );\n\n //Teaching staff entity \n TeachingStaff ts1=new TeachingStaff(1,\"Gopal\",\"MSc MEd\",\"Maths\");\n TeachingStaff ts2=new TeachingStaff(2, \"Manisha\", \"BSc BEd\", \"English\");\n \n //Non-Teaching Staff entity\n NonTeachingStaff nts1=new NonTeachingStaff(3, \"Satish\", \"Accounts\");\n NonTeachingStaff nts2=new NonTeachingStaff(4, \"Krishna\", \"Office Admin\");\n\n //storing all entities\n entitymanager.persist(ts1);\n entitymanager.persist(ts2);\n entitymanager.persist(nts1);\n entitymanager.persist(nts2);\n \n entitymanager.getTransaction().commit();\n \n entitymanager.close();\n emfactory.close();\n }\n}"
},
{
"code": null,
"e": 9795,
"s": 9592,
"text": "After compilation and execution of the above program you will get notifications in the console panel of Eclipse IDE. Check MySQL workbench for output. The output in a tabular format is shown as follows:"
},
{
"code": null,
"e": 9929,
"s": 9795,
"text": "Finally you will get single table which contains all three class’s fields and differs with discriminator column named ‘Type’ (field)."
},
{
"code": null,
"e": 10103,
"s": 9929,
"text": "Joined table strategy is to share the referenced column which contains unique values to join the table and make easy transactions. Let us consider the same example as above."
},
{
"code": null,
"e": 10167,
"s": 10103,
"text": "Create a JPA Project. All the project modules shown as follows:"
},
{
"code": null,
"e": 10357,
"s": 10167,
"text": "Create a package named ‘com.tutorialspoint.eclipselink.entity’ under ‘src’ package. Create a new java class named Staff.java under given package. The Staff entity class is shown as follows:"
},
{
"code": null,
"e": 11333,
"s": 10357,
"text": "package com.tutorialspoint.eclipselink.entity;\n\nimport java.io.Serializable;\n\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Inheritance;\nimport javax.persistence.InheritanceType;\nimport javax.persistence.Table;\n\n@Entity\n@Table\n@Inheritance( strategy = InheritanceType.JOINED )\n\npublic class Staff implements Serializable {\n\n @Id\n @GeneratedValue( strategy = GenerationType.AUTO )\n \n private int sid;\n private String sname;\n \n public Staff( int sid, String sname ) {\n super( );\n this.sid = sid;\n this.sname = sname;\n }\n \n public Staff( ) {\n super( );\n }\n \n public int getSid( ) {\n return sid;\n }\n \n public void setSid( int sid ) {\n this.sid = sid;\n }\n \n public String getSname( ) {\n return sname;\n }\n \n public void setSname( String sname ) {\n this.sname = sname;\n }\n}"
},
{
"code": null,
"e": 11508,
"s": 11333,
"text": "Create a subclass (class) to Staff class named TeachingStaff.java under the com.tutorialspoint.eclipselink.entity package. The TeachingStaff Entity class is shown as follows:"
},
{
"code": null,
"e": 12460,
"s": 11508,
"text": "package com.tutorialspoint.eclipselink.entity;\n\nimport javax.persistence.DiscriminatorValue;\nimport javax.persistence.Entity;\n\n@Entity\n@PrimaryKeyJoinColumn(referencedColumnName=\"sid\")\n\npublic class TeachingStaff extends Staff {\n private String qualification;\n private String subjectexpertise;\n\n public TeachingStaff( int sid, String sname, \n \n String qualification,String subjectexpertise ) {\n super( sid, sname );\n this.qualification = qualification;\n this.subjectexpertise = subjectexpertise;\n }\n\n public TeachingStaff( ) {\n super( );\n }\n\n public String getQualification( ){\n return qualification;\n }\n\n public void setQualification( String qualification ){\n this.qualification = qualification;\n }\n\n public String getSubjectexpertise( ) {\n return subjectexpertise;\n }\n\n public void setSubjectexpertise( String subjectexpertise ){\n this.subjectexpertise = subjectexpertise;\n }\n}"
},
{
"code": null,
"e": 12641,
"s": 12460,
"text": "Create a subclass (class) to Staff class named NonTeachingStaff.java under the com.tutorialspoint.eclipselink.entity package. The NonTeachingStaff Entity class is shown as follows:"
},
{
"code": null,
"e": 13292,
"s": 12641,
"text": "package com.tutorialspoint.eclipselink.entity;\n\nimport javax.persistence.DiscriminatorValue;\nimport javax.persistence.Entity;\n\n@Entity\n@PrimaryKeyJoinColumn(referencedColumnName=\"sid\")\n\npublic class NonTeachingStaff extends Staff {\n private String areaexpertise;\n\n public NonTeachingStaff( int sid, String sname, String areaexpertise ) {\n super( sid, sname );\n this.areaexpertise = areaexpertise;\n }\n\n public NonTeachingStaff( ) {\n super( );\n }\n\n public String getAreaexpertise( ) {\n return areaexpertise;\n }\n\n public void setAreaexpertise( String areaexpertise ) {\n this.areaexpertise = areaexpertise;\n }\n}"
},
{
"code": null,
"e": 13446,
"s": 13292,
"text": "Persistence.xml file contains the configuration information of database and registration information of entity classes. The xml file is shown as follows:"
},
{
"code": null,
"e": 14645,
"s": 13446,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<persistence version = \"2.0\" xmlns = \"http://java.sun.com/xml/ns/persistence\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation = \"http://java.sun.com/xml/ns/persistence \n http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd\">\n \n <persistence-unit name = \"Eclipselink_JPA\" transaction-type = \"RESOURCE_LOCAL\">\n <class>com.tutorialspoint.eclipselink.entity.Staff</class>\n <class>com.tutorialspoint.eclipselink.entity.NonTeachingStaff</class>\n <class>com.tutorialspoint.eclipselink.entity.TeachingStaff</class>\n \n <properties>\n <property name = \"javax.persistence.jdbc.url\" value = \"jdbc:mysql://localhost:3306/jpadb\"/>\n <property name = \"javax.persistence.jdbc.user\" value = \"root\"/>\n <property name = \"javax.persistence.jdbc.password\" value = \"root\"/>\n <property name = \"javax.persistence.jdbc.driver\" value = \"com.mysql.jdbc.Driver\"/>\n <property name = \"eclipselink.logging.level\" value = \"FINE\"/>\n <property name = \"eclipselink.ddl-generation\" value = \"create-tables\"/>\n </properties>\n \n </persistence-unit>\n</persistence>"
},
{
"code": null,
"e": 14797,
"s": 14645,
"text": "Service classes are the implementation part of business component. Create a package under ‘src’ package named ‘com.tutorialspoint.eclipselink.service’."
},
{
"code": null,
"e": 14958,
"s": 14797,
"text": "Create a class named SaveClient.java under the given package to store Staff, TeachingStaff, and NonTeachingStaff class fields. Then SaveClient class as follows:"
},
{
"code": null,
"e": 16211,
"s": 14958,
"text": "package com.tutorialspoint.eclipselink.service;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport com.tutorialspoint.eclipselink.entity.NonTeachingStaff;\nimport com.tutorialspoint.eclipselink.entity.TeachingStaff;\n\npublic class SaveClient {\n public static void main( String[ ] args ) {\n EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( \"Eclipselink_JPA\" );\n EntityManager entitymanager = emfactory.createEntityManager( );\n entitymanager.getTransaction( ).begin( );\n\n //Teaching staff entity \n TeachingStaff ts1 = new TeachingStaff(1,\"Gopal\",\"MSc MEd\",\"Maths\");\n TeachingStaff ts2 = new TeachingStaff(2, \"Manisha\", \"BSc BEd\", \"English\");\n \n //Non-Teaching Staff entity\n NonTeachingStaff nts1 = new NonTeachingStaff(3, \"Satish\", \"Accounts\");\n NonTeachingStaff nts2 = new NonTeachingStaff(4, \"Krishna\", \"Office Admin\");\n\n //storing all entities\n entitymanager.persist(ts1);\n entitymanager.persist(ts2);\n entitymanager.persist(nts1);\n entitymanager.persist(nts2);\n\n entitymanager.getTransaction().commit();\n entitymanager.close();\n emfactory.close();\n }\n}"
},
{
"code": null,
"e": 16373,
"s": 16211,
"text": "After compilation and execution of the above program you will get notifications in the console panel of Eclipse IDE. For output check MySQL workbench as follows:"
},
{
"code": null,
"e": 16474,
"s": 16373,
"text": "Here three tables are created and the result of staff table in a tabular format is shown as follows:"
},
{
"code": null,
"e": 16549,
"s": 16474,
"text": "The result of TeachingStaff table in a tabular format is shown as follows:"
},
{
"code": null,
"e": 16702,
"s": 16549,
"text": "In the above table sid is the foreign key (reference field form staff table) The result of NonTeachingStaff table in tabular format is shown as follows:"
},
{
"code": null,
"e": 16928,
"s": 16702,
"text": "Finally the three tables are created using their fields respectively and SID field is shared by all three tables. In staff table SID is primary key, in remaining (TeachingStaff and NonTeachingStaff) tables SID is foreign key."
},
{
"code": null,
"e": 17154,
"s": 16928,
"text": "Table per class strategy is to create a table for each sub entity. The staff table will be created but it will contain null records. The field values of Staff table must be shared by TeachingStaff and NonTeachingStaff tables."
},
{
"code": null,
"e": 17247,
"s": 17154,
"text": "Let us consider the same example as above. All modules of this project are shown as follows:"
},
{
"code": null,
"e": 17437,
"s": 17247,
"text": "Create a package named ‘com.tutorialspoint.eclipselink.entity’ under ‘src’ package. Create a new java class named Staff.java under given package. The Staff entity class is shown as follows:"
},
{
"code": null,
"e": 18401,
"s": 17437,
"text": "package com.tutorialspoint.eclipselink.entity;\n\nimport java.io.Serializable;\n\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Inheritance;\nimport javax.persistence.InheritanceType;\nimport javax.persistence.Table;\n\n@Entity\n@Table\n@Inheritance( strategy = InheritanceType.TABLE_PER_CLASS )\n\npublic class Staff implements Serializable {\n\n @Id\n @GeneratedValue( strategy = GenerationType.AUTO )\n\n private int sid;\n private String sname;\n\n public Staff( int sid, String sname ) {\n super( );\n this.sid = sid;\n this.sname = sname;\n }\n\n public Staff( ) {\n super( );\n }\n\n public int getSid( ) {\n return sid;\n }\n\n public void setSid( int sid ) {\n this.sid = sid;\n }\n\n public String getSname( ) {\n return sname;\n }\n\n public void setSname( String sname ) {\n this.sname = sname;\n }\n}"
},
{
"code": null,
"e": 18576,
"s": 18401,
"text": "Create a subclass (class) to Staff class named TeachingStaff.java under the com.tutorialspoint.eclipselink.entity package. The TeachingStaff Entity class is shown as follows:"
},
{
"code": null,
"e": 19474,
"s": 18576,
"text": "package com.tutorialspoint.eclipselink.entity;\n\nimport javax.persistence.DiscriminatorValue;\nimport javax.persistence.Entity;\n\n@Entity\npublic class TeachingStaff extends Staff {\n private String qualification;\n private String subjectexpertise;\n\n public TeachingStaff( int sid, String sname, String qualification, String subjectexpertise ) {\n super( sid, sname );\n this.qualification = qualification;\n this.subjectexpertise = subjectexpertise;\n }\n\n public TeachingStaff( ) {\n super( );\n }\n\n public String getQualification( ){\n return qualification;\n }\n \n public void setQualification( String qualification ) {\n this.qualification = qualification;\n }\n\n public String getSubjectexpertise( ) {\n return subjectexpertise;\n }\n\n public void setSubjectexpertise( String subjectexpertise ){\n this.subjectexpertise = subjectexpertise;\n }\n}"
},
{
"code": null,
"e": 19655,
"s": 19474,
"text": "Create a subclass (class) to Staff class named NonTeachingStaff.java under the com.tutorialspoint.eclipselink.entity package. The NonTeachingStaff Entity class is shown as follows:"
},
{
"code": null,
"e": 20255,
"s": 19655,
"text": "package com.tutorialspoint.eclipselink.entity;\n\nimport javax.persistence.DiscriminatorValue;\nimport javax.persistence.Entity;\n\n@Entity\npublic class NonTeachingStaff extends Staff {\n private String areaexpertise;\n\n public NonTeachingStaff( int sid, String sname, String areaexpertise ) {\n super( sid, sname );\n this.areaexpertise = areaexpertise;\n }\n\n public NonTeachingStaff( ) {\n super( );\n }\n\n public String getAreaexpertise( ) {\n return areaexpertise;\n }\n\n public void setAreaexpertise( String areaexpertise ) {\n this.areaexpertise = areaexpertise;\n }\n}"
},
{
"code": null,
"e": 20409,
"s": 20255,
"text": "Persistence.xml file contains the configuration information of database and registration information of entity classes. The xml file is shown as follows:"
},
{
"code": null,
"e": 21599,
"s": 20409,
"text": "<?xml version=\"1.0\" encoding = \"UTF-8\"?>\n<persistence version = \"2.0\" xmlns = \"http://java.sun.com/xml/ns/persistence\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation = \"http://java.sun.com/xml/ns/persistence \n http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd\">\n\n <persistence-unit name = \"Eclipselink_JPA\" transaction-type = \"RESOURCE_LOCAL\">\n <class>com.tutorialspoint.eclipselink.entity.Staff</class>\n <class>com.tutorialspoint.eclipselink.entity.NonTeachingStaff</class>\n <class>com.tutorialspoint.eclipselink.entity.TeachingStaff</class>\n \n <properties>\n <property name = \"javax.persistence.jdbc.url\" value = \"jdbc:mysql://localhost:3306/jpadb\"/>\n <property name = \"javax.persistence.jdbc.user\" value = \"root\"/>\n <property name = \"javax.persistence.jdbc.password\" value = \"root\"/>\n <property name = \"javax.persistence.jdbc.driver\" value = \"com.mysql.jdbc.Driver\"/>\n <property name = \"eclipselink.logging.level\" value = \"FINE\"/>\n <property name = \"eclipselink.ddl-generation\" value=\"create-tables\"/>\n </properties>\n \n </persistence-unit>\n</persistence>"
},
{
"code": null,
"e": 21751,
"s": 21599,
"text": "Service classes are the implementation part of business component. Create a package under ‘src’ package named ‘com.tutorialspoint.eclipselink.service’."
},
{
"code": null,
"e": 21920,
"s": 21751,
"text": "Create a class named SaveClient.java under the given package to store Staff, TeachingStaff, and NonTeachingStaff class fields. The SaveClient class is shown as follows:"
},
{
"code": null,
"e": 23174,
"s": 21920,
"text": "package com.tutorialspoint.eclipselink.service;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport com.tutorialspoint.eclipselink.entity.NonTeachingStaff;\nimport com.tutorialspoint.eclipselink.entity.TeachingStaff;\n\npublic class SaveClient {\n public static void main( String[ ] args ) {\n EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( \"Eclipselink_JPA\" );\n EntityManager entitymanager = emfactory.createEntityManager( );\n entitymanager.getTransaction( ).begin( );\n\n //Teaching staff entity \n TeachingStaff ts1 = new TeachingStaff(1,\"Gopal\",\"MSc MEd\",\"Maths\");\n TeachingStaff ts2 = new TeachingStaff(2, \"Manisha\", \"BSc BEd\", \"English\");\n \n //Non-Teaching Staff entity\n NonTeachingStaff nts1 = new NonTeachingStaff(3, \"Satish\", \"Accounts\");\n NonTeachingStaff nts2 = new NonTeachingStaff(4, \"Krishna\", \"Office Admin\");\n\n //storing all entities\n entitymanager.persist(ts1);\n entitymanager.persist(ts2);\n entitymanager.persist(nts1);\n entitymanager.persist(nts2);\n\n entitymanager.getTransaction().commit();\n entitymanager.close();\n emfactory.close();\n }\n}"
},
{
"code": null,
"e": 23337,
"s": 23174,
"text": "After compilation and execution of the above program you will get notifications in the console panel of Eclipse IDE. For output, check MySQL workbench as follows:"
},
{
"code": null,
"e": 23414,
"s": 23337,
"text": "Here the three tables are created and the Staff table contains null records."
},
{
"code": null,
"e": 23483,
"s": 23414,
"text": "The result of TeachingStaff in a tabular format is shown as follows:"
},
{
"code": null,
"e": 23571,
"s": 23483,
"text": "The above table TeachingStaff contains fields of both Staff and TeachingStaff Entities."
},
{
"code": null,
"e": 23643,
"s": 23571,
"text": "The result of NonTeachingStaff in a tabular format is shown as follows:"
}
]
|
Matplotlib.axes.Axes.hist() in Python | 13 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.hist() function in axes module of matplotlib library is used to plot a histogram.
Syntax: Axes.hist(self, x, bins=None, range=None, density=None, weights=None, cumulative=False, bottom=None, histtype=’bar’, align=’mid’, orientation=’vertical’, rwidth=None, log=False, color=None, label=None, stacked=False, normed=None, *, data=None, **kwargs)
Parameters: This method accept the following parameters that are described below:
x : This parameter are the sequence of data.
bins : This parameter is an optional parameter and it contains the integer or sequence or string.
range : This parameter is an optional parameter and it the lower and upper range of the bins.
density : This parameter is an optional parameter and it contains the boolean values.
weights : This parameter is an optional parameter and it is an array of weights, of the same shape as x.
bottom : This parameter is the location of the bottom baseline of each bin.
histtype : This parameter is an optional parameter and it is used to draw type of histogram. {‘bar’, ‘barstacked’, ‘step’, ‘stepfilled’}
align : This parameter is an optional parameter and it controls how the histogram is plotted. {‘left’, ‘mid’, ‘right’}
rwidth : This parameter is an optional parameter and it is a relative width of the bars as a fraction of the bin width
log : This parameter is an optional parameter and it is used to set histogram axis to a log scale
color : This parameter is an optional parameter and it is a color spec or sequence of color specs, one per dataset.
label : This parameter is an optional parameter and it is a string, or sequence of strings to match multiple datasets.
normed : This parameter is an optional parameter and it contains the boolean values.It uses the density keyword argument instead.
Returns: This returns the following:
n :This returns the values of the histogram bins.
bins :This returns the edges of the bins.
patches :This returns the list of individual patches used to create the histogram.
Below examples illustrate the matplotlib.axes.Axes.hexbin() function in matplotlib.axes:
Example-1:
# Implementation of matplotlib functionimport matplotlibimport numpy as npimport matplotlib.pyplot as plt np.random.seed(10**7)mu = 121 sigma = 21x = mu + sigma * np.random.randn(1000) num_bins = 100fig, ax = plt.subplots() n, bins, patches = ax.hist(x, num_bins, density = 1, color ='green', alpha = 0.7) y = ((1 / (np.sqrt(2 * np.pi) * sigma)) * np.exp(-0.5 * (1 / sigma * (bins - mu))**2))ax.plot(bins, y, '--', color ='black')ax.set_xlabel('X-Axis')ax.set_ylabel('Y-Axis') ax.set_title('matplotlib.axes.Axes.hist() Example')plt.show()
Output:
Example-2:
# Implementation of matplotlib functionimport matplotlibimport numpy as npimport matplotlib.pyplot as plt np.random.seed(10**7)n_bins = 20x = np.random.randn(10000, 3) fig, [(ax0, ax1), (ax2, ax3)] = plt.subplots(nrows = 2, ncols = 2) colors = ['green', 'blue', 'lime'] ax0.hist(x, n_bins, density = True, histtype ='bar', color = colors, label = colors) ax0.legend(prop ={'size': 10}) ax1.hist(x, n_bins, density = True, histtype ='barstacked', stacked = True, color = colors) ax2.hist(x, n_bins, histtype ='step', stacked = True, fill = False, color = colors) x_multi = [np.random.randn(n) for n in [100000, 80000, 1000]] ax3.hist(x_multi, n_bins, histtype ='stepfilled', color = colors) plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Apr, 2020"
},
{
"code": null,
"e": 328,
"s": 28,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute."
},
{
"code": null,
"e": 419,
"s": 328,
"text": "The Axes.hist() function in axes module of matplotlib library is used to plot a histogram."
},
{
"code": null,
"e": 681,
"s": 419,
"text": "Syntax: Axes.hist(self, x, bins=None, range=None, density=None, weights=None, cumulative=False, bottom=None, histtype=’bar’, align=’mid’, orientation=’vertical’, rwidth=None, log=False, color=None, label=None, stacked=False, normed=None, *, data=None, **kwargs)"
},
{
"code": null,
"e": 763,
"s": 681,
"text": "Parameters: This method accept the following parameters that are described below:"
},
{
"code": null,
"e": 808,
"s": 763,
"text": "x : This parameter are the sequence of data."
},
{
"code": null,
"e": 906,
"s": 808,
"text": "bins : This parameter is an optional parameter and it contains the integer or sequence or string."
},
{
"code": null,
"e": 1000,
"s": 906,
"text": "range : This parameter is an optional parameter and it the lower and upper range of the bins."
},
{
"code": null,
"e": 1086,
"s": 1000,
"text": "density : This parameter is an optional parameter and it contains the boolean values."
},
{
"code": null,
"e": 1191,
"s": 1086,
"text": "weights : This parameter is an optional parameter and it is an array of weights, of the same shape as x."
},
{
"code": null,
"e": 1267,
"s": 1191,
"text": "bottom : This parameter is the location of the bottom baseline of each bin."
},
{
"code": null,
"e": 1404,
"s": 1267,
"text": "histtype : This parameter is an optional parameter and it is used to draw type of histogram. {‘bar’, ‘barstacked’, ‘step’, ‘stepfilled’}"
},
{
"code": null,
"e": 1523,
"s": 1404,
"text": "align : This parameter is an optional parameter and it controls how the histogram is plotted. {‘left’, ‘mid’, ‘right’}"
},
{
"code": null,
"e": 1642,
"s": 1523,
"text": "rwidth : This parameter is an optional parameter and it is a relative width of the bars as a fraction of the bin width"
},
{
"code": null,
"e": 1740,
"s": 1642,
"text": "log : This parameter is an optional parameter and it is used to set histogram axis to a log scale"
},
{
"code": null,
"e": 1856,
"s": 1740,
"text": "color : This parameter is an optional parameter and it is a color spec or sequence of color specs, one per dataset."
},
{
"code": null,
"e": 1975,
"s": 1856,
"text": "label : This parameter is an optional parameter and it is a string, or sequence of strings to match multiple datasets."
},
{
"code": null,
"e": 2105,
"s": 1975,
"text": "normed : This parameter is an optional parameter and it contains the boolean values.It uses the density keyword argument instead."
},
{
"code": null,
"e": 2142,
"s": 2105,
"text": "Returns: This returns the following:"
},
{
"code": null,
"e": 2192,
"s": 2142,
"text": "n :This returns the values of the histogram bins."
},
{
"code": null,
"e": 2234,
"s": 2192,
"text": "bins :This returns the edges of the bins."
},
{
"code": null,
"e": 2317,
"s": 2234,
"text": "patches :This returns the list of individual patches used to create the histogram."
},
{
"code": null,
"e": 2406,
"s": 2317,
"text": "Below examples illustrate the matplotlib.axes.Axes.hexbin() function in matplotlib.axes:"
},
{
"code": null,
"e": 2417,
"s": 2406,
"text": "Example-1:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlibimport numpy as npimport matplotlib.pyplot as plt np.random.seed(10**7)mu = 121 sigma = 21x = mu + sigma * np.random.randn(1000) num_bins = 100fig, ax = plt.subplots() n, bins, patches = ax.hist(x, num_bins, density = 1, color ='green', alpha = 0.7) y = ((1 / (np.sqrt(2 * np.pi) * sigma)) * np.exp(-0.5 * (1 / sigma * (bins - mu))**2))ax.plot(bins, y, '--', color ='black')ax.set_xlabel('X-Axis')ax.set_ylabel('Y-Axis') ax.set_title('matplotlib.axes.Axes.hist() Example')plt.show()",
"e": 3046,
"s": 2417,
"text": null
},
{
"code": null,
"e": 3054,
"s": 3046,
"text": "Output:"
},
{
"code": null,
"e": 3065,
"s": 3054,
"text": "Example-2:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlibimport numpy as npimport matplotlib.pyplot as plt np.random.seed(10**7)n_bins = 20x = np.random.randn(10000, 3) fig, [(ax0, ax1), (ax2, ax3)] = plt.subplots(nrows = 2, ncols = 2) colors = ['green', 'blue', 'lime'] ax0.hist(x, n_bins, density = True, histtype ='bar', color = colors, label = colors) ax0.legend(prop ={'size': 10}) ax1.hist(x, n_bins, density = True, histtype ='barstacked', stacked = True, color = colors) ax2.hist(x, n_bins, histtype ='step', stacked = True, fill = False, color = colors) x_multi = [np.random.randn(n) for n in [100000, 80000, 1000]] ax3.hist(x_multi, n_bins, histtype ='stepfilled', color = colors) plt.show()",
"e": 3993,
"s": 3065,
"text": null
},
{
"code": null,
"e": 4001,
"s": 3993,
"text": "Output:"
},
{
"code": null,
"e": 4019,
"s": 4001,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 4026,
"s": 4019,
"text": "Python"
},
{
"code": null,
"e": 4124,
"s": 4026,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4156,
"s": 4124,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4183,
"s": 4156,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4214,
"s": 4183,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 4235,
"s": 4214,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4291,
"s": 4235,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 4314,
"s": 4291,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 4356,
"s": 4314,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 4398,
"s": 4356,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 4437,
"s": 4398,
"text": "Python | datetime.timedelta() function"
}
]
|
Longest Common Prefix using Binary Search | 21 Jan, 2022
Given a set of strings, find the longest common prefix.
Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”}
Output : "gee"
Input : {"apple", "ape", "april"}
Output : "ap"
Input : {"abcd"}
Output : "abcd"
Previous Approaches – Word by Word Matching , Character by Character Matching, Divide and Conquer In this article, an approach using Binary Search is discussed. Steps:
Find the string having the minimum length. Let this length be L.Perform a binary search on any one string (from the input array of strings). Let us take the first string and do a binary search on the characters from the index – 0 to L-1.Initially, take low = 0 and high = L-1 and divide the string into two halves – left (low to mid) and right (mid+1 to high).Check whether all the characters in the left half is present at the corresponding indices (low to mid) of all the strings or not. If it is present then we append this half to our prefix string and we look in the right half in a hope to find a longer prefix.(It is guaranteed that a common prefix string is there.)Otherwise, if all the characters in the left half is not present at the corresponding indices (low to mid) in all the strings, then we need not look at the right half as there is some character(s) in the left half itself which is not a part of the longest prefix string. So we indeed look at the left half in a hope to find a common prefix string. (It may be possible that we don’t find any common prefix string)
Find the string having the minimum length. Let this length be L.
Perform a binary search on any one string (from the input array of strings). Let us take the first string and do a binary search on the characters from the index – 0 to L-1.
Initially, take low = 0 and high = L-1 and divide the string into two halves – left (low to mid) and right (mid+1 to high).
Check whether all the characters in the left half is present at the corresponding indices (low to mid) of all the strings or not. If it is present then we append this half to our prefix string and we look in the right half in a hope to find a longer prefix.(It is guaranteed that a common prefix string is there.)
Otherwise, if all the characters in the left half is not present at the corresponding indices (low to mid) in all the strings, then we need not look at the right half as there is some character(s) in the left half itself which is not a part of the longest prefix string. So we indeed look at the left half in a hope to find a common prefix string. (It may be possible that we don’t find any common prefix string)
Algorithm Illustration considering strings as – “geeksforgeeks”, “geeks”, “geek”, “geezer”
Below is the implementation of above approach.
C++
Java
Python3
C#
Javascript
// A C++ Program to find the longest common prefix#include<bits/stdc++.h>using namespace std; // A Function to find the string having the minimum// length and returns that lengthint findMinLength(string arr[], int n){ int min = INT_MAX; for (int i=0; i<=n-1; i++) if (arr[i].length() < min) min = arr[i].length(); return(min);} bool allContainsPrefix(string arr[], int n, string str, int start, int end){ for (int i=0; i<=n-1; i++) for (int j=start; j<=end; j++) if (arr[i][j] != str[j]) return (false); return (true);} // A Function that returns the longest common prefix// from the array of stringsstring commonPrefix(string arr[], int n){ int index = findMinLength(arr, n); string prefix; // Our resultant string // We will do an in-place binary search on the // first string of the array in the range 0 to // index int low = 0, high = index; while (low <= high) { // Same as (low + high)/2, but avoids overflow // for large low and high int mid = low + (high - low) / 2; if (allContainsPrefix (arr, n, arr[0], low, mid)) { // If all the strings in the input array contains // this prefix then append this substring to // our answer prefix = prefix + arr[0].substr(low, mid-low+1); // And then go for the right part low = mid + 1; } else // Go for the left part high = mid - 1; } return (prefix);} // Driver program to test above functionint main(){ string arr[] = {"geeksforgeeks", "geeks", "geek", "geezer"}; int n = sizeof (arr) / sizeof (arr[0]); string ans = commonPrefix(arr, n); if (ans.length()) cout << "The longest common prefix is " << ans; else cout << "There is no common prefix"; return (0);}
// A Java Program to find the longest common prefix class GFG { // A Function to find the string having the // minimum length and returns that length static int findMinLength(String arr[], int n) { int min = Integer.MAX_VALUE; for (int i = 0; i <= (n - 1); i++) { if (arr[i].length() < min) { min = arr[i].length(); } } return min; } static boolean allContainsPrefix(String arr[], int n, String str, int start, int end) { for (int i = 0; i <= (n - 1); i++) { String arr_i = arr[i]; for (int j = start; j <= end; j++) if (arr_i.charAt(j) != str.charAt(j)) return false; } return true; } // A Function that returns the longest common prefix // from the array of strings static String commonPrefix(String arr[], int n) { int index = findMinLength(arr, n); String prefix = ""; // Our resultant string // We will do an in-place binary search on the // first string of the array in the range 0 to // index int low = 0, high = index-1; while (low <= high) { // Same as (low + high)/2, but avoids // overflow for large low and high int mid = low + (high - low) / 2; if (allContainsPrefix(arr, n, arr[0], low, mid)) { // If all the strings in the input array // contains this prefix then append this // substring to our answer prefix = prefix + arr[0].substring(low, mid + 1); // And then go for the right part low = mid + 1; } else // Go for the left part { high = mid - 1; } } return prefix; } // Driver program to test above function public static void main(String args[]) { String arr[] = {"geeksforgeeks", "geeks", "geek", "geezer"}; int n = arr.length; String ans = commonPrefix(arr, n); if (ans.length() > 0) System.out.println("The longest common" + " prefix is " + ans); else System.out.println("There is no common" + " prefix"); }} // This code is contributed by Indrajit Sinha.
# A Python3 Program to find# the longest common prefix # A Function to find the string having the# minimum length and returns that lengthdef findMinLength(strList): return len(min(arr, key = len)) def allContainsPrefix(strList, str, start, end): for i in range(0, len(strList)): word = strList[i] for j in range(start, end + 1): if word[j] != str[j]: return False return True # A Function that returns the longest# common prefix from the array of stringsdef CommonPrefix(strList): index = findMinLength(strList) prefix = "" # Our resultant string # We will do an in-place binary search # on the first string of the array # in the range 0 to index low, high = 0, index - 1 while low <= high: # Same as (low + high)/2, but avoids # overflow for large low and high mid = int(low + (high - low) / 2) if allContainsPrefix(strList, strList[0], low, mid): # If all the strings in the input array # contains this prefix then append this # substring to our answer prefix = prefix + strList[0][low:mid + 1] # And then go for the right part low = mid + 1 else: # Go for the left part high = mid - 1 return prefix # Driver Codearr = ["geeksforgeeks", "geeks", "geek", "geezer"]lcp = CommonPrefix(arr) if len(lcp) > 0: print ("The longest common prefix is " + str(lcp))else: print ("There is no common prefix") # This code is contributed by garychan8523
// C# Program to find the longest common prefix using System;using System; public class GFG { // A Function to find the string having the // minimum length and returns that length static int findMinLength(string []arr, int n) { int min = int.MaxValue; for (int i = 0; i <= (n - 1); i++) { if (arr[i].Length < min) { min = arr[i].Length; } } return min; } static bool allContainsPrefix(string []arr, int n, string str, int start, int end) { for (int i = 0; i <= (n - 1); i++) { string arr_i = arr[i]; for (int j = start; j <= end; j++) if (arr_i[j] != str[j]) return false; } return true; } // A Function that returns the longest common prefix // from the array of strings static string commonPrefix(string []arr, int n) { int index = findMinLength(arr, n); string prefix = ""; // Our resultant string // We will do an in-place binary search on the // first string of the array in the range 0 to // index int low = 0, high = index; while (low <= high) { // Same as (low + high)/2, but avoids // overflow for large low and high int mid = low + (high - low) / 2; if (allContainsPrefix(arr, n, arr[0], low, mid)) { // If all the strings in the input array // contains this prefix then append this // substring to our answer prefix = prefix + arr[0].Substring(low, mid + 1); // And then go for the right part low = mid + 1; } else // Go for the left part { high = mid - 1; } } return prefix; } // Driver program to test above function public static void Main() { string []arr = {"geeksforgeeks", "geeks", "geek", "geezer"}; int n = arr.Length; string ans = commonPrefix(arr, n); if (ans.Length > 0) Console.WriteLine("The longest common" + " prefix is - " + ans); else Console.WriteLine("There is no common" + " prefix"); }} // This code is contributed by PrinciRaj1992
<script>// A JavaScript Program to find the longest common prefix // A Function to find the string having the minimum// length and returns that lengthfunction findMinLength( arr , n){ var min = Number.POSITIVE_INFINITY; for (let i=0; i<=n-1; i++) if (arr[i].length< min) min = arr[i].length; return(min);} function allContainsPrefix( arr, n, str, start, end){ for (let i=0; i<=n-1; i++) for (let j=start; j<=end; j++) if (arr[i][j] != str[j]) return (false); return (true);} // A Function that returns the longest common prefix// from the array of stringsfunction commonPrefix( arr , n){ var index = findMinLength(arr, n); var prefix = ""; // Our resultant string // We will do an in-place binary search on the // first string of the array in the range 0 to // index var low = 0, high = index; while (low <= high) { // Same as (low + high)/2, but avoids overflow // for large low and high var mid = low + (high - low) / 2; if (allContainsPrefix (arr, n, arr[0], low, mid)) { // If all the strings in the input array contains // this prefix then append this substring to // our answer prefix = prefix + arr[0].substr(low, mid-low+1); // And then go for the right part low = mid + 1; } else // Go for the left part high = mid - 1; } return (prefix); } // Driver program to test above function var arr= new Array("geeksforgeeks", "geeks", "geek", "geezer"); var n = arr.length; var ans = commonPrefix(arr, n); if (ans.length) document.write("The longest common prefix is " + ans); else document.write("There is no common prefix"); // This code is contributed by ukasp.</script>
Output :
The longest common prefix is - gee
Time Complexity : The recurrence relation is
T(M) = T(M/2) + O(MN)
where
N = Number of strings
M = Length of the largest string
So we can say that the time complexity is O(NM log M)Auxiliary Space: To store the longest prefix string we are allocating space which is O(N) where, N = length of the largest string among all the strings This article is contributed by Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
indrajit1
Pratik Prajapati
princiraj1992
khyati agrawal
GreenBlack
garychan8523
ukasp
Accolite
Amazon
Binary Search
Longest Common Prefix
MakeMyTrip
Strings
Accolite
Amazon
MakeMyTrip
Strings
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Jan, 2022"
},
{
"code": null,
"e": 112,
"s": 54,
"text": "Given a set of strings, find the longest common prefix. "
},
{
"code": null,
"e": 267,
"s": 112,
"text": "Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”}\nOutput : \"gee\"\n\nInput : {\"apple\", \"ape\", \"april\"}\nOutput : \"ap\"\n\n\nInput : {\"abcd\"}\nOutput : \"abcd\""
},
{
"code": null,
"e": 437,
"s": 267,
"text": "Previous Approaches – Word by Word Matching , Character by Character Matching, Divide and Conquer In this article, an approach using Binary Search is discussed. Steps: "
},
{
"code": null,
"e": 1523,
"s": 437,
"text": "Find the string having the minimum length. Let this length be L.Perform a binary search on any one string (from the input array of strings). Let us take the first string and do a binary search on the characters from the index – 0 to L-1.Initially, take low = 0 and high = L-1 and divide the string into two halves – left (low to mid) and right (mid+1 to high).Check whether all the characters in the left half is present at the corresponding indices (low to mid) of all the strings or not. If it is present then we append this half to our prefix string and we look in the right half in a hope to find a longer prefix.(It is guaranteed that a common prefix string is there.)Otherwise, if all the characters in the left half is not present at the corresponding indices (low to mid) in all the strings, then we need not look at the right half as there is some character(s) in the left half itself which is not a part of the longest prefix string. So we indeed look at the left half in a hope to find a common prefix string. (It may be possible that we don’t find any common prefix string)"
},
{
"code": null,
"e": 1588,
"s": 1523,
"text": "Find the string having the minimum length. Let this length be L."
},
{
"code": null,
"e": 1762,
"s": 1588,
"text": "Perform a binary search on any one string (from the input array of strings). Let us take the first string and do a binary search on the characters from the index – 0 to L-1."
},
{
"code": null,
"e": 1886,
"s": 1762,
"text": "Initially, take low = 0 and high = L-1 and divide the string into two halves – left (low to mid) and right (mid+1 to high)."
},
{
"code": null,
"e": 2200,
"s": 1886,
"text": "Check whether all the characters in the left half is present at the corresponding indices (low to mid) of all the strings or not. If it is present then we append this half to our prefix string and we look in the right half in a hope to find a longer prefix.(It is guaranteed that a common prefix string is there.)"
},
{
"code": null,
"e": 2613,
"s": 2200,
"text": "Otherwise, if all the characters in the left half is not present at the corresponding indices (low to mid) in all the strings, then we need not look at the right half as there is some character(s) in the left half itself which is not a part of the longest prefix string. So we indeed look at the left half in a hope to find a common prefix string. (It may be possible that we don’t find any common prefix string)"
},
{
"code": null,
"e": 2705,
"s": 2613,
"text": "Algorithm Illustration considering strings as – “geeksforgeeks”, “geeks”, “geek”, “geezer” "
},
{
"code": null,
"e": 2758,
"s": 2709,
"text": "Below is the implementation of above approach. "
},
{
"code": null,
"e": 2762,
"s": 2758,
"text": "C++"
},
{
"code": null,
"e": 2767,
"s": 2762,
"text": "Java"
},
{
"code": null,
"e": 2775,
"s": 2767,
"text": "Python3"
},
{
"code": null,
"e": 2778,
"s": 2775,
"text": "C#"
},
{
"code": null,
"e": 2789,
"s": 2778,
"text": "Javascript"
},
{
"code": "// A C++ Program to find the longest common prefix#include<bits/stdc++.h>using namespace std; // A Function to find the string having the minimum// length and returns that lengthint findMinLength(string arr[], int n){ int min = INT_MAX; for (int i=0; i<=n-1; i++) if (arr[i].length() < min) min = arr[i].length(); return(min);} bool allContainsPrefix(string arr[], int n, string str, int start, int end){ for (int i=0; i<=n-1; i++) for (int j=start; j<=end; j++) if (arr[i][j] != str[j]) return (false); return (true);} // A Function that returns the longest common prefix// from the array of stringsstring commonPrefix(string arr[], int n){ int index = findMinLength(arr, n); string prefix; // Our resultant string // We will do an in-place binary search on the // first string of the array in the range 0 to // index int low = 0, high = index; while (low <= high) { // Same as (low + high)/2, but avoids overflow // for large low and high int mid = low + (high - low) / 2; if (allContainsPrefix (arr, n, arr[0], low, mid)) { // If all the strings in the input array contains // this prefix then append this substring to // our answer prefix = prefix + arr[0].substr(low, mid-low+1); // And then go for the right part low = mid + 1; } else // Go for the left part high = mid - 1; } return (prefix);} // Driver program to test above functionint main(){ string arr[] = {\"geeksforgeeks\", \"geeks\", \"geek\", \"geezer\"}; int n = sizeof (arr) / sizeof (arr[0]); string ans = commonPrefix(arr, n); if (ans.length()) cout << \"The longest common prefix is \" << ans; else cout << \"There is no common prefix\"; return (0);}",
"e": 4716,
"s": 2789,
"text": null
},
{
"code": "// A Java Program to find the longest common prefix class GFG { // A Function to find the string having the // minimum length and returns that length static int findMinLength(String arr[], int n) { int min = Integer.MAX_VALUE; for (int i = 0; i <= (n - 1); i++) { if (arr[i].length() < min) { min = arr[i].length(); } } return min; } static boolean allContainsPrefix(String arr[], int n, String str, int start, int end) { for (int i = 0; i <= (n - 1); i++) { String arr_i = arr[i]; for (int j = start; j <= end; j++) if (arr_i.charAt(j) != str.charAt(j)) return false; } return true; } // A Function that returns the longest common prefix // from the array of strings static String commonPrefix(String arr[], int n) { int index = findMinLength(arr, n); String prefix = \"\"; // Our resultant string // We will do an in-place binary search on the // first string of the array in the range 0 to // index int low = 0, high = index-1; while (low <= high) { // Same as (low + high)/2, but avoids // overflow for large low and high int mid = low + (high - low) / 2; if (allContainsPrefix(arr, n, arr[0], low, mid)) { // If all the strings in the input array // contains this prefix then append this // substring to our answer prefix = prefix + arr[0].substring(low, mid + 1); // And then go for the right part low = mid + 1; } else // Go for the left part { high = mid - 1; } } return prefix; } // Driver program to test above function public static void main(String args[]) { String arr[] = {\"geeksforgeeks\", \"geeks\", \"geek\", \"geezer\"}; int n = arr.length; String ans = commonPrefix(arr, n); if (ans.length() > 0) System.out.println(\"The longest common\" + \" prefix is \" + ans); else System.out.println(\"There is no common\" + \" prefix\"); }} // This code is contributed by Indrajit Sinha.",
"e": 7279,
"s": 4716,
"text": null
},
{
"code": "# A Python3 Program to find# the longest common prefix # A Function to find the string having the# minimum length and returns that lengthdef findMinLength(strList): return len(min(arr, key = len)) def allContainsPrefix(strList, str, start, end): for i in range(0, len(strList)): word = strList[i] for j in range(start, end + 1): if word[j] != str[j]: return False return True # A Function that returns the longest# common prefix from the array of stringsdef CommonPrefix(strList): index = findMinLength(strList) prefix = \"\" # Our resultant string # We will do an in-place binary search # on the first string of the array # in the range 0 to index low, high = 0, index - 1 while low <= high: # Same as (low + high)/2, but avoids # overflow for large low and high mid = int(low + (high - low) / 2) if allContainsPrefix(strList, strList[0], low, mid): # If all the strings in the input array # contains this prefix then append this # substring to our answer prefix = prefix + strList[0][low:mid + 1] # And then go for the right part low = mid + 1 else: # Go for the left part high = mid - 1 return prefix # Driver Codearr = [\"geeksforgeeks\", \"geeks\", \"geek\", \"geezer\"]lcp = CommonPrefix(arr) if len(lcp) > 0: print (\"The longest common prefix is \" + str(lcp))else: print (\"There is no common prefix\") # This code is contributed by garychan8523",
"e": 8945,
"s": 7279,
"text": null
},
{
"code": "// C# Program to find the longest common prefix using System;using System; public class GFG { // A Function to find the string having the // minimum length and returns that length static int findMinLength(string []arr, int n) { int min = int.MaxValue; for (int i = 0; i <= (n - 1); i++) { if (arr[i].Length < min) { min = arr[i].Length; } } return min; } static bool allContainsPrefix(string []arr, int n, string str, int start, int end) { for (int i = 0; i <= (n - 1); i++) { string arr_i = arr[i]; for (int j = start; j <= end; j++) if (arr_i[j] != str[j]) return false; } return true; } // A Function that returns the longest common prefix // from the array of strings static string commonPrefix(string []arr, int n) { int index = findMinLength(arr, n); string prefix = \"\"; // Our resultant string // We will do an in-place binary search on the // first string of the array in the range 0 to // index int low = 0, high = index; while (low <= high) { // Same as (low + high)/2, but avoids // overflow for large low and high int mid = low + (high - low) / 2; if (allContainsPrefix(arr, n, arr[0], low, mid)) { // If all the strings in the input array // contains this prefix then append this // substring to our answer prefix = prefix + arr[0].Substring(low, mid + 1); // And then go for the right part low = mid + 1; } else // Go for the left part { high = mid - 1; } } return prefix; } // Driver program to test above function public static void Main() { string []arr = {\"geeksforgeeks\", \"geeks\", \"geek\", \"geezer\"}; int n = arr.Length; string ans = commonPrefix(arr, n); if (ans.Length > 0) Console.WriteLine(\"The longest common\" + \" prefix is - \" + ans); else Console.WriteLine(\"There is no common\" + \" prefix\"); }} // This code is contributed by PrinciRaj1992",
"e": 11519,
"s": 8945,
"text": null
},
{
"code": "<script>// A JavaScript Program to find the longest common prefix // A Function to find the string having the minimum// length and returns that lengthfunction findMinLength( arr , n){ var min = Number.POSITIVE_INFINITY; for (let i=0; i<=n-1; i++) if (arr[i].length< min) min = arr[i].length; return(min);} function allContainsPrefix( arr, n, str, start, end){ for (let i=0; i<=n-1; i++) for (let j=start; j<=end; j++) if (arr[i][j] != str[j]) return (false); return (true);} // A Function that returns the longest common prefix// from the array of stringsfunction commonPrefix( arr , n){ var index = findMinLength(arr, n); var prefix = \"\"; // Our resultant string // We will do an in-place binary search on the // first string of the array in the range 0 to // index var low = 0, high = index; while (low <= high) { // Same as (low + high)/2, but avoids overflow // for large low and high var mid = low + (high - low) / 2; if (allContainsPrefix (arr, n, arr[0], low, mid)) { // If all the strings in the input array contains // this prefix then append this substring to // our answer prefix = prefix + arr[0].substr(low, mid-low+1); // And then go for the right part low = mid + 1; } else // Go for the left part high = mid - 1; } return (prefix); } // Driver program to test above function var arr= new Array(\"geeksforgeeks\", \"geeks\", \"geek\", \"geezer\"); var n = arr.length; var ans = commonPrefix(arr, n); if (ans.length) document.write(\"The longest common prefix is \" + ans); else document.write(\"There is no common prefix\"); // This code is contributed by ukasp.</script>",
"e": 13422,
"s": 11519,
"text": null
},
{
"code": null,
"e": 13433,
"s": 13422,
"text": "Output : "
},
{
"code": null,
"e": 13468,
"s": 13433,
"text": "The longest common prefix is - gee"
},
{
"code": null,
"e": 13515,
"s": 13468,
"text": "Time Complexity : The recurrence relation is "
},
{
"code": null,
"e": 13538,
"s": 13515,
"text": "T(M) = T(M/2) + O(MN) "
},
{
"code": null,
"e": 13546,
"s": 13538,
"text": "where "
},
{
"code": null,
"e": 13601,
"s": 13546,
"text": "N = Number of strings\nM = Length of the largest string"
},
{
"code": null,
"e": 14230,
"s": 13601,
"text": "So we can say that the time complexity is O(NM log M)Auxiliary Space: To store the longest prefix string we are allocating space which is O(N) where, N = length of the largest string among all the strings This article is contributed by Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 14240,
"s": 14230,
"text": "indrajit1"
},
{
"code": null,
"e": 14257,
"s": 14240,
"text": "Pratik Prajapati"
},
{
"code": null,
"e": 14271,
"s": 14257,
"text": "princiraj1992"
},
{
"code": null,
"e": 14286,
"s": 14271,
"text": "khyati agrawal"
},
{
"code": null,
"e": 14297,
"s": 14286,
"text": "GreenBlack"
},
{
"code": null,
"e": 14310,
"s": 14297,
"text": "garychan8523"
},
{
"code": null,
"e": 14316,
"s": 14310,
"text": "ukasp"
},
{
"code": null,
"e": 14325,
"s": 14316,
"text": "Accolite"
},
{
"code": null,
"e": 14332,
"s": 14325,
"text": "Amazon"
},
{
"code": null,
"e": 14346,
"s": 14332,
"text": "Binary Search"
},
{
"code": null,
"e": 14368,
"s": 14346,
"text": "Longest Common Prefix"
},
{
"code": null,
"e": 14379,
"s": 14368,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 14387,
"s": 14379,
"text": "Strings"
},
{
"code": null,
"e": 14396,
"s": 14387,
"text": "Accolite"
},
{
"code": null,
"e": 14403,
"s": 14396,
"text": "Amazon"
},
{
"code": null,
"e": 14414,
"s": 14403,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 14422,
"s": 14414,
"text": "Strings"
},
{
"code": null,
"e": 14436,
"s": 14422,
"text": "Binary Search"
}
]
|
Lookup and Reference - INDEX Function | The INDEX function returns a value or the reference to a value from within a table or range. You can use INDEX function in two ways −
To return the value of a specified cell or array of cells.
To return a reference to specified cells.
Use this if the first argument to INDEX is an array constant.
Description
The function returns the value of an element in a table or an array, selected by the row and column number indexes.
Syntax
INDEX (array, row_num, [column_num])
Arguments
A range of cells or an array constant.
If array contains only one row or column, the corresponding Row_num or Column_num argument is optional.
If array has more than one row and more than one column, and only Row_num or Column_num is used, INDEX returns an array of the entire row or column in array.
Selects the row in array from which to return a value. If Row_num is omitted, Column_num is required.
Selects the column in array from which to return a value.
If Column_num is omitted, Row_num is required.
Notes
If both the Row_num and Column_num arguments are used, INDEX returns the value in the cell at the intersection of Row_num and Column_num.
If both the Row_num and Column_num arguments are used, INDEX returns the value in the cell at the intersection of Row_num and Column_num.
If you set Row_num or Column_num to 0 (zero), INDEX returns the array of values for the entire column or row, respectively. To use values returned as an array, enter the INDEX function as an array formula in a horizontal range of cells for a row, and in a vertical range of cells for a column. To enter an array formula, press CTRL+SHIFT+ENTER
If you set Row_num or Column_num to 0 (zero), INDEX returns the array of values for the entire column or row, respectively. To use values returned as an array, enter the INDEX function as an array formula in a horizontal range of cells for a row, and in a vertical range of cells for a column. To enter an array formula, press CTRL+SHIFT+ENTER
Row_num and Column_num must point to a cell within array. Otherwise, INDEX returns the #REF! error value.
Row_num and Column_num must point to a cell within array. Otherwise, INDEX returns the #REF! error value.
Description
The function returns the reference of the cell at the intersection of a particular row and column. If the reference is made up of nonadjacent selections, you can pick the selection to look in.
Syntax
INDEX (reference, row_num, [column_num], [area_num])
Arguments
A reference to one or more cell ranges.
If you are entering a nonadjacent range for the reference, enclose reference in parentheses.
If each area in reference contains only one row or column, the Row_num or Column_num argument, respectively, is optional. E.g. for a single row reference, use −
INDEX(reference,,column_num)
The number of the row in reference from which to return a reference.
The number of the column in reference from which to return a reference.
Selects a range in reference from which to return the intersection of Row_num and Column_num. The first area selected or entered is numbered 1, the second is 2, and so on.
If Area_num is omitted, INDEX uses area 1.
Notes
After Reference and Area_num have selected a particular range, Row_num and Column_num select a particular cell: Row_num 1 is the first row in the range, Column_num 1 is the first column, and so on. The reference returned by INDEX is the intersection of Row_num and Column_num.
After Reference and Area_num have selected a particular range, Row_num and Column_num select a particular cell: Row_num 1 is the first row in the range, Column_num 1 is the first column, and so on. The reference returned by INDEX is the intersection of Row_num and Column_num.
If you set Row_num or Column_num to 0 (zero), INDEX returns the reference for the entire column or row, respectively.
If you set Row_num or Column_num to 0 (zero), INDEX returns the reference for the entire column or row, respectively.
Row_num, Column_num, and Area_num must point to a cell within reference. Otherwise, INDEX returns the #REF! Error value. If Row_num and Column_num are omitted, INDEX returns the area in reference specified by Area_num.
Row_num, Column_num, and Area_num must point to a cell within reference. Otherwise, INDEX returns the #REF! Error value. If Row_num and Column_num are omitted, INDEX returns the area in reference specified by Area_num.
The result of the INDEX function is a reference and is interpreted as such by other formulas. Depending on the formula, the return value of INDEX may be used as a reference or as a value. For example, the formula CELL("width",INDEX(A1:B2,1,2)) is equivalent to CELL("width",B1). The CELL function uses the return value of INDEX as a cell reference. On the other hand, a formula such as 2*INDEX(A1:B2,1,2) translates the return value of INDEX into the number in cell B1.
The result of the INDEX function is a reference and is interpreted as such by other formulas. Depending on the formula, the return value of INDEX may be used as a reference or as a value. For example, the formula CELL("width",INDEX(A1:B2,1,2)) is equivalent to CELL("width",B1). The CELL function uses the return value of INDEX as a cell reference. On the other hand, a formula such as 2*INDEX(A1:B2,1,2) translates the return value of INDEX into the number in cell B1.
Excel 2007, Excel 2010, Excel 2013, Excel 2016
296 Lectures
146 hours
Arun Motoori
56 Lectures
5.5 hours
Pavan Lalwani
120 Lectures
6.5 hours
Inf Sid
134 Lectures
8.5 hours
Yoda Learning
46 Lectures
7.5 hours
William Fiset
25 Lectures
1.5 hours
Sasha Miller
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1988,
"s": 1854,
"text": "The INDEX function returns a value or the reference to a value from within a table or range. You can use INDEX function in two ways −"
},
{
"code": null,
"e": 2047,
"s": 1988,
"text": "To return the value of a specified cell or array of cells."
},
{
"code": null,
"e": 2089,
"s": 2047,
"text": "To return a reference to specified cells."
},
{
"code": null,
"e": 2151,
"s": 2089,
"text": "Use this if the first argument to INDEX is an array constant."
},
{
"code": null,
"e": 2163,
"s": 2151,
"text": "Description"
},
{
"code": null,
"e": 2279,
"s": 2163,
"text": "The function returns the value of an element in a table or an array, selected by the row and column number indexes."
},
{
"code": null,
"e": 2286,
"s": 2279,
"text": "Syntax"
},
{
"code": null,
"e": 2325,
"s": 2286,
"text": "INDEX (array, row_num, [column_num]) \n"
},
{
"code": null,
"e": 2335,
"s": 2325,
"text": "Arguments"
},
{
"code": null,
"e": 2374,
"s": 2335,
"text": "A range of cells or an array constant."
},
{
"code": null,
"e": 2478,
"s": 2374,
"text": "If array contains only one row or column, the corresponding Row_num or Column_num argument is optional."
},
{
"code": null,
"e": 2636,
"s": 2478,
"text": "If array has more than one row and more than one column, and only Row_num or Column_num is used, INDEX returns an array of the entire row or column in array."
},
{
"code": null,
"e": 2738,
"s": 2636,
"text": "Selects the row in array from which to return a value. If Row_num is omitted, Column_num is required."
},
{
"code": null,
"e": 2796,
"s": 2738,
"text": "Selects the column in array from which to return a value."
},
{
"code": null,
"e": 2843,
"s": 2796,
"text": "If Column_num is omitted, Row_num is required."
},
{
"code": null,
"e": 2849,
"s": 2843,
"text": "Notes"
},
{
"code": null,
"e": 2987,
"s": 2849,
"text": "If both the Row_num and Column_num arguments are used, INDEX returns the value in the cell at the intersection of Row_num and Column_num."
},
{
"code": null,
"e": 3125,
"s": 2987,
"text": "If both the Row_num and Column_num arguments are used, INDEX returns the value in the cell at the intersection of Row_num and Column_num."
},
{
"code": null,
"e": 3469,
"s": 3125,
"text": "If you set Row_num or Column_num to 0 (zero), INDEX returns the array of values for the entire column or row, respectively. To use values returned as an array, enter the INDEX function as an array formula in a horizontal range of cells for a row, and in a vertical range of cells for a column. To enter an array formula, press CTRL+SHIFT+ENTER"
},
{
"code": null,
"e": 3813,
"s": 3469,
"text": "If you set Row_num or Column_num to 0 (zero), INDEX returns the array of values for the entire column or row, respectively. To use values returned as an array, enter the INDEX function as an array formula in a horizontal range of cells for a row, and in a vertical range of cells for a column. To enter an array formula, press CTRL+SHIFT+ENTER"
},
{
"code": null,
"e": 3919,
"s": 3813,
"text": "Row_num and Column_num must point to a cell within array. Otherwise, INDEX returns the #REF! error value."
},
{
"code": null,
"e": 4025,
"s": 3919,
"text": "Row_num and Column_num must point to a cell within array. Otherwise, INDEX returns the #REF! error value."
},
{
"code": null,
"e": 4037,
"s": 4025,
"text": "Description"
},
{
"code": null,
"e": 4230,
"s": 4037,
"text": "The function returns the reference of the cell at the intersection of a particular row and column. If the reference is made up of nonadjacent selections, you can pick the selection to look in."
},
{
"code": null,
"e": 4237,
"s": 4230,
"text": "Syntax"
},
{
"code": null,
"e": 4292,
"s": 4237,
"text": "INDEX (reference, row_num, [column_num], [area_num]) \n"
},
{
"code": null,
"e": 4302,
"s": 4292,
"text": "Arguments"
},
{
"code": null,
"e": 4342,
"s": 4302,
"text": "A reference to one or more cell ranges."
},
{
"code": null,
"e": 4435,
"s": 4342,
"text": "If you are entering a nonadjacent range for the reference, enclose reference in parentheses."
},
{
"code": null,
"e": 4596,
"s": 4435,
"text": "If each area in reference contains only one row or column, the Row_num or Column_num argument, respectively, is optional. E.g. for a single row reference, use −"
},
{
"code": null,
"e": 4625,
"s": 4596,
"text": "INDEX(reference,,column_num)"
},
{
"code": null,
"e": 4694,
"s": 4625,
"text": "The number of the row in reference from which to return a reference."
},
{
"code": null,
"e": 4766,
"s": 4694,
"text": "The number of the column in reference from which to return a reference."
},
{
"code": null,
"e": 4938,
"s": 4766,
"text": "Selects a range in reference from which to return the intersection of Row_num and Column_num. The first area selected or entered is numbered 1, the second is 2, and so on."
},
{
"code": null,
"e": 4981,
"s": 4938,
"text": "If Area_num is omitted, INDEX uses area 1."
},
{
"code": null,
"e": 4987,
"s": 4981,
"text": "Notes"
},
{
"code": null,
"e": 5264,
"s": 4987,
"text": "After Reference and Area_num have selected a particular range, Row_num and Column_num select a particular cell: Row_num 1 is the first row in the range, Column_num 1 is the first column, and so on. The reference returned by INDEX is the intersection of Row_num and Column_num."
},
{
"code": null,
"e": 5541,
"s": 5264,
"text": "After Reference and Area_num have selected a particular range, Row_num and Column_num select a particular cell: Row_num 1 is the first row in the range, Column_num 1 is the first column, and so on. The reference returned by INDEX is the intersection of Row_num and Column_num."
},
{
"code": null,
"e": 5659,
"s": 5541,
"text": "If you set Row_num or Column_num to 0 (zero), INDEX returns the reference for the entire column or row, respectively."
},
{
"code": null,
"e": 5777,
"s": 5659,
"text": "If you set Row_num or Column_num to 0 (zero), INDEX returns the reference for the entire column or row, respectively."
},
{
"code": null,
"e": 5996,
"s": 5777,
"text": "Row_num, Column_num, and Area_num must point to a cell within reference. Otherwise, INDEX returns the #REF! Error value. If Row_num and Column_num are omitted, INDEX returns the area in reference specified by Area_num."
},
{
"code": null,
"e": 6215,
"s": 5996,
"text": "Row_num, Column_num, and Area_num must point to a cell within reference. Otherwise, INDEX returns the #REF! Error value. If Row_num and Column_num are omitted, INDEX returns the area in reference specified by Area_num."
},
{
"code": null,
"e": 6685,
"s": 6215,
"text": "The result of the INDEX function is a reference and is interpreted as such by other formulas. Depending on the formula, the return value of INDEX may be used as a reference or as a value. For example, the formula CELL(\"width\",INDEX(A1:B2,1,2)) is equivalent to CELL(\"width\",B1). The CELL function uses the return value of INDEX as a cell reference. On the other hand, a formula such as 2*INDEX(A1:B2,1,2) translates the return value of INDEX into the number in cell B1."
},
{
"code": null,
"e": 7155,
"s": 6685,
"text": "The result of the INDEX function is a reference and is interpreted as such by other formulas. Depending on the formula, the return value of INDEX may be used as a reference or as a value. For example, the formula CELL(\"width\",INDEX(A1:B2,1,2)) is equivalent to CELL(\"width\",B1). The CELL function uses the return value of INDEX as a cell reference. On the other hand, a formula such as 2*INDEX(A1:B2,1,2) translates the return value of INDEX into the number in cell B1."
},
{
"code": null,
"e": 7202,
"s": 7155,
"text": "Excel 2007, Excel 2010, Excel 2013, Excel 2016"
},
{
"code": null,
"e": 7238,
"s": 7202,
"text": "\n 296 Lectures \n 146 hours \n"
},
{
"code": null,
"e": 7252,
"s": 7238,
"text": " Arun Motoori"
},
{
"code": null,
"e": 7287,
"s": 7252,
"text": "\n 56 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 7302,
"s": 7287,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 7338,
"s": 7302,
"text": "\n 120 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 7347,
"s": 7338,
"text": " Inf Sid"
},
{
"code": null,
"e": 7383,
"s": 7347,
"text": "\n 134 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 7398,
"s": 7383,
"text": " Yoda Learning"
},
{
"code": null,
"e": 7433,
"s": 7398,
"text": "\n 46 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 7448,
"s": 7433,
"text": " William Fiset"
},
{
"code": null,
"e": 7483,
"s": 7448,
"text": "\n 25 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7497,
"s": 7483,
"text": " Sasha Miller"
},
{
"code": null,
"e": 7504,
"s": 7497,
"text": " Print"
},
{
"code": null,
"e": 7515,
"s": 7504,
"text": " Add Notes"
}
]
|
D3.js axis.tickSize() Function - GeeksforGeeks | 18 Aug, 2020
The d3.axis.tickSize() function in D3.js is used to set the inner and outer tick size to the specified value and returns the axis. If size is not specified, returns the current inner tick size, which defaults to 6.
Syntax:
axis.tickSize([size])
Parameters: This function accepts single parameter as mentioned above and described below:
size: This parameter holds the size to set the inner and outer tick size.
Return Value: This function returns the axis.
Below programs illustrate the d3.axis.tickSize() function in D3.js:
Example 1:
HTML
<!DOCTYPE html> <html> <head> <title> D3.js | D3.axis.tickSize() Function </title> <script type="text/javascript" src="https://d3js.org/d3.v4.min.js"> </script> <style> svg text { fill: green; font: 15px sans-serif; text-anchor: center; } </style> </head> <body> <script> var width = 400, height = 400; var svg = d3.select("body") .append("svg") .attr("width", width) .attr("height", height); var xscale = d3.scaleLinear() .domain([0, 10]) .range([0, width - 60]); var x_axis = d3.axisBottom() .scale(xscale).tickSize(15); var xAxisTranslate = height / 2; svg.append("g") .attr("transform", "translate(50, " + xAxisTranslate + ")") .call(x_axis) </script> </body> </html>
Output:
Example 2:
HTML
<!DOCTYPE html> <html> <head> <title> D3.js | D3.axis.tickSize() Function </title> <script type="text/javascript" src="https://d3js.org/d3.v4.min.js"> </script> <style> svg text { fill: green; font: 15px sans-serif; text-anchor: center; } </style> </head> <body> <script> var width = 400, height = 400; var svg = d3.select("body") .append("svg") .attr("width", width) .attr("height", height); var yscale = d3.scaleLinear() .domain([0, 1]) .range([height - 50, 0]); var y_axis = d3.axisRight() .scale(yscale).tickSize(0); svg.append("g") .attr("transform", "translate(100,20)") .call(y_axis) </script> </body> </html>
Output:
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
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": 24916,
"s": 24888,
"text": "\n18 Aug, 2020"
},
{
"code": null,
"e": 25131,
"s": 24916,
"text": "The d3.axis.tickSize() function in D3.js is used to set the inner and outer tick size to the specified value and returns the axis. If size is not specified, returns the current inner tick size, which defaults to 6."
},
{
"code": null,
"e": 25139,
"s": 25131,
"text": "Syntax:"
},
{
"code": null,
"e": 25161,
"s": 25139,
"text": "axis.tickSize([size])"
},
{
"code": null,
"e": 25252,
"s": 25161,
"text": "Parameters: This function accepts single parameter as mentioned above and described below:"
},
{
"code": null,
"e": 25326,
"s": 25252,
"text": "size: This parameter holds the size to set the inner and outer tick size."
},
{
"code": null,
"e": 25372,
"s": 25326,
"text": "Return Value: This function returns the axis."
},
{
"code": null,
"e": 25440,
"s": 25372,
"text": "Below programs illustrate the d3.axis.tickSize() function in D3.js:"
},
{
"code": null,
"e": 25451,
"s": 25440,
"text": "Example 1:"
},
{
"code": null,
"e": 25456,
"s": 25451,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <html> <head> <title> D3.js | D3.axis.tickSize() Function </title> <script type=\"text/javascript\" src=\"https://d3js.org/d3.v4.min.js\"> </script> <style> svg text { fill: green; font: 15px sans-serif; text-anchor: center; } </style> </head> <body> <script> var width = 400, height = 400; var svg = d3.select(\"body\") .append(\"svg\") .attr(\"width\", width) .attr(\"height\", height); var xscale = d3.scaleLinear() .domain([0, 10]) .range([0, width - 60]); var x_axis = d3.axisBottom() .scale(xscale).tickSize(15); var xAxisTranslate = height / 2; svg.append(\"g\") .attr(\"transform\", \"translate(50, \" + xAxisTranslate + \")\") .call(x_axis) </script> </body> </html>",
"e": 26421,
"s": 25456,
"text": null
},
{
"code": null,
"e": 26429,
"s": 26421,
"text": "Output:"
},
{
"code": null,
"e": 26440,
"s": 26429,
"text": "Example 2:"
},
{
"code": null,
"e": 26445,
"s": 26440,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <html> <head> <title> D3.js | D3.axis.tickSize() Function </title> <script type=\"text/javascript\" src=\"https://d3js.org/d3.v4.min.js\"> </script> <style> svg text { fill: green; font: 15px sans-serif; text-anchor: center; } </style> </head> <body> <script> var width = 400, height = 400; var svg = d3.select(\"body\") .append(\"svg\") .attr(\"width\", width) .attr(\"height\", height); var yscale = d3.scaleLinear() .domain([0, 1]) .range([height - 50, 0]); var y_axis = d3.axisRight() .scale(yscale).tickSize(0); svg.append(\"g\") .attr(\"transform\", \"translate(100,20)\") .call(y_axis) </script> </body> </html>",
"e": 27326,
"s": 26445,
"text": null
},
{
"code": null,
"e": 27334,
"s": 27326,
"text": "Output:"
},
{
"code": null,
"e": 27340,
"s": 27334,
"text": "D3.js"
},
{
"code": null,
"e": 27351,
"s": 27340,
"text": "JavaScript"
},
{
"code": null,
"e": 27368,
"s": 27351,
"text": "Web Technologies"
},
{
"code": null,
"e": 27466,
"s": 27368,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27511,
"s": 27466,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27572,
"s": 27511,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27644,
"s": 27572,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 27696,
"s": 27644,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 27742,
"s": 27696,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 27784,
"s": 27742,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27817,
"s": 27784,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27860,
"s": 27817,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27922,
"s": 27860,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
]
|
How to create a responsive navigation menu with icons, using CSS?
| Following is the code for creating the responsive navigation menu with icons.
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body{
margin:0px;
margin-top:10px;
padding: 0px;
}
nav{
width: 100%;
background-color: rgb(39, 39, 39);
overflow: auto;
height: auto;
}
.links {
display: inline-block;
text-align: center;
padding: 14px;
color: rgb(178, 137, 253);
text-decoration: none;
font-size: 17px;
}
.links:hover {
background-color: rgb(100, 100, 100);
}
.selected{
background-color: rgb(0, 18, 43);
}
@media screen and (max-width: 600px) {
.links {
display: block;
}
}
</style>
</head>
<body>
<nav>
<a class="links selected" href="#"><i class="fa fa-fw fa-home"></i> Home</a>
<a class="links" href="#"><i class="fa fa-fw fa-user"></i> Login</a>
<a class="links" href="#"><i class="fa fa-user-circle-o" aria-hidden="true"></i> Register</a>
<a class="links" href="#"><i class="fa fa-fw fa-envelope"></i> Contact Us</a>
<a class="links" href="#"><i class="fa fa-info-circle" aria-hidden="true"></i> More Info</a>
</nav>
</body>
</html>
The above code will produce the following output −
When the screen will be resized to 600px − | [
{
"code": null,
"e": 1140,
"s": 1062,
"text": "Following is the code for creating the responsive navigation menu with icons."
},
{
"code": null,
"e": 1151,
"s": 1140,
"text": " Live Demo"
},
{
"code": null,
"e": 2295,
"s": 1151,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>Document</title>\n<style>\nbody{\n margin:0px;\n margin-top:10px;\n padding: 0px;\n}\nnav{\n width: 100%;\n background-color: rgb(39, 39, 39);\n overflow: auto;\n height: auto;\n}\n.links {\n display: inline-block;\n text-align: center;\n padding: 14px;\n color: rgb(178, 137, 253);\n text-decoration: none;\n font-size: 17px;\n}\n.links:hover {\n background-color: rgb(100, 100, 100);\n}\n.selected{\n background-color: rgb(0, 18, 43);\n}\n@media screen and (max-width: 600px) {\n .links {\n display: block;\n }\n}\n</style>\n</head>\n<body>\n<nav>\n <a class=\"links selected\" href=\"#\"><i class=\"fa fa-fw fa-home\"></i> Home</a>\n <a class=\"links\" href=\"#\"><i class=\"fa fa-fw fa-user\"></i> Login</a>\n <a class=\"links\" href=\"#\"><i class=\"fa fa-user-circle-o\" aria-hidden=\"true\"></i> Register</a>\n <a class=\"links\" href=\"#\"><i class=\"fa fa-fw fa-envelope\"></i> Contact Us</a>\n <a class=\"links\" href=\"#\"><i class=\"fa fa-info-circle\" aria-hidden=\"true\"></i> More Info</a>\n</nav>\n</body>\n</html>"
},
{
"code": null,
"e": 2346,
"s": 2295,
"text": "The above code will produce the following output −"
},
{
"code": null,
"e": 2389,
"s": 2346,
"text": "When the screen will be resized to 600px −"
}
]
|
JavaScript: How to loop through all DOM elements on a page and display result on console? | To loop through all DOM elements on a page, use document.getElementsByTagName(‘*’). Loop
through its length and display the result in console as in the below code −
var tags = document.getElementsByTagName("*");
for (var i=0, max=tags.length; i < max; i++) {
console.log(tags[i]);
}
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<h1>Demo</h1>
<label>
Enter the name:
<input type="text" id="txtName">
</label>
<button type="submit">Save</button>
<script>
var tags = document.getElementsByTagName("*");
for (var i=0, max=tags.length; i < max; i++) {
console.log(tags[i]);
}
</script>
</body>
</html>
To run the above program, save the file name “anyName.html(index.html)” and right click on the file. Select the option “Open with Live Server” in VS Code editor.
This will produce the following output − | [
{
"code": null,
"e": 1227,
"s": 1062,
"text": "To loop through all DOM elements on a page, use document.getElementsByTagName(‘*’). Loop\nthrough its length and display the result in console as in the below code −"
},
{
"code": null,
"e": 1348,
"s": 1227,
"text": "var tags = document.getElementsByTagName(\"*\");\nfor (var i=0, max=tags.length; i < max; i++) {\n console.log(tags[i]);\n}"
},
{
"code": null,
"e": 1359,
"s": 1348,
"text": " Live Demo"
},
{
"code": null,
"e": 2036,
"s": 1359,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initialscale=1.0\">\n<title>Document</title>\n<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n</head>\n<body>\n<h1>Demo</h1>\n<label>\nEnter the name:\n<input type=\"text\" id=\"txtName\">\n</label>\n<button type=\"submit\">Save</button>\n<script>\n var tags = document.getElementsByTagName(\"*\");\n for (var i=0, max=tags.length; i < max; i++) {\n console.log(tags[i]);\n }\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2198,
"s": 2036,
"text": "To run the above program, save the file name “anyName.html(index.html)” and right click on the file. Select the option “Open with Live Server” in VS Code editor."
},
{
"code": null,
"e": 2239,
"s": 2198,
"text": "This will produce the following output −"
}
]
|
Join Multiple Tables Using Inner Join - GeeksforGeeks | 27 May, 2021
To retrieve data from the single table we use SELECT and PROJECTION operations but to retrieve data from multiple tables we use JOINS in SQL. There are different types of JOINS in SQL. In this article, only operations on inner joins in MSSQL are discussed.
Inner Join is the method of retrieval of data from multiple tables based on a required condition and necessary conditions are that there must be common columns or matched columns between the two tables of the database and the data types of columns must be the same.
Let us see how to join two tables and three tables using Inner Join in MSSQL step-by-step.
Creating a database GeeksForGeeks by using the following SQL query as follows.
CREATE DATABASE GeeksForGeeks;
Using the database student using the following SQL query as follows.
USE GeeksForGeeks;
Creating three tables student, course, and lecturer with SQL query as follows:
CREATE TABLE student
( stu_id varchar(10),
stu_name varchar(20),
course_id varchar(10),
branch varchar(20),
lecturer_id varchar(10)
);
CREATE TABLE course
(
course_id varchar(10),
course_name varchar(20)
);
CREATE TABLE lecturer
(
lecturer_id varchar(10),
lecturer_name varchar(20)
);
To view the description of the three tables in the database GeeksForGeeks using the following SQL query as follows.
EXEC sp_columns student;
EXEC sp_columns course;
EXEC sp_columns lecturer;
Inserting rows into student table using the following SQL query as follows:
INSERT INTO student VALUES
('1901401','DEVA','CS1003','C.S', 'P4002'),
('1901402','HARSH','CS1001','C.S', 'P4001'),
('1901403','ABHISHEK','CS1001','C.S', 'P4001'),
('1901404','GARVIT','CS1002','C.S', 'P4003'),
('1901405','SAMPATH','CS1003','C.S', 'P4002'),
('1901406','SATWIK','CS1002','C.S', 'P4003'),
('1901407','GUPTA','CS1001','C.S', 'P4001'),
('1901408','DAS','CS1003','C.S', 'P4002');
Inserting rows into the course table using the following SQL query as follows:
INSERT INTO course VALUES
('CS1001', 'DBMS'),
('CS1002', 'O.S'),
('CS1003', 'C.N'),
('CS1004', 'M.L'),
('CS1005', 'A.I');
Inserting rows into lecturer table using the following SQL query as follows:
INSERT INTO lecturer VALUES
('P4001', 'RAMESH'),
('P4002', 'RAVINDER'),
('P4003', 'RAHUL SHARMA'),
('P4004', 'PRADEEP KUMAR'),
('P4005', 'SRINIVASA RAO');
Viewing the three tables after inserting rows by using the following SQL query as follows.
SELECT* FROM student;
SELECT* FROM course;
SELECT* FROM lecturer;
The syntax for multiple joins:
SELECT column_name1,column_name2,..
FROM table_name1
INNER JOIN
table_name2
ON condition_1
INNER JOIN
table_name3
ON condition_2
INNER JOIN
table_name4
ON condition_3
.
.
.
Note: While selecting only particular columns use table_name. column_name when there are the same column names in the two tables otherwise you will get an ambiguous error.
Inner Join on two tables student and course:
SELECT *
FROM student
INNER JOIN
course
ON
student.course_id = course.course_id;
All the columns of 2 tables appear that satisfy the equality condition
Inner Join on three tables student, course, and lecturer:
SELECT *
FROM student
INNER JOIN
course
ON
student.course_id = course.course_id
INNER JOIN
lecturer
ON
student.lecturer_id = lecturer.lecturer_id;
All the columns of 3 tables appear that satisfy the equality condition
Inner join on three tables student, course, lecturer but by selecting particular columns of a particular table.
SELECT stu_id, stu_name,course.course_id,course.course_name,
lecturer.lecturer_name
FROM student
INNER JOIN
course
ON
student.course_id = course.course_id
INNER JOIN
lecturer
ON
student.lecturer_id = lecturer.lecturer_id;
Picked
SQL-basics
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SQL Trigger | Student Database
SQL | Views
CTE in SQL
Difference between DDL and DML in DBMS
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | GROUP BY
Difference between DELETE, DROP and TRUNCATE
How to Alter Multiple Columns at Once in SQL Server?
Difference between SQL and NoSQL
MySQL | Group_CONCAT() Function | [
{
"code": null,
"e": 24262,
"s": 24234,
"text": "\n27 May, 2021"
},
{
"code": null,
"e": 24521,
"s": 24262,
"text": "To retrieve data from the single table we use SELECT and PROJECTION operations but to retrieve data from multiple tables we use JOINS in SQL. There are different types of JOINS in SQL. In this article, only operations on inner joins in MSSQL are discussed. "
},
{
"code": null,
"e": 24787,
"s": 24521,
"text": "Inner Join is the method of retrieval of data from multiple tables based on a required condition and necessary conditions are that there must be common columns or matched columns between the two tables of the database and the data types of columns must be the same."
},
{
"code": null,
"e": 24878,
"s": 24787,
"text": "Let us see how to join two tables and three tables using Inner Join in MSSQL step-by-step."
},
{
"code": null,
"e": 24957,
"s": 24878,
"text": "Creating a database GeeksForGeeks by using the following SQL query as follows."
},
{
"code": null,
"e": 24989,
"s": 24957,
"text": " CREATE DATABASE GeeksForGeeks;"
},
{
"code": null,
"e": 25058,
"s": 24989,
"text": "Using the database student using the following SQL query as follows."
},
{
"code": null,
"e": 25077,
"s": 25058,
"text": "USE GeeksForGeeks;"
},
{
"code": null,
"e": 25156,
"s": 25077,
"text": "Creating three tables student, course, and lecturer with SQL query as follows:"
},
{
"code": null,
"e": 25295,
"s": 25156,
"text": "CREATE TABLE student\n( stu_id varchar(10),\n stu_name varchar(20),\n course_id varchar(10),\n branch varchar(20),\n lecturer_id varchar(10)\n);"
},
{
"code": null,
"e": 25371,
"s": 25295,
"text": "CREATE TABLE course\n(\n course_id varchar(10),\n course_name varchar(20)\n);"
},
{
"code": null,
"e": 25453,
"s": 25371,
"text": "CREATE TABLE lecturer\n(\n lecturer_id varchar(10),\n lecturer_name varchar(20)\n);"
},
{
"code": null,
"e": 25569,
"s": 25453,
"text": "To view the description of the three tables in the database GeeksForGeeks using the following SQL query as follows."
},
{
"code": null,
"e": 25644,
"s": 25569,
"text": "EXEC sp_columns student;\nEXEC sp_columns course;\nEXEC sp_columns lecturer;"
},
{
"code": null,
"e": 25720,
"s": 25644,
"text": "Inserting rows into student table using the following SQL query as follows:"
},
{
"code": null,
"e": 26111,
"s": 25720,
"text": "INSERT INTO student VALUES\n('1901401','DEVA','CS1003','C.S', 'P4002'),\n('1901402','HARSH','CS1001','C.S', 'P4001'),\n('1901403','ABHISHEK','CS1001','C.S', 'P4001'),\n('1901404','GARVIT','CS1002','C.S', 'P4003'),\n('1901405','SAMPATH','CS1003','C.S', 'P4002'),\n('1901406','SATWIK','CS1002','C.S', 'P4003'),\n('1901407','GUPTA','CS1001','C.S', 'P4001'),\n('1901408','DAS','CS1003','C.S', 'P4002');"
},
{
"code": null,
"e": 26190,
"s": 26111,
"text": "Inserting rows into the course table using the following SQL query as follows:"
},
{
"code": null,
"e": 26312,
"s": 26190,
"text": "INSERT INTO course VALUES\n('CS1001', 'DBMS'),\n('CS1002', 'O.S'),\n('CS1003', 'C.N'),\n('CS1004', 'M.L'),\n('CS1005', 'A.I');"
},
{
"code": null,
"e": 26389,
"s": 26312,
"text": "Inserting rows into lecturer table using the following SQL query as follows:"
},
{
"code": null,
"e": 26544,
"s": 26389,
"text": "INSERT INTO lecturer VALUES\n('P4001', 'RAMESH'),\n('P4002', 'RAVINDER'),\n('P4003', 'RAHUL SHARMA'),\n('P4004', 'PRADEEP KUMAR'),\n('P4005', 'SRINIVASA RAO');"
},
{
"code": null,
"e": 26636,
"s": 26544,
"text": " Viewing the three tables after inserting rows by using the following SQL query as follows."
},
{
"code": null,
"e": 26702,
"s": 26636,
"text": "SELECT* FROM student;\nSELECT* FROM course;\nSELECT* FROM lecturer;"
},
{
"code": null,
"e": 26733,
"s": 26702,
"text": "The syntax for multiple joins:"
},
{
"code": null,
"e": 26909,
"s": 26733,
"text": "SELECT column_name1,column_name2,..\nFROM table_name1\nINNER JOIN \ntable_name2\nON condition_1\nINNER JOIN \ntable_name3\nON condition_2\nINNER JOIN \ntable_name4\nON condition_3\n.\n.\n."
},
{
"code": null,
"e": 27081,
"s": 26909,
"text": "Note: While selecting only particular columns use table_name. column_name when there are the same column names in the two tables otherwise you will get an ambiguous error."
},
{
"code": null,
"e": 27126,
"s": 27081,
"text": "Inner Join on two tables student and course:"
},
{
"code": null,
"e": 27215,
"s": 27126,
"text": "SELECT *\nFROM student \nINNER JOIN \ncourse \nON \nstudent.course_id = course.course_id;"
},
{
"code": null,
"e": 27286,
"s": 27215,
"text": "All the columns of 2 tables appear that satisfy the equality condition"
},
{
"code": null,
"e": 27344,
"s": 27286,
"text": "Inner Join on three tables student, course, and lecturer:"
},
{
"code": null,
"e": 27505,
"s": 27344,
"text": "SELECT *\nFROM student \nINNER JOIN \ncourse \nON \nstudent.course_id = course.course_id\nINNER JOIN \nlecturer \nON \nstudent.lecturer_id = lecturer.lecturer_id;"
},
{
"code": null,
"e": 27576,
"s": 27505,
"text": "All the columns of 3 tables appear that satisfy the equality condition"
},
{
"code": null,
"e": 27688,
"s": 27576,
"text": "Inner join on three tables student, course, lecturer but by selecting particular columns of a particular table."
},
{
"code": null,
"e": 27924,
"s": 27688,
"text": "SELECT stu_id, stu_name,course.course_id,course.course_name,\nlecturer.lecturer_name\nFROM student \nINNER JOIN \ncourse \nON \nstudent.course_id = course.course_id\nINNER JOIN \nlecturer \nON \nstudent.lecturer_id = lecturer.lecturer_id;"
},
{
"code": null,
"e": 27931,
"s": 27924,
"text": "Picked"
},
{
"code": null,
"e": 27942,
"s": 27931,
"text": "SQL-basics"
},
{
"code": null,
"e": 27946,
"s": 27942,
"text": "SQL"
},
{
"code": null,
"e": 27950,
"s": 27946,
"text": "SQL"
},
{
"code": null,
"e": 28048,
"s": 27950,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28057,
"s": 28048,
"text": "Comments"
},
{
"code": null,
"e": 28070,
"s": 28057,
"text": "Old Comments"
},
{
"code": null,
"e": 28101,
"s": 28070,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 28113,
"s": 28101,
"text": "SQL | Views"
},
{
"code": null,
"e": 28124,
"s": 28113,
"text": "CTE in SQL"
},
{
"code": null,
"e": 28163,
"s": 28124,
"text": "Difference between DDL and DML in DBMS"
},
{
"code": null,
"e": 28229,
"s": 28163,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 28244,
"s": 28229,
"text": "SQL | GROUP BY"
},
{
"code": null,
"e": 28289,
"s": 28244,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 28342,
"s": 28289,
"text": "How to Alter Multiple Columns at Once in SQL Server?"
},
{
"code": null,
"e": 28375,
"s": 28342,
"text": "Difference between SQL and NoSQL"
}
]
|
Visualizing beyond 3 Dimensions. Peeking into unseeably complex data | by Alec Morgan | Towards Data Science | Vision is arguably one of our greatest strengths as humans. Even the most tremendously complex ideas tend to become easy (or at least, much easier) to understand as soon as you find a way to visualize them — our occipital lobes have done us well. That’s why when you’re working with datasets that have more than 3 dimensions, it can be a challenge just to understand what’s going on inside of them, much less to present your findings to others. That’s the challenge we’ll be tackling today.
To this end we’ll be using a King County house sales data set which contains information on over 21,000 real house sales from 2014 and 2015. This dataset also happens to contain 21 pieces of info in every single record, such as price, square footage, condition of the property, and many more — in other words, this dataset is 21-dimensional. I actually had to transpose it just to get it to fit horizontally for this next shot.
df.head(10).T
Where do we even start? One of the easiest ways is to plot histograms for all metrics, or to plot all features against your choice of target (e.g. price) in scatterplots.
df.hist()
This tells us something about all of our pieces of data individually, but nothing about how they relate to each other. Enter scatterplots — yes, I just said scatterplots aren’t too much help for this either, but bear with me.
For visibility’s sake, lets engineer a price_thousands feature and take a random sample of roughly 3% of our data points. 3% is still ~600 in this case, any more than than that and the plot would get too crowded in this case.
df['price_thousands'] = df['price'] / 1000np.random.seed(25565)df = df.sample(n=round(len(df)/33))plt.figure(figsize=(9, 9))sns.scatterplot(x='price_thousands', y='sqft_living', palette='Blues', data=df);
The result looks like this:
However, just by adding a few new parameters, we can make it look like this...
sns.scatterplot(x='price_thousands', y='sqft_living', hue='grade', size='sqft_living', palette='Blues', data=df);
By essentially adding hue as a dimension, we’re able to essentially able to represent 3 dimensions in 2 — not a bad deal! Notice that we’ve also represented sqft_living twice here: once as an axis, then once more as the scale of the points. If you’re thinking to yourself it’d be much better to use the scale of the dots to represent sqft_living and the y-axis to represent some other feature of the data, then in principle I agree with you wholeheartedly. In practice however, with this particular dataset such attempts get so messy that the data becomes visually intractable. At least we can increase the readability of this data by representing sqft_living twice though, so it’s not as though nothing has been gained. I would say the takeaway from this tangent is that data visualization is still more of an art than a science.
Back to the topic at hand: how to visualize beyond 3 dimensions. Maybe we can combine our new tricks of changing color gradients and point sizes with an actual 3D scatterplot? Well, yes, but actually no.
from mpl_toolkits.mplot3d import Axes3Dfig = plt.figure(figsize=(9, 9))ax = fig.add_subplot(111, projection='3d')x_param = 'price_thousands'y_param = 'sqft_living'z_param = 'bedrooms'x = df[x_param]y = df[y_param] * 25z = df[z_param]ax.set_xlabel(x_param)ax.set_ylabel(y_param)ax.set_zlabel(z_param)ax.scatter(x, y, z, c='b', s=50, edgecolors='w', marker='o', alpha=0.4);
The shifting hues and point sizes are a feature of Seaborn, but Seaborn does not support 3D scatter plots as far as I know. Conversely, Matplotlib may be able to plot in 3-dimensions, but it does not support those shifting hues and point sizes that are so lovely and useful. In summary, there is no solution (that I know of) which comes right out of the box ready to let us have our cake and eat t too. If this does exist though, please do share in the comments!
Lets try one more approach: surface plots.
fig = plt.figure(figsize=(9, 9))ax = fig.gca(projection='3d')ax.plot_trisurf(y, x, z, cmap=plt.cm.viridis, linewidth=0.2)ax.view_init(30, 145)plt.show();
Hmm. As it turns out, surface plots are very messy unless we sort their values. However, while sorting the values will give us a clearer picture, it won’t necessarily give us a more useful one.
x = np.sort(x)y = np.sort(y)z = np.sort(z)fig = plt.figure(figsize=(9, 9))ax = fig.gca(projection='3d')ax.plot_trisurf(y, x, z, cmap=plt.cm.viridis, linewidth=0.2)ax.view_init(35, 140)plt.show();
All these variables correlate very strongly with each other, so what we end up with is this very narrow and linear shape that’s difficult to make heads or tails of. In the end, it seems that the scatterplots provided a more effective visualization, at least for this particular dataset. Others translate somewhat better to this medium however.
iris = sns.load_dataset('iris')fig = plt.figure(figsize=(9, 9))ax = fig.gca(projection='3d')ax.plot_trisurf(iris['sepal_length'], iris['sepal_width'], iris['petal_length'], cmap=plt.cm.viridis, linewidth=0.2)ax.view_init(30, 145)plt.show();
There are some more tricks we haven’t tried yet (such as different point shapes or animating our plot to change over time), but the fact of the matter is we’re still not close to visualizing 21 dimensions simultaneously — it’s not exactly possible. But that doesn’t mean we can’t glean meaningful insights from our super-dimensional data. We probably care less about all 21 dimensions of this data and more about what all that data can actually do for us, such as allowing us to more accurately predict price. To that end, we can simply plot our error values in two dimensions.
residuals = model_1st.residfig = sm.graphics.qqplot(residuals, dist=stats.norm, line='45', fit=True)plt.xlabel('Quantiles of Standard Normal Distribution')plt.ylabel('Quantiles of Residuals')plt.title('Distribution of Residuals (Best Model)')fig.show()
Even if we can’t see all 21 dimensions simultaneously, there are plenty of ways that we can take slices of that data and glean meaningful insights from it. If you know of any more, please let me know! | [
{
"code": null,
"e": 662,
"s": 171,
"text": "Vision is arguably one of our greatest strengths as humans. Even the most tremendously complex ideas tend to become easy (or at least, much easier) to understand as soon as you find a way to visualize them — our occipital lobes have done us well. That’s why when you’re working with datasets that have more than 3 dimensions, it can be a challenge just to understand what’s going on inside of them, much less to present your findings to others. That’s the challenge we’ll be tackling today."
},
{
"code": null,
"e": 1090,
"s": 662,
"text": "To this end we’ll be using a King County house sales data set which contains information on over 21,000 real house sales from 2014 and 2015. This dataset also happens to contain 21 pieces of info in every single record, such as price, square footage, condition of the property, and many more — in other words, this dataset is 21-dimensional. I actually had to transpose it just to get it to fit horizontally for this next shot."
},
{
"code": null,
"e": 1104,
"s": 1090,
"text": "df.head(10).T"
},
{
"code": null,
"e": 1275,
"s": 1104,
"text": "Where do we even start? One of the easiest ways is to plot histograms for all metrics, or to plot all features against your choice of target (e.g. price) in scatterplots."
},
{
"code": null,
"e": 1286,
"s": 1275,
"text": "df.hist() "
},
{
"code": null,
"e": 1512,
"s": 1286,
"text": "This tells us something about all of our pieces of data individually, but nothing about how they relate to each other. Enter scatterplots — yes, I just said scatterplots aren’t too much help for this either, but bear with me."
},
{
"code": null,
"e": 1738,
"s": 1512,
"text": "For visibility’s sake, lets engineer a price_thousands feature and take a random sample of roughly 3% of our data points. 3% is still ~600 in this case, any more than than that and the plot would get too crowded in this case."
},
{
"code": null,
"e": 1991,
"s": 1738,
"text": "df['price_thousands'] = df['price'] / 1000np.random.seed(25565)df = df.sample(n=round(len(df)/33))plt.figure(figsize=(9, 9))sns.scatterplot(x='price_thousands', y='sqft_living', palette='Blues', data=df);"
},
{
"code": null,
"e": 2019,
"s": 1991,
"text": "The result looks like this:"
},
{
"code": null,
"e": 2098,
"s": 2019,
"text": "However, just by adding a few new parameters, we can make it look like this..."
},
{
"code": null,
"e": 2292,
"s": 2098,
"text": "sns.scatterplot(x='price_thousands', y='sqft_living', hue='grade', size='sqft_living', palette='Blues', data=df);"
},
{
"code": null,
"e": 3123,
"s": 2292,
"text": "By essentially adding hue as a dimension, we’re able to essentially able to represent 3 dimensions in 2 — not a bad deal! Notice that we’ve also represented sqft_living twice here: once as an axis, then once more as the scale of the points. If you’re thinking to yourself it’d be much better to use the scale of the dots to represent sqft_living and the y-axis to represent some other feature of the data, then in principle I agree with you wholeheartedly. In practice however, with this particular dataset such attempts get so messy that the data becomes visually intractable. At least we can increase the readability of this data by representing sqft_living twice though, so it’s not as though nothing has been gained. I would say the takeaway from this tangent is that data visualization is still more of an art than a science."
},
{
"code": null,
"e": 3327,
"s": 3123,
"text": "Back to the topic at hand: how to visualize beyond 3 dimensions. Maybe we can combine our new tricks of changing color gradients and point sizes with an actual 3D scatterplot? Well, yes, but actually no."
},
{
"code": null,
"e": 3742,
"s": 3327,
"text": "from mpl_toolkits.mplot3d import Axes3Dfig = plt.figure(figsize=(9, 9))ax = fig.add_subplot(111, projection='3d')x_param = 'price_thousands'y_param = 'sqft_living'z_param = 'bedrooms'x = df[x_param]y = df[y_param] * 25z = df[z_param]ax.set_xlabel(x_param)ax.set_ylabel(y_param)ax.set_zlabel(z_param)ax.scatter(x, y, z, c='b', s=50, edgecolors='w', marker='o', alpha=0.4);"
},
{
"code": null,
"e": 4205,
"s": 3742,
"text": "The shifting hues and point sizes are a feature of Seaborn, but Seaborn does not support 3D scatter plots as far as I know. Conversely, Matplotlib may be able to plot in 3-dimensions, but it does not support those shifting hues and point sizes that are so lovely and useful. In summary, there is no solution (that I know of) which comes right out of the box ready to let us have our cake and eat t too. If this does exist though, please do share in the comments!"
},
{
"code": null,
"e": 4248,
"s": 4205,
"text": "Lets try one more approach: surface plots."
},
{
"code": null,
"e": 4402,
"s": 4248,
"text": "fig = plt.figure(figsize=(9, 9))ax = fig.gca(projection='3d')ax.plot_trisurf(y, x, z, cmap=plt.cm.viridis, linewidth=0.2)ax.view_init(30, 145)plt.show();"
},
{
"code": null,
"e": 4596,
"s": 4402,
"text": "Hmm. As it turns out, surface plots are very messy unless we sort their values. However, while sorting the values will give us a clearer picture, it won’t necessarily give us a more useful one."
},
{
"code": null,
"e": 4792,
"s": 4596,
"text": "x = np.sort(x)y = np.sort(y)z = np.sort(z)fig = plt.figure(figsize=(9, 9))ax = fig.gca(projection='3d')ax.plot_trisurf(y, x, z, cmap=plt.cm.viridis, linewidth=0.2)ax.view_init(35, 140)plt.show();"
},
{
"code": null,
"e": 5136,
"s": 4792,
"text": "All these variables correlate very strongly with each other, so what we end up with is this very narrow and linear shape that’s difficult to make heads or tails of. In the end, it seems that the scatterplots provided a more effective visualization, at least for this particular dataset. Others translate somewhat better to this medium however."
},
{
"code": null,
"e": 5442,
"s": 5136,
"text": "iris = sns.load_dataset('iris')fig = plt.figure(figsize=(9, 9))ax = fig.gca(projection='3d')ax.plot_trisurf(iris['sepal_length'], iris['sepal_width'], iris['petal_length'], cmap=plt.cm.viridis, linewidth=0.2)ax.view_init(30, 145)plt.show();"
},
{
"code": null,
"e": 6020,
"s": 5442,
"text": "There are some more tricks we haven’t tried yet (such as different point shapes or animating our plot to change over time), but the fact of the matter is we’re still not close to visualizing 21 dimensions simultaneously — it’s not exactly possible. But that doesn’t mean we can’t glean meaningful insights from our super-dimensional data. We probably care less about all 21 dimensions of this data and more about what all that data can actually do for us, such as allowing us to more accurately predict price. To that end, we can simply plot our error values in two dimensions."
},
{
"code": null,
"e": 6273,
"s": 6020,
"text": "residuals = model_1st.residfig = sm.graphics.qqplot(residuals, dist=stats.norm, line='45', fit=True)plt.xlabel('Quantiles of Standard Normal Distribution')plt.ylabel('Quantiles of Residuals')plt.title('Distribution of Residuals (Best Model)')fig.show()"
}
]
|
Inbuilt Data Structures in Python - GeeksforGeeks | 01 Feb, 2022
Python has four basic inbuilt data structures namely Lists, Dictionary, Tuple and Set. These almost cover 80% of the our real world data structures. This article will cover the above mentioned topics.
Above mentioned topics are divided into four sections below.
Lists: Lists in Python are one of the most versatile collection object types available. The other two types are dictionaries and tuples, but they are really more like variations of lists.
Python lists do the work of most of the collection data structures found in other languages and since they are built-in, you don’t have to worry about manually creating them.
Lists can be used for any type of object, from numbers and strings to more lists.
They are accessed just like strings (e.g. slicing and concatenation) so they are simple to use and they’re variable length, i.e. they grow and shrink automatically as they’re used.
In reality, Python lists are C arrays inside the Python interpreter and act just like an array of pointers.
Dictionary: In python, dictionary is similar to hash or maps in other languages. It consists of key value pairs. The value can be accessed by unique key in the dictionary.
Keys are unique & immutable objects.
Syntax:
dictionary = {"key name": value}
Tuple : Python tuples work exactly like Python lists except they are immutable, i.e. they can’t be changed in place. They are normally written inside parentheses to distinguish them from lists (which use square brackets), but as you’ll see, parentheses aren’t always necessary. Since tuples are immutable, their length is fixed. To grow or shrink a tuple, a new tuple must be created.
Here’s a list of commonly used tuples:
() An empty tuple
t1 = (0, ) A one-item tuple (not an expression)
t2 = (0, 1, 2, 3) A four-item tuple
t3 = 0, 1, 2, 3 Another four-item tuple (same as prior line, just minus the parenthesis)
t3 = (‘abc’, (‘def’, ‘ghi’)) Nested tuples
t1[n], t3[n][j] Index
t1[i:j], Slice
len(tl) Length
Python3
# Python program to illustrate# tupletup = (1, "a", "string", 1+2)print (tup)print (tup[1])
Output:
(1, 'a', 'string', 3)
a
Detailed article on Tuples in Python
Sets: Unordered collection of unique objects.
Set operations such as union (|) , intersection(&), difference(-) can be applied on a set.
Frozen Sets are immutable i.e once created further data can’t be added to them
{} are used to represent a set.Objects placed inside these brackets would be treated as a set.
Python3
# Python program to demonstrate working of# Set in Python # Creating two setsset1 = set()set2 = set() # Adding elements to set1for i in range(1, 6): set1.add(i) # Adding elements to set2for i in range(3, 8): set2.add(i) print("Set1 = ", set1)print("Set2 = ", set2)print("\n")
Output:
('Set1 = ', set([1, 2, 3, 4, 5]))
('Set2 = ', set([3, 4, 5, 6, 7]))
To read more about sets in python read our article about set by clicking here.
annaop93
amartyaghoshgfg
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24316,
"s": 24288,
"text": "\n01 Feb, 2022"
},
{
"code": null,
"e": 24518,
"s": 24316,
"text": "Python has four basic inbuilt data structures namely Lists, Dictionary, Tuple and Set. These almost cover 80% of the our real world data structures. This article will cover the above mentioned topics. "
},
{
"code": null,
"e": 24580,
"s": 24518,
"text": "Above mentioned topics are divided into four sections below. "
},
{
"code": null,
"e": 24768,
"s": 24580,
"text": "Lists: Lists in Python are one of the most versatile collection object types available. The other two types are dictionaries and tuples, but they are really more like variations of lists."
},
{
"code": null,
"e": 24943,
"s": 24768,
"text": "Python lists do the work of most of the collection data structures found in other languages and since they are built-in, you don’t have to worry about manually creating them."
},
{
"code": null,
"e": 25025,
"s": 24943,
"text": "Lists can be used for any type of object, from numbers and strings to more lists."
},
{
"code": null,
"e": 25206,
"s": 25025,
"text": "They are accessed just like strings (e.g. slicing and concatenation) so they are simple to use and they’re variable length, i.e. they grow and shrink automatically as they’re used."
},
{
"code": null,
"e": 25314,
"s": 25206,
"text": "In reality, Python lists are C arrays inside the Python interpreter and act just like an array of pointers."
},
{
"code": null,
"e": 25487,
"s": 25314,
"text": "Dictionary: In python, dictionary is similar to hash or maps in other languages. It consists of key value pairs. The value can be accessed by unique key in the dictionary. "
},
{
"code": null,
"e": 25524,
"s": 25487,
"text": "Keys are unique & immutable objects."
},
{
"code": null,
"e": 25533,
"s": 25524,
"text": "Syntax: "
},
{
"code": null,
"e": 25566,
"s": 25533,
"text": "dictionary = {\"key name\": value}"
},
{
"code": null,
"e": 25952,
"s": 25566,
"text": "Tuple : Python tuples work exactly like Python lists except they are immutable, i.e. they can’t be changed in place. They are normally written inside parentheses to distinguish them from lists (which use square brackets), but as you’ll see, parentheses aren’t always necessary. Since tuples are immutable, their length is fixed. To grow or shrink a tuple, a new tuple must be created. "
},
{
"code": null,
"e": 25991,
"s": 25952,
"text": "Here’s a list of commonly used tuples:"
},
{
"code": null,
"e": 26277,
"s": 25991,
"text": "() An empty tuple\nt1 = (0, ) A one-item tuple (not an expression)\nt2 = (0, 1, 2, 3) A four-item tuple\nt3 = 0, 1, 2, 3 Another four-item tuple (same as prior line, just minus the parenthesis)\nt3 = (‘abc’, (‘def’, ‘ghi’)) Nested tuples\nt1[n], t3[n][j] Index\nt1[i:j], Slice\nlen(tl) Length"
},
{
"code": null,
"e": 26285,
"s": 26277,
"text": "Python3"
},
{
"code": "# Python program to illustrate# tupletup = (1, \"a\", \"string\", 1+2)print (tup)print (tup[1])",
"e": 26377,
"s": 26285,
"text": null
},
{
"code": null,
"e": 26386,
"s": 26377,
"text": "Output: "
},
{
"code": null,
"e": 26410,
"s": 26386,
"text": "(1, 'a', 'string', 3)\na"
},
{
"code": null,
"e": 26447,
"s": 26410,
"text": "Detailed article on Tuples in Python"
},
{
"code": null,
"e": 26494,
"s": 26447,
"text": "Sets: Unordered collection of unique objects. "
},
{
"code": null,
"e": 26585,
"s": 26494,
"text": "Set operations such as union (|) , intersection(&), difference(-) can be applied on a set."
},
{
"code": null,
"e": 26664,
"s": 26585,
"text": "Frozen Sets are immutable i.e once created further data can’t be added to them"
},
{
"code": null,
"e": 26759,
"s": 26664,
"text": "{} are used to represent a set.Objects placed inside these brackets would be treated as a set."
},
{
"code": null,
"e": 26767,
"s": 26759,
"text": "Python3"
},
{
"code": "# Python program to demonstrate working of# Set in Python # Creating two setsset1 = set()set2 = set() # Adding elements to set1for i in range(1, 6): set1.add(i) # Adding elements to set2for i in range(3, 8): set2.add(i) print(\"Set1 = \", set1)print(\"Set2 = \", set2)print(\"\\n\")",
"e": 27049,
"s": 26767,
"text": null
},
{
"code": null,
"e": 27057,
"s": 27049,
"text": "Output:"
},
{
"code": null,
"e": 27125,
"s": 27057,
"text": "('Set1 = ', set([1, 2, 3, 4, 5]))\n('Set2 = ', set([3, 4, 5, 6, 7]))"
},
{
"code": null,
"e": 27204,
"s": 27125,
"text": "To read more about sets in python read our article about set by clicking here."
},
{
"code": null,
"e": 27213,
"s": 27204,
"text": "annaop93"
},
{
"code": null,
"e": 27229,
"s": 27213,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 27236,
"s": 27229,
"text": "Python"
},
{
"code": null,
"e": 27334,
"s": 27236,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27366,
"s": 27334,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27422,
"s": 27366,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27464,
"s": 27422,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27506,
"s": 27464,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27528,
"s": 27506,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27567,
"s": 27528,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27598,
"s": 27567,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27653,
"s": 27598,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 27682,
"s": 27653,
"text": "Create a directory in Python"
}
]
|
Embedding Graphs with Deep Learning | by Connor Shorten | Towards Data Science | Sparse representations are the natural killer of classifiers. Current graph data structures such as adjacency matrices and lists are plagued with this sparsity. This article will discuss techniques such as Matrix decomposition, DeepWalk, and Node2Vec which convert sparse graph data into low-dimensional continuous vector spaces.
Historically, matrix decomposition has been a popular way of reducing the dimensionality of graph data. This includes techniques such as SVD (Singular Value Decomposition) and MDS (Multi-dimensional Scaling). The problem with these techniques is that they essentially have the running time of Matrix Multiplication (typically n3, although n^(2.37) and n^(2.77) are achievable with clever tricks such as the Coopersmith-Winograd or Strassen algorithms).
An n3 running time isn’t too terrible for many problems. However, this is catastrophic in the case of graph representations with thousands or even millions of users. Additionally, this must be recomputed as new users and connections are added to the graph. Social network graphs such as twitter retweets or medium followers are dynamic and constantly evolving.
Instead of using Matrix Decompositions to represent graphs, we can use Deep Learning!
One of the first papers to elegantly formulate the use of Deep Learning for representation graphs was DeepWalk (linked below).
arxiv.org
DeepWalk is inspired by similarities between graph representations and text tokens. Naively, text tokens are encoded as one-hot vectors. For example, you would take a very long vector the size of the vocabulary, and reserve an index for each word. The word “tiger” would be encoded as something like:
One-hot encoding of text[ 0 0 .. 0 0 1 0 0 .. 0 0 ] = "tiger"
Naturally, these sparse representations of text wrecked havoc for classification models on downstream tasks such as sentiment prediction. The savior of this was the introduction of the Skip-gram model (pictured below):
The Skip-gram model works by sliding context windows across sentences and building a Deep Neural Network that takes as input the word token and maps it to a prediction of other words appearing in the context window. The intermediate representation (denoted as “projection” in the diagram above) is then the low-dimensional representation of the text tokens.
DeepWalk took this idea and extended it to graph data. However, text data naturally contains some kind of structure that is well fitted to the context window. The authors of DeepWalk simulate this structure by constructing neighborhoods through random walks, hence the name “DeepWalk”.
The diagram above is used to depict a Random Walk. Starting from node “Connor”, we either travel to Erika, Daniel, Ben, or James with the probabilities a, b, c, and d. In DeepWalk, a = b = c = d, but in Node2Vec these probabilities are parameterized throughout the walk.
Random walking along graphs results in neighborhoods such as:
Examples of Vertex Neighborhoods(Connor, James, Jon, Bob, Joe)(Connor, James, Jon, James, Connor)(Connor, Erika, Connor, Daniel, Connor)
Context windows are then slid across these neighborhoods and a skip-gram model is trained.
Two important ideas for training skip-gram models are Hierarchical Softmax and Negative Sampling. The image highlights the idea of Hierarchical Softmax.
Imagine a facebook network where you have millions of users to predict in the vertex neighborhoods. This would result in a softmax layer with millions of hidden units. This disaster can be avoided by constructing the vertex space in a binary tree and predicting a path along the tree to traverse. For example, if there are 8 users in the network, you only need 3 values to traverse from the root to any individual node.
The next idea (which is a crucial idea in Word2Vec) is negative sampling. Negative sampling basically throws out the idea of directly predicting the words in the context window, and rather treating the context prediction task as a binary classification problem. Once you have a context pair, you randomly sample negative pairs and then have the model label wether the word appears in the context or not.
Another interesting paper building on DeepWalk is Node2Vec (linked below):
arxiv.org
Node2Vec takes apart the idea of using random walks to construct vertex neighborhoods. This begins by looking at two extreme ways of traversing a graph, Bread-First and Depth-First Search:
They find that if you traverse nodes in a Depth-First Search, the resulting embedding will capture homophily. Homophily refers to the notion that nodes which have a small shortest-path distance should be embedded near each other in the new representation. They also find that if you traverse nodes in a Breadth-First Search, the resulting embedding will capture structural equivalence. Structural equivalence is easily explained in the image above, even though u and s6 do not share any neighbors, they both serve as the hub of their respective communities.
The authors of Node2Vec thus propose to parameterize the random walk so that it can construct more semantic vertex neighborhoods:
In Conclusion, this article has introduced DeepWalk and Node2Vec and showed how they use Deep Learning to embed graphs into low-dimensional representations. The skip-gram model approach has the advantage of being adaptable to changes in the network, compared to Matrix Decomposition methods which must be recomputed. Thanks for reading, please check out the video below if you would like a recap of this article! | [
{
"code": null,
"e": 502,
"s": 172,
"text": "Sparse representations are the natural killer of classifiers. Current graph data structures such as adjacency matrices and lists are plagued with this sparsity. This article will discuss techniques such as Matrix decomposition, DeepWalk, and Node2Vec which convert sparse graph data into low-dimensional continuous vector spaces."
},
{
"code": null,
"e": 955,
"s": 502,
"text": "Historically, matrix decomposition has been a popular way of reducing the dimensionality of graph data. This includes techniques such as SVD (Singular Value Decomposition) and MDS (Multi-dimensional Scaling). The problem with these techniques is that they essentially have the running time of Matrix Multiplication (typically n3, although n^(2.37) and n^(2.77) are achievable with clever tricks such as the Coopersmith-Winograd or Strassen algorithms)."
},
{
"code": null,
"e": 1316,
"s": 955,
"text": "An n3 running time isn’t too terrible for many problems. However, this is catastrophic in the case of graph representations with thousands or even millions of users. Additionally, this must be recomputed as new users and connections are added to the graph. Social network graphs such as twitter retweets or medium followers are dynamic and constantly evolving."
},
{
"code": null,
"e": 1402,
"s": 1316,
"text": "Instead of using Matrix Decompositions to represent graphs, we can use Deep Learning!"
},
{
"code": null,
"e": 1529,
"s": 1402,
"text": "One of the first papers to elegantly formulate the use of Deep Learning for representation graphs was DeepWalk (linked below)."
},
{
"code": null,
"e": 1539,
"s": 1529,
"text": "arxiv.org"
},
{
"code": null,
"e": 1840,
"s": 1539,
"text": "DeepWalk is inspired by similarities between graph representations and text tokens. Naively, text tokens are encoded as one-hot vectors. For example, you would take a very long vector the size of the vocabulary, and reserve an index for each word. The word “tiger” would be encoded as something like:"
},
{
"code": null,
"e": 1902,
"s": 1840,
"text": "One-hot encoding of text[ 0 0 .. 0 0 1 0 0 .. 0 0 ] = \"tiger\""
},
{
"code": null,
"e": 2121,
"s": 1902,
"text": "Naturally, these sparse representations of text wrecked havoc for classification models on downstream tasks such as sentiment prediction. The savior of this was the introduction of the Skip-gram model (pictured below):"
},
{
"code": null,
"e": 2479,
"s": 2121,
"text": "The Skip-gram model works by sliding context windows across sentences and building a Deep Neural Network that takes as input the word token and maps it to a prediction of other words appearing in the context window. The intermediate representation (denoted as “projection” in the diagram above) is then the low-dimensional representation of the text tokens."
},
{
"code": null,
"e": 2765,
"s": 2479,
"text": "DeepWalk took this idea and extended it to graph data. However, text data naturally contains some kind of structure that is well fitted to the context window. The authors of DeepWalk simulate this structure by constructing neighborhoods through random walks, hence the name “DeepWalk”."
},
{
"code": null,
"e": 3036,
"s": 2765,
"text": "The diagram above is used to depict a Random Walk. Starting from node “Connor”, we either travel to Erika, Daniel, Ben, or James with the probabilities a, b, c, and d. In DeepWalk, a = b = c = d, but in Node2Vec these probabilities are parameterized throughout the walk."
},
{
"code": null,
"e": 3098,
"s": 3036,
"text": "Random walking along graphs results in neighborhoods such as:"
},
{
"code": null,
"e": 3235,
"s": 3098,
"text": "Examples of Vertex Neighborhoods(Connor, James, Jon, Bob, Joe)(Connor, James, Jon, James, Connor)(Connor, Erika, Connor, Daniel, Connor)"
},
{
"code": null,
"e": 3326,
"s": 3235,
"text": "Context windows are then slid across these neighborhoods and a skip-gram model is trained."
},
{
"code": null,
"e": 3479,
"s": 3326,
"text": "Two important ideas for training skip-gram models are Hierarchical Softmax and Negative Sampling. The image highlights the idea of Hierarchical Softmax."
},
{
"code": null,
"e": 3899,
"s": 3479,
"text": "Imagine a facebook network where you have millions of users to predict in the vertex neighborhoods. This would result in a softmax layer with millions of hidden units. This disaster can be avoided by constructing the vertex space in a binary tree and predicting a path along the tree to traverse. For example, if there are 8 users in the network, you only need 3 values to traverse from the root to any individual node."
},
{
"code": null,
"e": 4303,
"s": 3899,
"text": "The next idea (which is a crucial idea in Word2Vec) is negative sampling. Negative sampling basically throws out the idea of directly predicting the words in the context window, and rather treating the context prediction task as a binary classification problem. Once you have a context pair, you randomly sample negative pairs and then have the model label wether the word appears in the context or not."
},
{
"code": null,
"e": 4378,
"s": 4303,
"text": "Another interesting paper building on DeepWalk is Node2Vec (linked below):"
},
{
"code": null,
"e": 4388,
"s": 4378,
"text": "arxiv.org"
},
{
"code": null,
"e": 4577,
"s": 4388,
"text": "Node2Vec takes apart the idea of using random walks to construct vertex neighborhoods. This begins by looking at two extreme ways of traversing a graph, Bread-First and Depth-First Search:"
},
{
"code": null,
"e": 5135,
"s": 4577,
"text": "They find that if you traverse nodes in a Depth-First Search, the resulting embedding will capture homophily. Homophily refers to the notion that nodes which have a small shortest-path distance should be embedded near each other in the new representation. They also find that if you traverse nodes in a Breadth-First Search, the resulting embedding will capture structural equivalence. Structural equivalence is easily explained in the image above, even though u and s6 do not share any neighbors, they both serve as the hub of their respective communities."
},
{
"code": null,
"e": 5265,
"s": 5135,
"text": "The authors of Node2Vec thus propose to parameterize the random walk so that it can construct more semantic vertex neighborhoods:"
}
]
|
Converting Tkinter program to exe file | Let us suppose that we want to create a standalone app (executable application) using tkinter. We can convert any tkinter application to an exe compatible file format using the PyInstaller package in Python.
To work with pyinstaller, first install the package in the environment by using the following command,
pip install pyinstaller
Once installed, we can follow the steps to convert a Python Script File (contains a Tkinter application file) to an Executable file.
Install pyinstaller using pip install pyinstaller in Windows operating system. Now, type pyinstaller --onefile -w filename and press Enter.
Now, check the location of the file (script file) and you will find a dist folder which contains the executable file in it.
When we run the file, it will display the window of the tkinter application.
main.py
In this example, we have created an application that will greet the user with their name by displaying the message on the screen.
#Import the required Libraries
from tkinter import *
from tkinter import ttk
#Create an instance of tkinter frame
win = Tk()
#Set the geometry of tkinter frame
win.geometry("750x250")
#Define a function to show a message
def myclick():
message= "Hello "+ entry.get()
label= Label(frame, text= message, font= ('Times New Roman', 14, 'italic'))
entry.delete(0, 'end')
label.pack(pady=30)
#Creates a Frame
frame = LabelFrame(win, width= 400, height= 180, bd=5)
frame.pack()
#Stop the frame from propagating the widget to be shrink or fit
frame.pack_propagate(False)
#Create an Entry widget in the Frame
entry = ttk.Entry(frame, width= 40)
entry.insert(INSERT, "Enter Your Name")
entry.pack()
#Create a Button
ttk.Button(win, text= "Click", command= myclick).pack(pady=20)
win.mainloop()
Now, run the above command to convert the given code into an executable file. It will affect the directory (dist folder) where all executable file will be placed automatically.
When we run the exe file, it will display a window that contains an entry widget. If we click the "Click" button, it will display a greeting message on the screen. | [
{
"code": null,
"e": 1270,
"s": 1062,
"text": "Let us suppose that we want to create a standalone app (executable application) using tkinter. We can convert any tkinter application to an exe compatible file format using the PyInstaller package in Python."
},
{
"code": null,
"e": 1373,
"s": 1270,
"text": "To work with pyinstaller, first install the package in the environment by using the following command,"
},
{
"code": null,
"e": 1397,
"s": 1373,
"text": "pip install pyinstaller"
},
{
"code": null,
"e": 1530,
"s": 1397,
"text": "Once installed, we can follow the steps to convert a Python Script File (contains a Tkinter application file) to an Executable file."
},
{
"code": null,
"e": 1670,
"s": 1530,
"text": "Install pyinstaller using pip install pyinstaller in Windows operating system. Now, type pyinstaller --onefile -w filename and press Enter."
},
{
"code": null,
"e": 1794,
"s": 1670,
"text": "Now, check the location of the file (script file) and you will find a dist folder which contains the executable file in it."
},
{
"code": null,
"e": 1871,
"s": 1794,
"text": "When we run the file, it will display the window of the tkinter application."
},
{
"code": null,
"e": 1879,
"s": 1871,
"text": "main.py"
},
{
"code": null,
"e": 2009,
"s": 1879,
"text": "In this example, we have created an application that will greet the user with their name by displaying the message on the screen."
},
{
"code": null,
"e": 2808,
"s": 2009,
"text": "#Import the required Libraries\nfrom tkinter import *\nfrom tkinter import ttk\n#Create an instance of tkinter frame\nwin = Tk()\n#Set the geometry of tkinter frame\nwin.geometry(\"750x250\")\n\n#Define a function to show a message\ndef myclick():\n message= \"Hello \"+ entry.get()\n label= Label(frame, text= message, font= ('Times New Roman', 14, 'italic'))\n entry.delete(0, 'end')\n label.pack(pady=30)\n\n#Creates a Frame\nframe = LabelFrame(win, width= 400, height= 180, bd=5)\nframe.pack()\n#Stop the frame from propagating the widget to be shrink or fit\nframe.pack_propagate(False)\n\n#Create an Entry widget in the Frame\nentry = ttk.Entry(frame, width= 40)\nentry.insert(INSERT, \"Enter Your Name\")\nentry.pack()\n#Create a Button\nttk.Button(win, text= \"Click\", command= myclick).pack(pady=20)\nwin.mainloop()"
},
{
"code": null,
"e": 2985,
"s": 2808,
"text": "Now, run the above command to convert the given code into an executable file. It will affect the directory (dist folder) where all executable file will be placed automatically."
},
{
"code": null,
"e": 3149,
"s": 2985,
"text": "When we run the exe file, it will display a window that contains an entry widget. If we click the \"Click\" button, it will display a greeting message on the screen."
}
]
|
Compiler Design | Detection of a Loop in Three Address Code - GeeksforGeeks | 10 Nov, 2021
Prerequisite – Three address code in CompilerLoop optimization is the phase after the Intermediate Code Generation. The main intention of this phase is to reduce the number of lines in a program. In any program majority of the time is spent by any program is actually inside the loop for an iterative program. In the case of the recursive program a block will be there and the majority of the time will present inside the block.
Loop Optimization –
To apply loop optimization we must first detect loops.For detecting loops we use Control Flow Analysis(CFA) using Program Flow Graph(PFG).To find program flow graph we need to find Basic Block
To apply loop optimization we must first detect loops.
For detecting loops we use Control Flow Analysis(CFA) using Program Flow Graph(PFG).
To find program flow graph we need to find Basic Block
Basic Block – A basic block is a sequence of three address statements where control enters at the beginning and leaves only at the end without any jumps or halts.
Finding the Basic Block –In order to find the basic blocks, we need to find the leaders in the program. Then a basic block will start from one leader to the next leader but not include the next leader. This means if you find out that line no 1 is a leader and line no 15 is the next leader, then the line from 1 to 14 is a basic block, but not including line no 15.
Identifying leader in a Basic Block –
First statement is always a leaderStatement that is target of conditional or un-conditional statement is a leaderStatement that follows immediately a conditional or un-conditional statement is a leader
First statement is always a leader
Statement that is target of conditional or un-conditional statement is a leader
Statement that follows immediately a conditional or un-conditional statement is a leader
fact(x){ int f = 1; for (i = 2; i <= x; i++) f = f * i; return f;}
Three Address Code of the above C code:
f = 1;i = 2;if (i > x) goto 9t1 = f * i;f = t1;t2 = i + 1;i = t2;goto(3)goto calling program
f = 1;
i = 2;
if (i > x) goto 9
t1 = f * i;
f = t1;
t2 = i + 1;
i = t2;
goto(3)
goto calling program
Leader and Basic Block –
Control Flow Analysis –
If the control enter B1 there is no other option after B1, it has to enter B2. Now, if control enters B2, then depending on the condition control will flow, if the condition is true we are going to line no 9, which means 9 is nothing but B4. But if the condition is false control goes to the next block B3. After B3, there is no condition at all we are direct goes to 3rd statement B2. Above control flow graph have a cycle between B2 and B3 which is nothing but a loop.
marcosarcticseal
Compiler Design
GATE CS
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Construction of LL(1) Parsing Table
Difference between Compiler and Interpreter
Difference between Top down parsing and Bottom up parsing
Recursive Descent Parser
Loop Optimization in Compiler Design
Layers of OSI Model
ACID Properties in DBMS
Normal Forms in DBMS
Types of Operating Systems
Page Replacement Algorithms in Operating Systems | [
{
"code": null,
"e": 25244,
"s": 25216,
"text": "\n10 Nov, 2021"
},
{
"code": null,
"e": 25673,
"s": 25244,
"text": "Prerequisite – Three address code in CompilerLoop optimization is the phase after the Intermediate Code Generation. The main intention of this phase is to reduce the number of lines in a program. In any program majority of the time is spent by any program is actually inside the loop for an iterative program. In the case of the recursive program a block will be there and the majority of the time will present inside the block."
},
{
"code": null,
"e": 25693,
"s": 25673,
"text": "Loop Optimization –"
},
{
"code": null,
"e": 25886,
"s": 25693,
"text": "To apply loop optimization we must first detect loops.For detecting loops we use Control Flow Analysis(CFA) using Program Flow Graph(PFG).To find program flow graph we need to find Basic Block"
},
{
"code": null,
"e": 25941,
"s": 25886,
"text": "To apply loop optimization we must first detect loops."
},
{
"code": null,
"e": 26026,
"s": 25941,
"text": "For detecting loops we use Control Flow Analysis(CFA) using Program Flow Graph(PFG)."
},
{
"code": null,
"e": 26081,
"s": 26026,
"text": "To find program flow graph we need to find Basic Block"
},
{
"code": null,
"e": 26244,
"s": 26081,
"text": "Basic Block – A basic block is a sequence of three address statements where control enters at the beginning and leaves only at the end without any jumps or halts."
},
{
"code": null,
"e": 26610,
"s": 26244,
"text": "Finding the Basic Block –In order to find the basic blocks, we need to find the leaders in the program. Then a basic block will start from one leader to the next leader but not include the next leader. This means if you find out that line no 1 is a leader and line no 15 is the next leader, then the line from 1 to 14 is a basic block, but not including line no 15."
},
{
"code": null,
"e": 26648,
"s": 26610,
"text": "Identifying leader in a Basic Block –"
},
{
"code": null,
"e": 26850,
"s": 26648,
"text": "First statement is always a leaderStatement that is target of conditional or un-conditional statement is a leaderStatement that follows immediately a conditional or un-conditional statement is a leader"
},
{
"code": null,
"e": 26885,
"s": 26850,
"text": "First statement is always a leader"
},
{
"code": null,
"e": 26965,
"s": 26885,
"text": "Statement that is target of conditional or un-conditional statement is a leader"
},
{
"code": null,
"e": 27054,
"s": 26965,
"text": "Statement that follows immediately a conditional or un-conditional statement is a leader"
},
{
"code": "fact(x){ int f = 1; for (i = 2; i <= x; i++) f = f * i; return f;}",
"e": 27137,
"s": 27054,
"text": null
},
{
"code": null,
"e": 27177,
"s": 27137,
"text": "Three Address Code of the above C code:"
},
{
"code": null,
"e": 27270,
"s": 27177,
"text": "f = 1;i = 2;if (i > x) goto 9t1 = f * i;f = t1;t2 = i + 1;i = t2;goto(3)goto calling program"
},
{
"code": null,
"e": 27277,
"s": 27270,
"text": "f = 1;"
},
{
"code": null,
"e": 27284,
"s": 27277,
"text": "i = 2;"
},
{
"code": null,
"e": 27302,
"s": 27284,
"text": "if (i > x) goto 9"
},
{
"code": null,
"e": 27314,
"s": 27302,
"text": "t1 = f * i;"
},
{
"code": null,
"e": 27322,
"s": 27314,
"text": "f = t1;"
},
{
"code": null,
"e": 27334,
"s": 27322,
"text": "t2 = i + 1;"
},
{
"code": null,
"e": 27342,
"s": 27334,
"text": "i = t2;"
},
{
"code": null,
"e": 27350,
"s": 27342,
"text": "goto(3)"
},
{
"code": null,
"e": 27371,
"s": 27350,
"text": "goto calling program"
},
{
"code": null,
"e": 27396,
"s": 27371,
"text": "Leader and Basic Block –"
},
{
"code": null,
"e": 27420,
"s": 27396,
"text": "Control Flow Analysis –"
},
{
"code": null,
"e": 27891,
"s": 27420,
"text": "If the control enter B1 there is no other option after B1, it has to enter B2. Now, if control enters B2, then depending on the condition control will flow, if the condition is true we are going to line no 9, which means 9 is nothing but B4. But if the condition is false control goes to the next block B3. After B3, there is no condition at all we are direct goes to 3rd statement B2. Above control flow graph have a cycle between B2 and B3 which is nothing but a loop."
},
{
"code": null,
"e": 27908,
"s": 27891,
"text": "marcosarcticseal"
},
{
"code": null,
"e": 27924,
"s": 27908,
"text": "Compiler Design"
},
{
"code": null,
"e": 27932,
"s": 27924,
"text": "GATE CS"
},
{
"code": null,
"e": 27953,
"s": 27932,
"text": "Software Engineering"
},
{
"code": null,
"e": 28051,
"s": 27953,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28060,
"s": 28051,
"text": "Comments"
},
{
"code": null,
"e": 28073,
"s": 28060,
"text": "Old Comments"
},
{
"code": null,
"e": 28109,
"s": 28073,
"text": "Construction of LL(1) Parsing Table"
},
{
"code": null,
"e": 28153,
"s": 28109,
"text": "Difference between Compiler and Interpreter"
},
{
"code": null,
"e": 28211,
"s": 28153,
"text": "Difference between Top down parsing and Bottom up parsing"
},
{
"code": null,
"e": 28236,
"s": 28211,
"text": "Recursive Descent Parser"
},
{
"code": null,
"e": 28273,
"s": 28236,
"text": "Loop Optimization in Compiler Design"
},
{
"code": null,
"e": 28293,
"s": 28273,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 28317,
"s": 28293,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 28338,
"s": 28317,
"text": "Normal Forms in DBMS"
},
{
"code": null,
"e": 28365,
"s": 28338,
"text": "Types of Operating Systems"
}
]
|
How can fetch records from specific month and year in a MySQL table? | Use YEAR() and MONTH() to display records from specific month and year respectively. Let us first create a table −
mysql> create table DemoTable
(
CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
CustomerName varchar(20),
CustomerTotalBill int,
PurchasingDate date
);
Query OK, 0 rows affected (0.83 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(CustomerName,CustomerTotalBill,PurchasingDate) values('John',2000,'2019-01-21');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(CustomerName,CustomerTotalBill,PurchasingDate) values('Chris',1000,'2019-01-31');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable(CustomerName,CustomerTotalBill,PurchasingDate) values('Robert',4500,'2018-01-01');
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable(CustomerName,CustomerTotalBill,PurchasingDate) values('Sam',5500,'2017-02-12');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(CustomerName,CustomerTotalBill,PurchasingDate) values('Carol',500,'2016-01-12');
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+------------+--------------+-------------------+----------------+
| CustomerId | CustomerName | CustomerTotalBill | PurchasingDate |
+------------+--------------+-------------------+----------------+
| 1 | John | 2000 | 2019-01-21 |
| 2 | Chris | 1000 | 2019-01-31 |
| 3 | Robert | 4500 | 2018-01-01 |
| 4 | Sam | 5500 | 2017-02-12 |
| 5 | Carol | 500 | 2016-01-12 |
+------------+--------------+-------------------+----------------+
5 rows in set (0.00 sec)
Following is the query to display records from specific month and year in MySQL −
mysql> select *from DemoTable WHERE YEAR(DATE(PurchasingDate))=2019 AND MONTH(DATE(PurchasingDate)) = 01;
This will produce the following output −
+------------+--------------+-------------------+----------------+
| CustomerId | CustomerName | CustomerTotalBill | PurchasingDate |
+------------+--------------+-------------------+----------------+
| 1 | John | 2000 | 2019-01-21 |
| 2 | Chris | 1000 | 2019-01-31 |
+------------+--------------+-------------------+----------------+
2 rows in set (0.03 sec) | [
{
"code": null,
"e": 1177,
"s": 1062,
"text": "Use YEAR() and MONTH() to display records from specific month and year respectively. Let us first create a table −"
},
{
"code": null,
"e": 1388,
"s": 1177,
"text": "mysql> create table DemoTable\n (\n CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n CustomerName varchar(20),\n CustomerTotalBill int,\n PurchasingDate date\n );\nQuery OK, 0 rows affected (0.83 sec)"
},
{
"code": null,
"e": 1444,
"s": 1388,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 2180,
"s": 1444,
"text": "mysql> insert into DemoTable(CustomerName,CustomerTotalBill,PurchasingDate) values('John',2000,'2019-01-21');\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> insert into DemoTable(CustomerName,CustomerTotalBill,PurchasingDate) values('Chris',1000,'2019-01-31');\nQuery OK, 1 row affected (0.21 sec)\n\nmysql> insert into DemoTable(CustomerName,CustomerTotalBill,PurchasingDate) values('Robert',4500,'2018-01-01');\nQuery OK, 1 row affected (0.24 sec)\n\nmysql> insert into DemoTable(CustomerName,CustomerTotalBill,PurchasingDate) values('Sam',5500,'2017-02-12');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into DemoTable(CustomerName,CustomerTotalBill,PurchasingDate) values('Carol',500,'2016-01-12');\nQuery OK, 1 row affected (0.17 sec)"
},
{
"code": null,
"e": 2240,
"s": 2180,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 2271,
"s": 2240,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 2312,
"s": 2271,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2940,
"s": 2312,
"text": "+------------+--------------+-------------------+----------------+\n| CustomerId | CustomerName | CustomerTotalBill | PurchasingDate |\n+------------+--------------+-------------------+----------------+\n| 1 | John | 2000 | 2019-01-21 |\n| 2 | Chris | 1000 | 2019-01-31 |\n| 3 | Robert | 4500 | 2018-01-01 |\n| 4 | Sam | 5500 | 2017-02-12 |\n| 5 | Carol | 500 | 2016-01-12 |\n+------------+--------------+-------------------+----------------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 3022,
"s": 2940,
"text": "Following is the query to display records from specific month and year in MySQL −"
},
{
"code": null,
"e": 3128,
"s": 3022,
"text": "mysql> select *from DemoTable WHERE YEAR(DATE(PurchasingDate))=2019 AND MONTH(DATE(PurchasingDate)) = 01;"
},
{
"code": null,
"e": 3169,
"s": 3128,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3596,
"s": 3169,
"text": "+------------+--------------+-------------------+----------------+\n| CustomerId | CustomerName | CustomerTotalBill | PurchasingDate |\n+------------+--------------+-------------------+----------------+\n| 1 | John | 2000 | 2019-01-21 |\n| 2 | Chris | 1000 | 2019-01-31 |\n+------------+--------------+-------------------+----------------+\n2 rows in set (0.03 sec)"
}
]
|
HTML | content Attribute - GeeksforGeeks | 25 Aug, 2021
The HTML content Attribute is used to given the values that are related to the http-equiv or name attribute. The content attribute can associated with the <meta> element.
Supported Tags:
<meta>
Syntax:
<meta content="text">
Attribute Values: It contains the values the text which specify the content of the meta information.Example: This Example illustrates the use of content attribute.
html
<!DOCTYPE html><html> <head> <title> content attribute in HTMLs </title> <meta name="keywords" content="content attribute in Meta Tag, Metadata" /></head> <body style="text-align:center;"> <h1> GeeksforGeeks</h1> <h2>Content Attribute In HTML</h2></body> </html>
Output:
Supported Browsers: The browser supported by HTML content Attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
hritikbhatnagar2182
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to update Node.js and NPM to next version ?
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
How to calculate the number of days between two dates in javascript? | [
{
"code": null,
"e": 23826,
"s": 23798,
"text": "\n25 Aug, 2021"
},
{
"code": null,
"e": 23998,
"s": 23826,
"text": "The HTML content Attribute is used to given the values that are related to the http-equiv or name attribute. The content attribute can associated with the <meta> element. "
},
{
"code": null,
"e": 24015,
"s": 23998,
"text": "Supported Tags: "
},
{
"code": null,
"e": 24022,
"s": 24015,
"text": "<meta>"
},
{
"code": null,
"e": 24032,
"s": 24022,
"text": "Syntax: "
},
{
"code": null,
"e": 24054,
"s": 24032,
"text": "<meta content=\"text\">"
},
{
"code": null,
"e": 24220,
"s": 24054,
"text": "Attribute Values: It contains the values the text which specify the content of the meta information.Example: This Example illustrates the use of content attribute. "
},
{
"code": null,
"e": 24225,
"s": 24220,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> content attribute in HTMLs </title> <meta name=\"keywords\" content=\"content attribute in Meta Tag, Metadata\" /></head> <body style=\"text-align:center;\"> <h1> GeeksforGeeks</h1> <h2>Content Attribute In HTML</h2></body> </html>",
"e": 24533,
"s": 24225,
"text": null
},
{
"code": null,
"e": 24543,
"s": 24533,
"text": "Output: "
},
{
"code": null,
"e": 24631,
"s": 24543,
"text": "Supported Browsers: The browser supported by HTML content Attribute are listed below: "
},
{
"code": null,
"e": 24645,
"s": 24631,
"text": "Google Chrome"
},
{
"code": null,
"e": 24663,
"s": 24645,
"text": "Internet Explorer"
},
{
"code": null,
"e": 24671,
"s": 24663,
"text": "Firefox"
},
{
"code": null,
"e": 24677,
"s": 24671,
"text": "Opera"
},
{
"code": null,
"e": 24684,
"s": 24677,
"text": "Safari"
},
{
"code": null,
"e": 24823,
"s": 24686,
"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": 24843,
"s": 24823,
"text": "hritikbhatnagar2182"
},
{
"code": null,
"e": 24859,
"s": 24843,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 24864,
"s": 24859,
"text": "HTML"
},
{
"code": null,
"e": 24881,
"s": 24864,
"text": "Web Technologies"
},
{
"code": null,
"e": 24886,
"s": 24881,
"text": "HTML"
},
{
"code": null,
"e": 24984,
"s": 24886,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24993,
"s": 24984,
"text": "Comments"
},
{
"code": null,
"e": 25006,
"s": 24993,
"text": "Old Comments"
},
{
"code": null,
"e": 25054,
"s": 25006,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 25104,
"s": 25054,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 25128,
"s": 25104,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 25178,
"s": 25128,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 25215,
"s": 25178,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 25257,
"s": 25215,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 25290,
"s": 25257,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 25333,
"s": 25290,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 25378,
"s": 25333,
"text": "Convert a string to an integer in JavaScript"
}
]
|
Convert an array of binary numbers to corresponding integer in JavaScript | Let’s say, we have an array of Numbers that contains 0 and 1 −
const arr = [0, 1, 0, 1];
We are required to write an Array function, toBinary() that returns the corresponding binary for
the array it is used with.
For example − If the array is −
const arr = [1, 0, 1, 1];
Then the output should be 11 because the decimal representation of binary 1011 is 11.
Therefore, let’s write the code for this function.
In JavaScript, there exists a method parseInt(), that takes in two arguments first one is a string
and second a number that represents a particular base, like 10 for decimal base, 2 for binary.
This function parses the string argument and returns an integer of the specified radix ( base).
In our case, to convert the array of binary to decimal, we can use the parseInt() function like
this −
const arr = [1, 0, 1, 1];
const parseArray = arr => {
const binaryString = arr.join("");
return parseInt(binaryString, 2);
};
console.log(parseArray(arr));
In this method we iterate over the binary array and construct a decimal based on the
corresponding binary numbers. We will use the left shift operator (<<) to shift the accumulated
value to left by one bit every time and return the bitwise OR (|) of the shifted accumulated value
and current value.
The code for this using Bitwise Operator −
const arr = [1, 0, 1, 1];
const parseArray = arr => {
return arr.reduce((acc, val) => {
return (acc << 1) | val;
});
};
console.log(parseArray(arr));
The output in the console will be −
11 | [
{
"code": null,
"e": 1125,
"s": 1062,
"text": "Let’s say, we have an array of Numbers that contains 0 and 1 −"
},
{
"code": null,
"e": 1151,
"s": 1125,
"text": "const arr = [0, 1, 0, 1];"
},
{
"code": null,
"e": 1275,
"s": 1151,
"text": "We are required to write an Array function, toBinary() that returns the corresponding binary for\nthe array it is used with."
},
{
"code": null,
"e": 1307,
"s": 1275,
"text": "For example − If the array is −"
},
{
"code": null,
"e": 1333,
"s": 1307,
"text": "const arr = [1, 0, 1, 1];"
},
{
"code": null,
"e": 1419,
"s": 1333,
"text": "Then the output should be 11 because the decimal representation of binary 1011 is 11."
},
{
"code": null,
"e": 1470,
"s": 1419,
"text": "Therefore, let’s write the code for this function."
},
{
"code": null,
"e": 1760,
"s": 1470,
"text": "In JavaScript, there exists a method parseInt(), that takes in two arguments first one is a string\nand second a number that represents a particular base, like 10 for decimal base, 2 for binary.\nThis function parses the string argument and returns an integer of the specified radix ( base)."
},
{
"code": null,
"e": 1863,
"s": 1760,
"text": "In our case, to convert the array of binary to decimal, we can use the parseInt() function like\nthis −"
},
{
"code": null,
"e": 2025,
"s": 1863,
"text": "const arr = [1, 0, 1, 1];\nconst parseArray = arr => {\n const binaryString = arr.join(\"\");\n return parseInt(binaryString, 2);\n};\nconsole.log(parseArray(arr));"
},
{
"code": null,
"e": 2324,
"s": 2025,
"text": "In this method we iterate over the binary array and construct a decimal based on the\ncorresponding binary numbers. We will use the left shift operator (<<) to shift the accumulated\nvalue to left by one bit every time and return the bitwise OR (|) of the shifted accumulated value\nand current value."
},
{
"code": null,
"e": 2367,
"s": 2324,
"text": "The code for this using Bitwise Operator −"
},
{
"code": null,
"e": 2529,
"s": 2367,
"text": "const arr = [1, 0, 1, 1];\nconst parseArray = arr => {\n return arr.reduce((acc, val) => {\n return (acc << 1) | val;\n });\n};\nconsole.log(parseArray(arr));"
},
{
"code": null,
"e": 2565,
"s": 2529,
"text": "The output in the console will be −"
},
{
"code": null,
"e": 2568,
"s": 2565,
"text": "11"
}
]
|
Python Pandas - Get the number of days from TimeDelta | To get the number of days from TimeDelta, use the timedelta.days property in Pandas. At first, import the required libraries −
import pandas as pd
TimeDeltas is Python’s standard datetime library uses a different representation timedelta’s. Create a Timedelta object
timedelta = pd.Timedelta('5 days 1 min 45 s')
Return the number of days
timedelta.days
Following is the code
import pandas as pd
# TimeDeltas is Python’s standard datetime library uses a different representation timedelta’s
# create a Timedelta object
timedelta = pd.Timedelta('5 days 1 min 45 s')
# display the Timedelta
print("Timedelta...\n", timedelta)
# return the number of days
res = timedelta.days
# display the days
print("\nDays...\n", res)
This will produce the following code
Timedelta...
5 days 00:01:45
Days...
5 | [
{
"code": null,
"e": 1314,
"s": 1187,
"text": "To get the number of days from TimeDelta, use the timedelta.days property in Pandas. At first, import the required libraries −"
},
{
"code": null,
"e": 1334,
"s": 1314,
"text": "import pandas as pd"
},
{
"code": null,
"e": 1454,
"s": 1334,
"text": "TimeDeltas is Python’s standard datetime library uses a different representation timedelta’s. Create a Timedelta object"
},
{
"code": null,
"e": 1501,
"s": 1454,
"text": "timedelta = pd.Timedelta('5 days 1 min 45 s')\n"
},
{
"code": null,
"e": 1527,
"s": 1501,
"text": "Return the number of days"
},
{
"code": null,
"e": 1542,
"s": 1527,
"text": "timedelta.days"
},
{
"code": null,
"e": 1564,
"s": 1542,
"text": "Following is the code"
},
{
"code": null,
"e": 1910,
"s": 1564,
"text": "import pandas as pd\n\n# TimeDeltas is Python’s standard datetime library uses a different representation timedelta’s\n# create a Timedelta object\ntimedelta = pd.Timedelta('5 days 1 min 45 s')\n\n# display the Timedelta\nprint(\"Timedelta...\\n\", timedelta)\n\n# return the number of days\nres = timedelta.days\n\n# display the days\nprint(\"\\nDays...\\n\", res)"
},
{
"code": null,
"e": 1947,
"s": 1910,
"text": "This will produce the following code"
},
{
"code": null,
"e": 1989,
"s": 1947,
"text": "Timedelta...\n 5 days 00:01:45\n\nDays...\n 5"
}
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.