title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Erlang - Variables
|
In Erlang, all the variables are bound with the ‘=’ statement. All variables need to start with the upper case character. In other programming languages, the ‘=’ sign is used for the assignment, but not in the case of Erlang. As stated, variables are defined with the use of the ‘=’ statement.
One key thing to note in Erlang is that variables are immutable, which means that in order for the value of the variable to change, it needs to be destroyed and recreated again.
The following basic variables in Erlang are explained in the last chapter −
Numbers − This is used to represent an integer or a float. An example is 10.
Numbers − This is used to represent an integer or a float. An example is 10.
Boolean − This represents a Boolean value which can either be true or false.
Boolean − This represents a Boolean value which can either be true or false.
Bit String − A bit string is used to store an area of un-typed memory. An example is <<40,50>>.
Bit String − A bit string is used to store an area of un-typed memory. An example is <<40,50>>.
Tuple − A tuple is a compound data type with a fixed number of terms. An example is {40,50}.
Tuple − A tuple is a compound data type with a fixed number of terms. An example is {40,50}.
Map − A map is a compound data type with a variable number of key-value associations. Each key-value association in the map is called an association pair. An example is {type=>person,age=>25}.
Map − A map is a compound data type with a variable number of key-value associations. Each key-value association in the map is called an association pair. An example is {type=>person,age=>25}.
List − A list is a compound data type with a variable number of terms. An example is [40,40].
List − A list is a compound data type with a variable number of terms. An example is [40,40].
The general syntax of defining a variable is as follows −
var-name = var-value
Where,
var-name − This is the name of the variable.
var-name − This is the name of the variable.
var-value − This is the value bound to the variable.
var-value − This is the value bound to the variable.
Following is an example of variable declaration −
-module(helloworld).
-export([start/0]).
start() ->
X = 40,
Y = 50,
Result = X + Y,
io:fwrite("~w",[Result]).
In the above example, we have 2 variables, one is X which is bound to the value 40 and the next is Y which is bound to the value of 50. Another variable called Result is bound to the addition of X and Y.
The output of the above program will be −
90
As discussed, variable names have to start with uppercase. Let’s take an example of a variable declared in lower case.
-module(helloworld).
-export([start/0]).
start() ->
X = 40,
Y = 50,
result = X + Y,
io:fwrite("~w",[Result]).
If you try to compile the above program, you will get the following compile time error.
helloworld.erl:8: variable 'Result' is unbound
Secondly, all variables can only be assigned once. Let’s take an example of assigning a variable more than once.
-module(helloworld).
-export([start/0]).
start() ->
X = 40,
Y = 50,
X = 60,
io:fwrite("~w",[X]).
If you try to compile the above program, you will receive the following compile time error.
helloworld.erl:6: Warning: variable 'Y' is unused
helloworld.erl:7: Warning: no clause will ever match
helloworld.erl:7: Warning: the guard for this clause evaluates to 'false'
In this section we will discuss how to use the various functions of printing variables.
You would have seen this (io:fwrite) used in all of the above programs. The fwrite function is part of the ‘io’ module or Erlang, which can be used to output the value of variables in the program.
The following example shows a few more parameters which can be used with the fwrite statement.
-module(helloworld).
-export([start/0]).
start() ->
X = 40.00,
Y = 50.00,
io:fwrite("~f~n",[X]),
io:fwrite("~e",[Y]).
The output of the above program will be −
40.000000
5.00000e+1
The following pointers should be noted about the above program.
~ − This character symbolizes that some formatting needs to be carried out for the output.
~ − This character symbolizes that some formatting needs to be carried out for the output.
~f − The argument is a float which is written as [-]ddd.ddd, where the precision is the number of digits after the decimal point. The default precision is 6 and it cannot be less than 1.
~f − The argument is a float which is written as [-]ddd.ddd, where the precision is the number of digits after the decimal point. The default precision is 6 and it cannot be less than 1.
~n − This is to println to a new line.
~n − This is to println to a new line.
~e − The argument is a float which is written as [-]d.ddde+-ddd, where the precision is the number of digits written. The default precision is 6 and it cannot be less than 2.
~e − The argument is a float which is written as [-]d.ddde+-ddd, where the precision is the number of digits written. The default precision is 6 and it cannot be less than 2.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2595,
"s": 2301,
"text": "In Erlang, all the variables are bound with the ‘=’ statement. All variables need to start with the upper case character. In other programming languages, the ‘=’ sign is used for the assignment, but not in the case of Erlang. As stated, variables are defined with the use of the ‘=’ statement."
},
{
"code": null,
"e": 2773,
"s": 2595,
"text": "One key thing to note in Erlang is that variables are immutable, which means that in order for the value of the variable to change, it needs to be destroyed and recreated again."
},
{
"code": null,
"e": 2849,
"s": 2773,
"text": "The following basic variables in Erlang are explained in the last chapter −"
},
{
"code": null,
"e": 2926,
"s": 2849,
"text": "Numbers − This is used to represent an integer or a float. An example is 10."
},
{
"code": null,
"e": 3003,
"s": 2926,
"text": "Numbers − This is used to represent an integer or a float. An example is 10."
},
{
"code": null,
"e": 3080,
"s": 3003,
"text": "Boolean − This represents a Boolean value which can either be true or false."
},
{
"code": null,
"e": 3157,
"s": 3080,
"text": "Boolean − This represents a Boolean value which can either be true or false."
},
{
"code": null,
"e": 3253,
"s": 3157,
"text": "Bit String − A bit string is used to store an area of un-typed memory. An example is <<40,50>>."
},
{
"code": null,
"e": 3349,
"s": 3253,
"text": "Bit String − A bit string is used to store an area of un-typed memory. An example is <<40,50>>."
},
{
"code": null,
"e": 3442,
"s": 3349,
"text": "Tuple − A tuple is a compound data type with a fixed number of terms. An example is {40,50}."
},
{
"code": null,
"e": 3535,
"s": 3442,
"text": "Tuple − A tuple is a compound data type with a fixed number of terms. An example is {40,50}."
},
{
"code": null,
"e": 3728,
"s": 3535,
"text": "Map − A map is a compound data type with a variable number of key-value associations. Each key-value association in the map is called an association pair. An example is {type=>person,age=>25}."
},
{
"code": null,
"e": 3921,
"s": 3728,
"text": "Map − A map is a compound data type with a variable number of key-value associations. Each key-value association in the map is called an association pair. An example is {type=>person,age=>25}."
},
{
"code": null,
"e": 4015,
"s": 3921,
"text": "List − A list is a compound data type with a variable number of terms. An example is [40,40]."
},
{
"code": null,
"e": 4109,
"s": 4015,
"text": "List − A list is a compound data type with a variable number of terms. An example is [40,40]."
},
{
"code": null,
"e": 4167,
"s": 4109,
"text": "The general syntax of defining a variable is as follows −"
},
{
"code": null,
"e": 4189,
"s": 4167,
"text": "var-name = var-value\n"
},
{
"code": null,
"e": 4196,
"s": 4189,
"text": "Where,"
},
{
"code": null,
"e": 4241,
"s": 4196,
"text": "var-name − This is the name of the variable."
},
{
"code": null,
"e": 4286,
"s": 4241,
"text": "var-name − This is the name of the variable."
},
{
"code": null,
"e": 4339,
"s": 4286,
"text": "var-value − This is the value bound to the variable."
},
{
"code": null,
"e": 4392,
"s": 4339,
"text": "var-value − This is the value bound to the variable."
},
{
"code": null,
"e": 4442,
"s": 4392,
"text": "Following is an example of variable declaration −"
},
{
"code": null,
"e": 4571,
"s": 4442,
"text": "-module(helloworld). \n-export([start/0]). \n\nstart() -> \n X = 40, \n Y = 50, \n Result = X + Y, \n io:fwrite(\"~w\",[Result])."
},
{
"code": null,
"e": 4775,
"s": 4571,
"text": "In the above example, we have 2 variables, one is X which is bound to the value 40 and the next is Y which is bound to the value of 50. Another variable called Result is bound to the addition of X and Y."
},
{
"code": null,
"e": 4817,
"s": 4775,
"text": "The output of the above program will be −"
},
{
"code": null,
"e": 4821,
"s": 4817,
"text": "90\n"
},
{
"code": null,
"e": 4940,
"s": 4821,
"text": "As discussed, variable names have to start with uppercase. Let’s take an example of a variable declared in lower case."
},
{
"code": null,
"e": 5069,
"s": 4940,
"text": "-module(helloworld). \n-export([start/0]). \n\nstart() -> \n X = 40, \n Y = 50, \n result = X + Y, \n io:fwrite(\"~w\",[Result])."
},
{
"code": null,
"e": 5157,
"s": 5069,
"text": "If you try to compile the above program, you will get the following compile time error."
},
{
"code": null,
"e": 5205,
"s": 5157,
"text": "helloworld.erl:8: variable 'Result' is unbound\n"
},
{
"code": null,
"e": 5318,
"s": 5205,
"text": "Secondly, all variables can only be assigned once. Let’s take an example of assigning a variable more than once."
},
{
"code": null,
"e": 5434,
"s": 5318,
"text": "-module(helloworld). \n-export([start/0]). \n\nstart() -> \n X = 40, \n Y = 50, \n X = 60, \n io:fwrite(\"~w\",[X])."
},
{
"code": null,
"e": 5526,
"s": 5434,
"text": "If you try to compile the above program, you will receive the following compile time error."
},
{
"code": null,
"e": 5704,
"s": 5526,
"text": "helloworld.erl:6: Warning: variable 'Y' is unused\nhelloworld.erl:7: Warning: no clause will ever match\nhelloworld.erl:7: Warning: the guard for this clause evaluates to 'false'\n"
},
{
"code": null,
"e": 5792,
"s": 5704,
"text": "In this section we will discuss how to use the various functions of printing variables."
},
{
"code": null,
"e": 5989,
"s": 5792,
"text": "You would have seen this (io:fwrite) used in all of the above programs. The fwrite function is part of the ‘io’ module or Erlang, which can be used to output the value of variables in the program."
},
{
"code": null,
"e": 6084,
"s": 5989,
"text": "The following example shows a few more parameters which can be used with the fwrite statement."
},
{
"code": null,
"e": 6221,
"s": 6084,
"text": "-module(helloworld). \n-export([start/0]). \n\nstart() -> \n X = 40.00, \n Y = 50.00, \n io:fwrite(\"~f~n\",[X]), \n io:fwrite(\"~e\",[Y])."
},
{
"code": null,
"e": 6263,
"s": 6221,
"text": "The output of the above program will be −"
},
{
"code": null,
"e": 6285,
"s": 6263,
"text": "40.000000\n5.00000e+1\n"
},
{
"code": null,
"e": 6349,
"s": 6285,
"text": "The following pointers should be noted about the above program."
},
{
"code": null,
"e": 6440,
"s": 6349,
"text": "~ − This character symbolizes that some formatting needs to be carried out for the output."
},
{
"code": null,
"e": 6531,
"s": 6440,
"text": "~ − This character symbolizes that some formatting needs to be carried out for the output."
},
{
"code": null,
"e": 6718,
"s": 6531,
"text": "~f − The argument is a float which is written as [-]ddd.ddd, where the precision is the number of digits after the decimal point. The default precision is 6 and it cannot be less than 1."
},
{
"code": null,
"e": 6905,
"s": 6718,
"text": "~f − The argument is a float which is written as [-]ddd.ddd, where the precision is the number of digits after the decimal point. The default precision is 6 and it cannot be less than 1."
},
{
"code": null,
"e": 6944,
"s": 6905,
"text": "~n − This is to println to a new line."
},
{
"code": null,
"e": 6983,
"s": 6944,
"text": "~n − This is to println to a new line."
},
{
"code": null,
"e": 7158,
"s": 6983,
"text": "~e − The argument is a float which is written as [-]d.ddde+-ddd, where the precision is the number of digits written. The default precision is 6 and it cannot be less than 2."
},
{
"code": null,
"e": 7333,
"s": 7158,
"text": "~e − The argument is a float which is written as [-]d.ddde+-ddd, where the precision is the number of digits written. The default precision is 6 and it cannot be less than 2."
},
{
"code": null,
"e": 7340,
"s": 7333,
"text": " Print"
},
{
"code": null,
"e": 7351,
"s": 7340,
"text": " Add Notes"
}
] |
Remove a character from a Java StringBuffer object
|
In order to remove a character from a Java StringBuffer object, we use the deleteCharAt() method. The deleteCharAt() removes the character at the specified index. The length of resultant sequence of characters of the StringBuffer object is reduced by one.
Declaration − The java.lang.StringBuffer.deleteCharAt() method is declared as follows−
public StringBuffer deleteCharAt(int index)
Let us see a program to illustrate the use of the deleteCharAt()
Live Demo
public class Example {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello World");
sb.deleteCharAt(7);
System.out.println(sb);
}
}
Hello Wrld
|
[
{
"code": null,
"e": 1318,
"s": 1062,
"text": "In order to remove a character from a Java StringBuffer object, we use the deleteCharAt() method. The deleteCharAt() removes the character at the specified index. The length of resultant sequence of characters of the StringBuffer object is reduced by one."
},
{
"code": null,
"e": 1405,
"s": 1318,
"text": "Declaration − The java.lang.StringBuffer.deleteCharAt() method is declared as follows−"
},
{
"code": null,
"e": 1449,
"s": 1405,
"text": "public StringBuffer deleteCharAt(int index)"
},
{
"code": null,
"e": 1514,
"s": 1449,
"text": "Let us see a program to illustrate the use of the deleteCharAt()"
},
{
"code": null,
"e": 1525,
"s": 1514,
"text": " Live Demo"
},
{
"code": null,
"e": 1712,
"s": 1525,
"text": "public class Example {\n public static void main(String[] args) {\n StringBuffer sb = new StringBuffer(\"Hello World\");\n sb.deleteCharAt(7);\n System.out.println(sb);\n }\n}"
},
{
"code": null,
"e": 1723,
"s": 1712,
"text": "Hello Wrld"
}
] |
Gradient Descent and Adam Optimization | Towards Data Science
|
How artificial intelligence has influenced our daily lives in the past decade is something we can only ponder about. From spam filtering to news clustering, computer vision applications like fingerprint sensors to natural language processing problems like handwriting and speech recognition, it is very easy to undermine how big a role AI and data science is playing in our day-to-day lives. However, with an exponential increase in amount of data our algorithms deal with, it is essential to develop algorithms which can keep pace with this rise in complexity. One such algorithm which has caused a notable change to the industry is the Adam Optimization procedure. But before we delve into it, first let us look at gradient descent and where it falls short.
In case if you aren’t aware of what a cost function is, I would recommend you to go through this blog first, which serves as a great introduction to the topic: https://medium.com/@lachlanmiller_52885/understanding-and-calculating-the-cost-function-for-linear-regression-39b8a3519fcb
Suppose we have a convex cost function of 2 input variables as shown above and our goal is to minimize its value and find the value of the parameters (x,y) for which f(x,y) is minimum. What the gradient descent algorithm does is, we start at a specific point on the curve and use the negative gradient to find the direction of steepest descent and take a small step in that direction and keep iterating till our value starts converging.
I personally find the above analogy to gradient descent very cool, a person starting from the top of a hill and climbing down by the path which enables him to decrease his altitude quickest.
The formal definition of gradient descent is given alongside, we keep performing the update as required till convergence is reached. We can check convergence easily by checking whether the difference between f(Xi+1) and f(Xi) is less than some number, say 0.0001(the default value if you implement gradient descent using Python). If so, we say that gradient descent has converged at a local minimum of f.
If you cannot quite grasp the gradient concept or are interested in more in-depth knowledge of cost function and gradient descent, I strongly recommend the following video from my favorite YouTube channel 3Blue1Brown -
To perform a single step of gradient descent, we need to iterate over all training examples to find out the gradient at a particular point. This is termed as batch gradient descent and was done for many years but with the advent of the era of deep learning and big data, it has become common to have a training set size of the order of millions and this becomes computationally expensive, it may take few minutes to perform a single step of gradient descent. So what is done commonly, is something called a mini-batch gradient descent where we divide the training set into batches of small size and perform gradient descent using those batches individually. This often results in a faster convergence but there’s a major problem here — We only look at a fraction of the training set while taking a single step and hence, the step may not be towards the steepest decrease of the cost function. This is because we are minimizing the cost based on a subset of the total data, which is not a representative of what’s best for the entire training data. Instead of following a straight path towards the minimum, our algorithm now follows a roundabout path, not always even leading to an optimum and most commonly, overshooting (going past the minimum).
The following figures alongside show the steps of gradient descent in the 3 different batch size cases, and changes in how the cost function minimizes. In both the figures, it is apparent that the cost function is minimizing, but it oscillates even though in general, it is decreasing. The problem is as follows, Can we somehow “smoothen” out these steps of gradient descent so that it can follow a less noisy path and converge faster? The answer, as you might already have guessed, is Adam Optimization.
There’s a lot going on here. Let’s quickly break it down. First, let’s see the parameters involved.
α — Learning Rate for gradient descent step.β1 — Parameter for momentum step (also known as first moment in Adam). Generally 0.9β2 — Parameter for RMSProp step (also known as second moment in Adam). Generally 0.99ε — Parameter for numerical stability. Generally 10^-8m , v — First and second moment estimates, respectively. Initial values of both set to 0.t — The timestep parameter for bias correction steps.g and f — Gradient and function values at θ.
α — Learning Rate for gradient descent step.
β1 — Parameter for momentum step (also known as first moment in Adam). Generally 0.9
β2 — Parameter for RMSProp step (also known as second moment in Adam). Generally 0.99
ε — Parameter for numerical stability. Generally 10^-8
m , v — First and second moment estimates, respectively. Initial values of both set to 0.
t — The timestep parameter for bias correction steps.
g and f — Gradient and function values at θ.
Adam can essentially be broken down as a combination of 2 main algorithms— Momentum and RMSProp. The momentum step is as follows -
m = beta1 * m + (1 - beta1) * g
Suppose beta1=0.9. Then the corresponding step calculates 0.9*current moment + 0.1*current gradient. You can think of this as a weighted average over the last 10 gradient descent steps, which cancels out a lot of noise. However initially, moment is set to 0 hence the moment at the first step = 0.9*0 + 0.1*gradient = gradient/10 and so on. The moment will fail to keep up with the original gradient ,and this is known as a biased estimate. To correct this we do the following, known as bias correction ,dividing by 1 - (beta1 raised to the timestep) -
m_corrected = m / (1 - np.power(beta1, t))
Note that 1 - power(beta1,t) approaches 1 as t becomes higher with each step, decreasing the correction effect later and maximizing it at the first few steps.
The graph alongside pictures this perfectly, the yellow line refers to the moment(estimate) obtained with a smaller beta1, say 0.5 while the green line refers to a beta1 value closer to 1, say 0.9
RMSProp does a similar thing, but slightly different -
v = beta2 * v + (1 - beta2) * np.square(g)v_corrected = v / (1 - np.power(beta2, t))
It also computes a weighted average over the last 1/(1-beta2) examples approximately, which is 100 when beta2=0.99. But it computes the average of the squares of the gradient (a sort of scaled magnitude), and then the same bias correction step.
Now, in the gradient descent step instead of using the gradient we use these moments as follows -
theta = theta - learning_rate * m_corrected / np.sqrt(v_corrected) + epsilon)
Using m_corrected ensures that our gradient moves in the direction of the general trend and does not oscillate about too much while dividing by the square root of the mean of squared magnitudes ensures that the overall magnitude of the steps is fixed and close to unit value. This also adds in adaptive gradient, which I am not going to talk about in detail, it’s just a procedure of changing the magnitude of the steps as we approach convergence. This helps prevent overshooting. Finally, epsilon is added to the denominator to avoid division by 0 in case the estimate of the gradients encountered are too small and are rounded off to 0 by the compiler. The value is deliberately chosen to be very small so as not to affect the algorithm, generally of the order of 10^-8.
Adam has been in widespread use in Deep Learning models since 2015. It was presented by Diederik Kingma from OpenAI and Jimmy Ba from the University of Toronto in their 2015 ICLR paper “Adam: A method for stochastic gradient optimization”. Adam, as it may sound, has not been named after someone. It is short for “Adaptive Moment Estimation”. The following figure shows it’s effectiveness compared to other minimizing algorithms when applied to a neural network model on the MNIST dataset.
Adam has been one of the most remarkable achievements in the grounds of optimization. Several incidents where the training of a large model required days have been reduced to hours since usage of Adam. Since it’s inception it has been made the default optimizer used in almost all deep learning libraries. I myself use Adam frequently — on a handwritten digit classification problem, I found that just by changing my optimizer from mini-batch gradient descent to Adam my training accuracy jumped from 79% to 94%, and number of iterations required reduced to about one-third, a pretty significant change considering that my training data was of size about 10,000, not even close to a million, where the effects would be even more significant!
|
[
{
"code": null,
"e": 932,
"s": 172,
"text": "How artificial intelligence has influenced our daily lives in the past decade is something we can only ponder about. From spam filtering to news clustering, computer vision applications like fingerprint sensors to natural language processing problems like handwriting and speech recognition, it is very easy to undermine how big a role AI and data science is playing in our day-to-day lives. However, with an exponential increase in amount of data our algorithms deal with, it is essential to develop algorithms which can keep pace with this rise in complexity. One such algorithm which has caused a notable change to the industry is the Adam Optimization procedure. But before we delve into it, first let us look at gradient descent and where it falls short."
},
{
"code": null,
"e": 1215,
"s": 932,
"text": "In case if you aren’t aware of what a cost function is, I would recommend you to go through this blog first, which serves as a great introduction to the topic: https://medium.com/@lachlanmiller_52885/understanding-and-calculating-the-cost-function-for-linear-regression-39b8a3519fcb"
},
{
"code": null,
"e": 1652,
"s": 1215,
"text": "Suppose we have a convex cost function of 2 input variables as shown above and our goal is to minimize its value and find the value of the parameters (x,y) for which f(x,y) is minimum. What the gradient descent algorithm does is, we start at a specific point on the curve and use the negative gradient to find the direction of steepest descent and take a small step in that direction and keep iterating till our value starts converging."
},
{
"code": null,
"e": 1843,
"s": 1652,
"text": "I personally find the above analogy to gradient descent very cool, a person starting from the top of a hill and climbing down by the path which enables him to decrease his altitude quickest."
},
{
"code": null,
"e": 2248,
"s": 1843,
"text": "The formal definition of gradient descent is given alongside, we keep performing the update as required till convergence is reached. We can check convergence easily by checking whether the difference between f(Xi+1) and f(Xi) is less than some number, say 0.0001(the default value if you implement gradient descent using Python). If so, we say that gradient descent has converged at a local minimum of f."
},
{
"code": null,
"e": 2467,
"s": 2248,
"text": "If you cannot quite grasp the gradient concept or are interested in more in-depth knowledge of cost function and gradient descent, I strongly recommend the following video from my favorite YouTube channel 3Blue1Brown -"
},
{
"code": null,
"e": 3714,
"s": 2467,
"text": "To perform a single step of gradient descent, we need to iterate over all training examples to find out the gradient at a particular point. This is termed as batch gradient descent and was done for many years but with the advent of the era of deep learning and big data, it has become common to have a training set size of the order of millions and this becomes computationally expensive, it may take few minutes to perform a single step of gradient descent. So what is done commonly, is something called a mini-batch gradient descent where we divide the training set into batches of small size and perform gradient descent using those batches individually. This often results in a faster convergence but there’s a major problem here — We only look at a fraction of the training set while taking a single step and hence, the step may not be towards the steepest decrease of the cost function. This is because we are minimizing the cost based on a subset of the total data, which is not a representative of what’s best for the entire training data. Instead of following a straight path towards the minimum, our algorithm now follows a roundabout path, not always even leading to an optimum and most commonly, overshooting (going past the minimum)."
},
{
"code": null,
"e": 4219,
"s": 3714,
"text": "The following figures alongside show the steps of gradient descent in the 3 different batch size cases, and changes in how the cost function minimizes. In both the figures, it is apparent that the cost function is minimizing, but it oscillates even though in general, it is decreasing. The problem is as follows, Can we somehow “smoothen” out these steps of gradient descent so that it can follow a less noisy path and converge faster? The answer, as you might already have guessed, is Adam Optimization."
},
{
"code": null,
"e": 4319,
"s": 4219,
"text": "There’s a lot going on here. Let’s quickly break it down. First, let’s see the parameters involved."
},
{
"code": null,
"e": 4773,
"s": 4319,
"text": "α — Learning Rate for gradient descent step.β1 — Parameter for momentum step (also known as first moment in Adam). Generally 0.9β2 — Parameter for RMSProp step (also known as second moment in Adam). Generally 0.99ε — Parameter for numerical stability. Generally 10^-8m , v — First and second moment estimates, respectively. Initial values of both set to 0.t — The timestep parameter for bias correction steps.g and f — Gradient and function values at θ."
},
{
"code": null,
"e": 4818,
"s": 4773,
"text": "α — Learning Rate for gradient descent step."
},
{
"code": null,
"e": 4903,
"s": 4818,
"text": "β1 — Parameter for momentum step (also known as first moment in Adam). Generally 0.9"
},
{
"code": null,
"e": 4989,
"s": 4903,
"text": "β2 — Parameter for RMSProp step (also known as second moment in Adam). Generally 0.99"
},
{
"code": null,
"e": 5044,
"s": 4989,
"text": "ε — Parameter for numerical stability. Generally 10^-8"
},
{
"code": null,
"e": 5134,
"s": 5044,
"text": "m , v — First and second moment estimates, respectively. Initial values of both set to 0."
},
{
"code": null,
"e": 5188,
"s": 5134,
"text": "t — The timestep parameter for bias correction steps."
},
{
"code": null,
"e": 5233,
"s": 5188,
"text": "g and f — Gradient and function values at θ."
},
{
"code": null,
"e": 5364,
"s": 5233,
"text": "Adam can essentially be broken down as a combination of 2 main algorithms— Momentum and RMSProp. The momentum step is as follows -"
},
{
"code": null,
"e": 5396,
"s": 5364,
"text": "m = beta1 * m + (1 - beta1) * g"
},
{
"code": null,
"e": 5949,
"s": 5396,
"text": "Suppose beta1=0.9. Then the corresponding step calculates 0.9*current moment + 0.1*current gradient. You can think of this as a weighted average over the last 10 gradient descent steps, which cancels out a lot of noise. However initially, moment is set to 0 hence the moment at the first step = 0.9*0 + 0.1*gradient = gradient/10 and so on. The moment will fail to keep up with the original gradient ,and this is known as a biased estimate. To correct this we do the following, known as bias correction ,dividing by 1 - (beta1 raised to the timestep) -"
},
{
"code": null,
"e": 5992,
"s": 5949,
"text": "m_corrected = m / (1 - np.power(beta1, t))"
},
{
"code": null,
"e": 6151,
"s": 5992,
"text": "Note that 1 - power(beta1,t) approaches 1 as t becomes higher with each step, decreasing the correction effect later and maximizing it at the first few steps."
},
{
"code": null,
"e": 6348,
"s": 6151,
"text": "The graph alongside pictures this perfectly, the yellow line refers to the moment(estimate) obtained with a smaller beta1, say 0.5 while the green line refers to a beta1 value closer to 1, say 0.9"
},
{
"code": null,
"e": 6403,
"s": 6348,
"text": "RMSProp does a similar thing, but slightly different -"
},
{
"code": null,
"e": 6488,
"s": 6403,
"text": "v = beta2 * v + (1 - beta2) * np.square(g)v_corrected = v / (1 - np.power(beta2, t))"
},
{
"code": null,
"e": 6733,
"s": 6488,
"text": "It also computes a weighted average over the last 1/(1-beta2) examples approximately, which is 100 when beta2=0.99. But it computes the average of the squares of the gradient (a sort of scaled magnitude), and then the same bias correction step."
},
{
"code": null,
"e": 6831,
"s": 6733,
"text": "Now, in the gradient descent step instead of using the gradient we use these moments as follows -"
},
{
"code": null,
"e": 6909,
"s": 6831,
"text": "theta = theta - learning_rate * m_corrected / np.sqrt(v_corrected) + epsilon)"
},
{
"code": null,
"e": 7682,
"s": 6909,
"text": "Using m_corrected ensures that our gradient moves in the direction of the general trend and does not oscillate about too much while dividing by the square root of the mean of squared magnitudes ensures that the overall magnitude of the steps is fixed and close to unit value. This also adds in adaptive gradient, which I am not going to talk about in detail, it’s just a procedure of changing the magnitude of the steps as we approach convergence. This helps prevent overshooting. Finally, epsilon is added to the denominator to avoid division by 0 in case the estimate of the gradients encountered are too small and are rounded off to 0 by the compiler. The value is deliberately chosen to be very small so as not to affect the algorithm, generally of the order of 10^-8."
},
{
"code": null,
"e": 8172,
"s": 7682,
"text": "Adam has been in widespread use in Deep Learning models since 2015. It was presented by Diederik Kingma from OpenAI and Jimmy Ba from the University of Toronto in their 2015 ICLR paper “Adam: A method for stochastic gradient optimization”. Adam, as it may sound, has not been named after someone. It is short for “Adaptive Moment Estimation”. The following figure shows it’s effectiveness compared to other minimizing algorithms when applied to a neural network model on the MNIST dataset."
}
] |
DAX Filter - ALLSELECTED function
|
ALLSELECTED function gets the context that represents all rows and columns in the query, while keeping explicit filters and contexts other than row and column filters.
This function can be used to obtain visual totals in queries.
ALLSELECTED ([<tableName> | <columnName>])
tableName
Optional.
The name of a table.
It cannot be an expression.
columnName
Optional.
The name of a column, usually fully qualified.
It cannot be an expression.
The context of the query without any column and row filters.
ALLSELECTED function takes one or no arguments.
ALLSELECTED function takes one or no arguments.
If there is one argument, the argument is either tableName or columnName.
If there is one argument, the argument is either tableName or columnName.
This function is different from the function ALL () because it retains all filters explicitly set within the query, and it retains all context filters other than row and column filters.
This function is different from the function ALL () because it retains all filters explicitly set within the query, and it retains all context filters other than row and column filters.
SumTotal:= CALCULATE (SUM (Sales[Sales Amount]),ALLSELECTED ())
53 Lectures
5.5 hours
Abhay Gadiya
24 Lectures
2 hours
Randy Minder
26 Lectures
4.5 hours
Randy Minder
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2169,
"s": 2001,
"text": "ALLSELECTED function gets the context that represents all rows and columns in the query, while keeping explicit filters and contexts other than row and column filters."
},
{
"code": null,
"e": 2231,
"s": 2169,
"text": "This function can be used to obtain visual totals in queries."
},
{
"code": null,
"e": 2275,
"s": 2231,
"text": "ALLSELECTED ([<tableName> | <columnName>])\n"
},
{
"code": null,
"e": 2285,
"s": 2275,
"text": "tableName"
},
{
"code": null,
"e": 2295,
"s": 2285,
"text": "Optional."
},
{
"code": null,
"e": 2316,
"s": 2295,
"text": "The name of a table."
},
{
"code": null,
"e": 2344,
"s": 2316,
"text": "It cannot be an expression."
},
{
"code": null,
"e": 2355,
"s": 2344,
"text": "columnName"
},
{
"code": null,
"e": 2365,
"s": 2355,
"text": "Optional."
},
{
"code": null,
"e": 2412,
"s": 2365,
"text": "The name of a column, usually fully qualified."
},
{
"code": null,
"e": 2440,
"s": 2412,
"text": "It cannot be an expression."
},
{
"code": null,
"e": 2501,
"s": 2440,
"text": "The context of the query without any column and row filters."
},
{
"code": null,
"e": 2549,
"s": 2501,
"text": "ALLSELECTED function takes one or no arguments."
},
{
"code": null,
"e": 2597,
"s": 2549,
"text": "ALLSELECTED function takes one or no arguments."
},
{
"code": null,
"e": 2671,
"s": 2597,
"text": "If there is one argument, the argument is either tableName or columnName."
},
{
"code": null,
"e": 2745,
"s": 2671,
"text": "If there is one argument, the argument is either tableName or columnName."
},
{
"code": null,
"e": 2931,
"s": 2745,
"text": "This function is different from the function ALL () because it retains all filters explicitly set within the query, and it retains all context filters other than row and column filters."
},
{
"code": null,
"e": 3117,
"s": 2931,
"text": "This function is different from the function ALL () because it retains all filters explicitly set within the query, and it retains all context filters other than row and column filters."
},
{
"code": null,
"e": 3182,
"s": 3117,
"text": "SumTotal:= CALCULATE (SUM (Sales[Sales Amount]),ALLSELECTED ()) "
},
{
"code": null,
"e": 3217,
"s": 3182,
"text": "\n 53 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3231,
"s": 3217,
"text": " Abhay Gadiya"
},
{
"code": null,
"e": 3264,
"s": 3231,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3278,
"s": 3264,
"text": " Randy Minder"
},
{
"code": null,
"e": 3313,
"s": 3278,
"text": "\n 26 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3327,
"s": 3313,
"text": " Randy Minder"
},
{
"code": null,
"e": 3334,
"s": 3327,
"text": " Print"
},
{
"code": null,
"e": 3345,
"s": 3334,
"text": " Add Notes"
}
] |
What is the difference between declaration and definition in C#?
|
Declaration means that variable is only declared and memory is allocated, but no value is set.
However, definition means the variables has been initialized.
The same works for variables, arrays, collections, etc.
Declaring a variable.
int x;
Let’s define and assign a value.
x = 10;
Declaring an array.
int [] n // declaring
int n= new int[10]; // initializing
Let’s assign a value.
n[0] = 100;
n[1] = 200
|
[
{
"code": null,
"e": 1157,
"s": 1062,
"text": "Declaration means that variable is only declared and memory is allocated, but no value is set."
},
{
"code": null,
"e": 1219,
"s": 1157,
"text": "However, definition means the variables has been initialized."
},
{
"code": null,
"e": 1275,
"s": 1219,
"text": "The same works for variables, arrays, collections, etc."
},
{
"code": null,
"e": 1297,
"s": 1275,
"text": "Declaring a variable."
},
{
"code": null,
"e": 1304,
"s": 1297,
"text": "int x;"
},
{
"code": null,
"e": 1337,
"s": 1304,
"text": "Let’s define and assign a value."
},
{
"code": null,
"e": 1346,
"s": 1337,
"text": "x = 10;\n"
},
{
"code": null,
"e": 1366,
"s": 1346,
"text": "Declaring an array."
},
{
"code": null,
"e": 1424,
"s": 1366,
"text": "int [] n // declaring\nint n= new int[10]; // initializing"
},
{
"code": null,
"e": 1446,
"s": 1424,
"text": "Let’s assign a value."
},
{
"code": null,
"e": 1469,
"s": 1446,
"text": "n[0] = 100;\nn[1] = 200"
}
] |
Fit multiple propensity models and choose the best performing one for implementing a profit optimisation | by Diego Usai | Towards Data Science
|
In this day and age, a business that leverages data to understand the drivers of customers’ behaviour has a true competitive advantage. Organisations can dramatically improve their performance in the market by analysing customer level data in an effective way and focus their efforts towards those that are more likely to engage.
One trialled and tested approach to tease this type of insight out of data is Propensity Modelling, which combines information such as a customers’ demographics (age, race, religion, gender, family size, ethnicity, income, education level), psycho-graphic (social class, lifestyle and personality characteristics), engagement (emails opened, emails clicked, searches on a mobile app, webpage dwell time, etc.), user experience (customer service phone and email wait times, number of refunds, average shipping times), and user behaviour (purchase value on different time-scales, number of days since most recent purchase, the time between offer and conversion, etc.) to estimate the likelihood of a certain customer profile to perform a certain type of behaviour (e.g. the purchase of a product).
Once you understand the probability of a certain customer to interact with a brand, buy a product or sign up for a service, you can use this information to create scenarios, be it minimising marketing expenditure, maximising acquisition targets, and optimise email send frequency or depth of discount.
In this project, I’m analysing the results of a bank direct marketing campaign to sell term a deposit its existing clients in order to identify what type of characteristics make a customer more likely to respond. The marketing campaigns were based on phone calls and more than one contact to the same person was required at times.
First, I am going to carry out extensive data exploration and use the results and insights to prepare the data for analysis.
Then, I’m estimating the number of models and assess their performance and fit to the data using a model-agnostic methodology that enables to compare traditional “glass-box” models and “black-box” models.
Last, I’ll fit one final model that combines findings from the exploratory analysis and insight from models’ selection and use it to run a revenue optimisation.
library(tidyverse)library(data.table)library(skimr)library(correlationfunnel)library(GGally)library(ggmosaic)library(knitr)library(h2o)library(DALEX)library(knitr)library(tictoc)
The Data is the Portuguese Bank Marketing set from the UCI Machine Learning Repository and describes the direct marketing campaigns carried out by a Portuguese banking institution aimed at selling term deposits/certificate of deposits to their customers. The marketing campaigns were based on phone calls to potential buyers from May 2008 to November 2010.
The data I’m using (bank-direct-marketing.csv) is a modified version of the bank-additional-full.csv and contains 41,188 examples with 21 different variables (10 continuous, 10 categorical plus the target variable). In particular, the target subscribed is a binary response variable indicating whether the client subscribed (‘Yes’ or numeric value 1) to a term deposit or not (‘No’ or numeric value 0), which make this a binary classification problem.
The data required some manipulation to get into a usable format, details of which can be found on my webpage: Propensity Modelling — Data Preparation and Exploratory Data Analysis. Here I simply load up the pre-cleansed data I am hosting on my GitHub repo for this project
data_clean <- readRDS(file = "https://raw.githubusercontent.com/DiegoUsaiUK/Propensity_Modelling/master/01_data/data_clean.rds")
Although an integral part of any Data Science project and crucial to the full success of the analysis, Exploratory Data Analysis (EDA) can be an incredibly labour intensive and time consuming process. Recent years have seen a proliferation of approaches and libraries aimed at speeding up the process and in this project I’m going to sample one of the “new kids on the block” ( the correlationfunnel ) and combine its results with a more traditional EDA.
With 3 simple steps correlationfunnel can produce a graph that arranges predictors top to bottom in descending order of absolute correlation with the target variable. Features at the top of the funnel are expected to have stronger predictive power in a model.
This approach offers a quick way to identify a hierarchy of expected predictive power for all variables and gives an early indication of which predictors should feature strongly/weakly in any model.
data_clean %>% binarize(n_bins = 4, # bin number for converting features thresh_infreq = 0.01 # thresh. for assign categ. # features into "Other" ) %>% # correlate target variable to features correlate(target = subscribed__1) %>% # correlation funnel visualisation plot_correlation_funnel()
Zooming in on the top 5 features we can see that certain characteristics have a greater correlation with the target variable (subscribing to the term deposit product) when:
The duration of the last phone contact with the client is 319 seconds or longer
The number of days that passed by after the client was last contacted is greater than 6
The outcome of the previous marketing campaign was success
The number of employed is 5,099 thousands or higher
The value of the euribor 3 month rate is 1.344 or higher
Conversely, variables at the bottom of the funnel, such as day_of_week, housing, and loan. show very little variation compared to the target variable (i.e.: they are very close to the zero correlation point to the response). For that reason, I’m not expecting these features to impact the response.
Guided by the results of this visual correlation analysis, I will continue to explore the relationship between the target and each of the predictors in the next section. For this, I am going to enlist the help of the brilliant GGally library to visualise a modified version of the correlation matrix with Ggpairs, and plot mosaic charts with the ggmosaic package, a great way to examine the relationship among two or more categorical variables.
First things first, the target variable: subscribed shows a strong class imbalance, with nearly 89% in the No category to 11% in the Yes category.
I am going to address class imbalance during the modelling phase by enabling re-sampling, in h2o. This will rebalance the dataset by “shrinking” the prevalent class (“No” or 0) and ensure that the model adequately detects what variables are driving the ‘yes’ and ‘no’ responses.
Let’s continue with some of the numerical features:
Although the correlation funnel analysis revealed that duration has the strongest expected predictive power, it is unknown before a call (it’s obviously known afterwards) and offers very little actionable insight or predictive value. Therefore, it should be discarded from any realistic predictive model and will not be used in this analysis.
age ’s density plots have very similar variance compared to the target variable and are centred around the same area. For these reasons, it should not have a great impact on subscribed.
Despite continuous in nature, pdays and previous are in fact categorical features and are also all strongly right skewed. For these reasons, they will need to be discretised into groups. Both variables are also moderately correlated, suggesting that they may capture the same behaviour.
Next, I visualise the bank client data with the mosaic charts:
In line with the correlationfunnel findings, job, education, marital and default all show a good level of variation compared to the target variable, indicating that they would impact the response. In contrast, housing and loan sat at the very bottom of the funnel and are expected to have little influence on the target, given the small variation when split by “subscribed” response.
default has only 3 observations in the ‘yes’ level, which will be rolled into the least frequent level as they’re not enough to make a proper inference. Level ‘unknown’ of the housing and loan variables have a small number of observations and will be rolled into the second smallest category. Lastly, job and education would also benefit from grouping up of least common levels.
Moving on to the other campaign attributes:
Although continuous in principal, campaign is more categorical in nature and strongly right skewed, and will need to be discretised into groups. However, we have learned from the earlier correlation analysis that is not expected be a strong drivers of variation in any model.
On the other hand, poutcome is one of the attributes expected to be have a strong predictive power. The uneven distribution of levels would suggest to roll the least common occurring level (success or scs) into another category. However, contacting a client who previously purchased a term deposit is one of the catacteristics with highest predictive power and needs to be left ungrouped.
Then, I’m looking at last contact information:
contact and month should impact the response variable as they both have a good level of variation compared to the target. month would also benefit from grouping up of least common levels.
In contrast, day_of_week does not appear to impact the response as there is not enough variation between the levels.
Last but not least, the social and economic attributes:
All social and economic attributes show a good level of variation compared to the target variable, which suggests that they should all impact the response. They all display a high degree of multi-modality and do not have an even spread through the density plot, and will need to be binned.
It is also worth noting that, with the exception of consumer confidence index, all other social and economic attributes are strongly correlated to each other, indicating that only one could be included in the model as they are all “picking up” similar economic trend.
Correlation analysis with correlationfunnel helped identify a hierarchy of expected predictive power for all variables
duration has strongest correlation with target variable whereas some of the bank client data like housing and loan shows the weakest correlation
However, duration will NOT be used in the analysis as it is unknown before a call. As such it offers very little actionable insight or predictive value and should be discarded from any realistic predictive model
The target variable subscribed shows strong class imbalance, with nearly 89% of No churn, which will need to be addressed before the modelling analysis can begin
Most predictors would benefit from grouping up of least common levels
Further feature exploration revealed the most social and economic context attributes are strongly correlated to each other, suggesting that only a selection of them could be considered in a final model
Following up on the findings from the Exploratory Data Analysis, I’ve discretised categorical and continuous predictors by combining least common levels into “other’ category, set all variables but age as unordered factors ( h2o does not support ordered categorical variables) and shorted level names of some categorical variables to ease visualisations. You can find all the details and the full code on my webpage: Propensity Modelling - Data Preparation and Exploratory Data Analysis.
Here I simply load up the final dataset hosted on my GitHub repo:
data_final <- readRDS(file = "https://raw.githubusercontent.com/DiegoUsaiUK/Propensity_Modelling/master/01_data/data_final.rds")
In order to stick to a reasonable project running time, I’ve opted for h2o as my modelling platform as it offers a number of advantages:
it’s very easy to use and you can estimate several Machine Learning models in no time
it does not require to pre-treat character/factor variables by “binarising” them (this is done “internally”), which further reduces data formatting time
it has a functionality that takes care of the class imbalance highlighted in the Data Exploration phase — I simply set balance_classes = TRUE in the model specification, more on this later on
cross-validation can be enabled without the need for a separate validation frame to be “carved out” of the training set
hyper-parameters fine tuning (a.k.a. grid search) can be implemented alogside a number of strategies that ensure running time is capped without compromising on performance
I’m starting by creating a randomised training and validation set with rsample and save them as train_tbl and test_tbl.
set.seed(seed = 1975) train_test_split <- rsample::initial_split( data = data_final, prop = 0.80 ) train_tbl <- train_test_split %>% rsample::training() test_tbl <- train_test_split %>% rsample::testing()
Then, I start an h2o cluster. I specify the size of the memory cluster to “16G” to help speed things up a bit and turn off the progress bar.
# initialize h2o session and switch off progress barh2o.no_progress() h2o.init(max_mem_size = "16G")
Next, I sort out response and predictor variables sets. For a classification to be performed, I need to ensure that the response variable is a factor (otherwise h2o will carry out a regression). This was sorted out during the data cleansing and formatting phase.
# response variabley <- "subscribed"# predictors set: remove response variablex <- setdiff(names(train_tbl %>% as.h2o()), y)
For this project, I’m estimating a Generalised Linear Model (a.k.a. Elastic Net), a Random Forest (which h2o refers to at Distributed Random Forest) and a Gradient Boosting Machine (or GBM).
To implement a grid search for the tree-based models (DRF and GBM), I need to set up a random grid to search for optimal hyper-parameters for the h2o.grid() function. To do so, I start with defining the search parameters to be passed to the hyper_paramsargument:
sample_rate is used to set the row sampling rate for each tree
col_sample_rate_per_tree defines the column sampling for each tree
max_depth specifies the maximum tree depth
min_rows to fix the minimum number of observations per leaf
mtries(DRF only) indicates the columns to randomly select on each node of the tree
learn_rate(GBM only) specifies the rate at which the model learns when building a model
# DRF hyperparametershyper_params_drf <- list( mtries = seq(2, 5, by = 1), sample_rate = c(0.65, 0.8, 0.95), col_sample_rate_per_tree = c(0.5, 0.9, 1.0), max_depth = seq(1, 30, by = 3), min_rows = c(1, 2, 5, 10) )# GBM hyperparametershyper_params_gbm <- list( learn_rate = c(0.01, 0.1), sample_rate = c(0.65, 0.8, 0.95), col_sample_rate_per_tree = c(0.5, 0.9, 1.0), max_depth = seq(1, 30, by = 3), min_rows = c(1, 2, 5, 10) )
I also set up a second list for the search_criteria argument, which helps to manage the models’ estimation running time:
The strategy argument is set to RandomDiscrete for the search to randomly select a combination from the grid search parameters
Setting stopping_metric to AUC as the error metric for early stopping - the models will stop building new trees when the metric ceases to improve
With stopping_rounds I’m specifying the number of training rounds before early stopping is considered
I’m using stopping_tolerance to set minimal improvement needed for the training process to continue
max_runtime_secs restricts the search time to one hour per model
search_criteria_all <- list( strategy = "RandomDiscrete", stopping_metric = "AUC", stopping_rounds = 10, stopping_tolerance = 0.0001, max_runtime_secs = 60 * 60 )
At last, I can set up the models’ formulations. Note that all models have 2 parameters in common:
the nfolds parameter, which enables cross-validation to be carried out without the need for a validation_frame - if set to 5 for instance, it will perform a 5-fold cross-validation
the balance_classes parameter is set to TRUE to account for the imbalance in the target variable highlighted during the exploratory analysis. When enabled, h2o will either under-sample the majority class or oversample the minority class.
# elastic net model glm_model <- h2o.glm( x = x, y = y, training_frame = train_tbl %>% as.h2o(), balance_classes = TRUE, nfolds = 10, family = "binomial", seed = 1975 )# random forest modeldrf_model_grid <- h2o.grid( algorithm = "randomForest", x = x, y = y, training_frame = train_tbl %>% as.h2o(), balance_classes = TRUE, nfolds = 10, ntrees = 1000, grid_id = "drf_grid", hyper_params = hyper_params_drf, search_criteria = search_criteria_all, seed = 1975 )# gradient boosting machine modelgbm_model_grid <- h2o.grid( algorithm = "gbm", x = x, y = y, training_frame = train_tbl %>% as.h2o(), balance_classes = TRUE, nfolds = 10, ntrees = 1000, grid_id = "gbm_grid", hyper_params = hyper_params_gbm, search_criteria = search_criteria_all, seed = 1975 )
I sort the tree-based model by AUC score and retrieve the lead models from the grid
# Get the DRM grid results, sorted by AUC drf_grid_perf <- h2o.getGrid(grid_id = "drf_grid", sort_by = "AUC", decreasing = TRUE)# Fetch the top DRF model, chosen by validation AUCdrf_model <- h2o.getModel(drf_grid_perf@model_ids[[1]])# Get the GBM grid results, sorted by AUC gbm_grid_perf <- h2o.getGrid(grid_id = "gbm_grid", sort_by = "AUC", decreasing = TRUE)# Fetch the top GBM model, chosen by validation AUCgbm_model <- h2o.getModel(gbm_grid_perf@model_ids[[1]])
There are many libraries (like IML, PDP, VIP, and DALEX to name but the more popular) that help with Machine Learning Interpretability, feature explanation and general performance assessment and they all have gained in popularity in recent years.
There are a number of methodologies to interpret machine learning results (i.e. local interpretable model-agnostic explanations, partial dependence plots, permutation-based variable importance) but in this project, I examine the DALEX package, which focuses on Model-Agnostic Interpretability and provides a convenient way of comparing performance across multiple models with different structures.
One of the key advantages of the model-agnostic approach used by DALEX is that you can compare contributions of traditional “glass-box” models to black-box models on the same scale. However, being permutation-based, one of its main drawbacks is that it does not scale well with a large number of predictor variables and larger datasets.
Currently DALEX does not support some of the more recent ML packages like h2o or xgboost. To make it compatible with such objects, I’ve followed the procedure illustrated by Bradley Boehmke in his brilliant study Model Interpretability with DALEX, from which I’ve drawn lots of inspiration and borrowed some code.
First, the dataset needs to be in a specific format:
# convert feature variables to a data framex_valid <- test_tbl %>% select(-subscribed) %>% as_tibble()# change response variable to a numeric binary vectory_valid <- as.vector(as.numeric(as.character(test_tbl$subscribed)))
Then, I create a predict function returning a vector of numeric values, which extracts the probability of the response for binary classification problems.
# create custom predict functionpred <- function(model, newdata) { results <- as.data.frame(h2o.predict(model, newdata %>% as.h2o())) return(results[[3L]]) }
Now I can convert my machine learning models into DALEK “explainers” with the explain() function, which works as a “container” for the parameters.
# generalised linear model explainerexplainer_glm <- explain( model = glm_model, type = "classification", data = x_valid, y = y_valid, predict_function = pred, label = "h2o_glm" )# random forest model explainerexplainer_drf <- explain( model = drf_model, type = "classification", data = x_valid, y = y_valid, predict_function = pred, label = "h2o_drf" )# gradient boosting machine explainerexplainer_gbm <- explain( model = gbm_model, type = "classification", data = x_valid, y = y_valid, predict_function = pred, label = "h2o_gbm" )
At last, I’m ready to pass the explainer objects to several DALEX functions that will help assess and compare the performance of the different models. Given that performance measures may reflect a different aspect of the predictive performance of a model, it is important to evaluate and compare several metrics when appraising a model and with DALEX you can do just that!
To evaluate and compare my models’ performance, I’ve drawn inspiration from the framework used by Przemyslaw Biecek and Tomasz Burzykowski in their book, Explanatory Model Analysis, which is structured around key questions:
1 — Are the models well fitted?
2 — How do the models compare with one another?
3 — Which variables are important in the models?
4 — How does a single variable affect the average prediction?
To get an initial feel for how well my models fit the data, I can use the self-explanatory model_performance() function, which calculates selected model performance measures.
model_performance(explainer_glm)## Measures for: classification## recall : 0 ## precision: NaN ## f1 : NaN ## accuracy : 0.8914653 ## auc : 0.7500738## ## Residuals:## 0% 10% 20% 30% 40% 50% ## -0.48867133 -0.16735197 -0.09713539 -0.07193152 -0.06273300 -0.05418778 ## 60% 70% 80% 90% 100% ## -0.04661088 -0.03971492 -0.03265955 0.63246516 0.98072521model_performance(explainer_drf)## Measures for: classification## recall : 0.1700224 ## precision: 0.76 ## f1 : 0.2778793 ## accuracy : 0.9040913 ## auc : 0.7993824## ## Residuals:## 0% 10% 20% 30% 40% 50% ## -0.87841486 -0.13473277 -0.07933048 -0.06305297 -0.05556507 -0.04869549 ## 60% 70% 80% 90% 100% ## -0.04172427 -0.03453394 -0.02891645 0.33089059 0.98046626model_performance(explainer_gbm)## Measures for: classification## recall : 0.2192394 ## precision: 0.7340824 ## f1 : 0.33764 ## accuracy : 0.9066408 ## auc : 0.7988382## ## Residuals:## 0% 10% 20% 30% 40% 50% ## -0.83600975 -0.14609749 -0.08115376 -0.06542395 -0.05572322 -0.04789869 ## 60% 70% 80% 90% 100% ## -0.04068165 -0.03371074 -0.02750033 0.29004942 0.98274727
Based on the metrics available for all models ( accuracy and AUC), I can see that elastic net and gradient boosting are performing roughly on par with one another, with random forest not far behind. AUC ranges between .78-.80 whereas accuracy has a slightly narrower range of .89-.90
As shown in the previous paragraph, model_performance() also produces residual quantiles that can be plotted to compare absolute residual values across models.
# compute and assign residuals to an objectresids_glm <- model_performance(explainer_glm)resids_drf <- model_performance(explainer_drf)resids_gbm <- model_performance(explainer_gbm)# compare residuals plotsp1 <- plot(resids_glm, resids_drf, resids_gbm) + theme_minimal() + theme(legend.position = 'bottom', plot.title = element_text(hjust = 0.5)) + labs(y = '')p2 <- plot(resids_glm, resids_drf, resids_gbm, geom = "boxplot") + theme_minimal() + theme(legend.position = 'bottom', plot.title = element_text(hjust = 0.5)) gridExtra::grid.arrange(p2, p1, nrow = 1)
The DRF and GBM models appear to perform on a par with one another, given the median absolute residuals. Looking at the residuals distribution on the right-hand side, you can see that the median residuals are the lowest for these two models, with the GLM seeing a higher number of tail residuals. This is also mirrored by the boxplots on the left-hand side, where the tree-based models both achieve the lowest median absolute residual value.
The Receiver Operating Characteristic (ROC) curve is a graphical method that allows to visualise a classification model performance against a random guess, which is represented by the striped line on the graph. The curve plots the true positive rate (TPR) on the y-axis against the false positive rate (FPR) on the x-axis.
eva_glm <- DALEX::model_performance(explainer_glm)eva_dfr <- DALEX::model_performance(explainer_drf)eva_gbm <- DALEX::model_performance(explainer_gbm)plot(eva_glm, eva_dfr, eva_gbm, geom = "roc") + ggtitle("ROC Curves - All Models", "AUC_glm = 0.750 AUC_drf = 0.799 AUC_gbm = 0.798") + theme_minimal() + theme(plot.title = element_text(hjust = 0.5))
The insight from a ROC curve is two-fold:
Direct read: All models are performing much better than a random guess
Compared read: the AUC (Area Under the Curve) summarises the ROC curve and can be used to directly compare models performance — the perfect classifier would have AUC = 1.
All models performs much better that random guessing and achieves a AUC of .75-.80, with the DRF achieving the highest score of 0.799.
Each ML algorithm has its own way to assess the importance of each variable: linear models, for instance, refer to their coefficients, whereas tree-based models look at impurity, which makes it difficult to compare variable importance across models.
DALEX calculates variable importance measures via permutation, which is model agnostics and allows for direct comparison between models of different structure. However, when variable importance scores are based on permutations, we should remember that calculations slow down when the number of features increases.
Once again, I’m passing the “explainer” for each single model to the feature_importance() function and setting n_sample to 8000 to use practically all available observations. Although not exorbitant, the total execution time was nearly 30 minute but this is based on a relatively small dataset and the number of variables. Don’t forget that computation speed can be increased by reducing n_sample, which is especially important for larger datasets.
# measure execution timetictoc::tic()# compute permutation-based variable importancevip_glm <- feature_importance(explainer_glm, n_sample = 8000, loss_function = loss_root_mean_square) vip_drf <- feature_importance(explainer_drf, n_sample = 8000, loss_function = loss_root_mean_square)vip_gbm <- feature_importance(explainer_gbm, n_sample = 8000, loss_function = loss_root_mean_square)# show total execution timetictoc::toc()## 1803.65 sec elapsed
Now I only have to pass the vip objects to a plotting function: as suggested by the auto-generated x-axis label ( Drop-out loss), the main intuition behind how variable importance is calculated lies in how much the model fit would decrease if the contribution of a selected explanatory variable was removed. The larger the segment, the larger the loss when that variable is dropped from the model.
# plotting top 10 feature only for clarity of readingplot(vip_glm, vip_drf, vip_gbm, max_vars = 10) + ggtitle("Permutation variable importance", "Average variable importance based on 8,000 permutations") + theme_minimal() + theme(plot.title = element_text(hjust = 0.5))
I like this plot as it brings together a wealth of information.
First of all, you can notice that, although with slightly different relative weights, the top 5 features are common to each model, with nr_employed ( employed in the economy) being the single most important predictor in all of them. This consistency is reassuring as it tells us that all models are picking up the same structure and interactions in the data, and gives us the assurance that these features have strong predictive power.
You can also notice the distinct starting point for the x-axis left edge, which reflects the difference in the RMSE loss between the three models: in this case the elastic net model has the highest RMSE, suggesting the higher number of tail residuals seen earlier in the residual diagnostics is probably penalising the RMSE score.
After we have identified the relative predictive power of each variable, we may want to investigate how their relationship with the predicted response differ across all three models. Partial Dependence (PD) plots, sometimes also referred to as PD profiles, offer a great way to inspect how each model is responding to a particular predictor.
We can start with having a look at the single most important feature, nr_employed:
# compute PDP for a given variablepdp_glm <- model_profile(explainer_glm, variable = "nr_employed", type = "partial")pdp_drf <- model_profile(explainer_drf, variable = "nr_employed", type = "partial")pdp_gbm <- model_profile(explainer_gbm, variable = "nr_employed", type = "partial")plot(pdp_glm$agr_profiles, pdp_drf$agr_profiles, pdp_gbm$agr_profiles) + ggtitle("Contrastive Partial Dependence Profiles", "") + theme_minimal() + theme(plot.title = element_text(hjust = 0.5))
Although with different average prediction weights, all three models found that bank customers are more likely to sign up to a term deposit when the level of employed in the economy is up to 5.099m (nInf_5099.1). Both elastic net and random forest have found the exact same hierarchy of predictive power among the 3 different levels of nr_employed (less pronounced for the random forest) that we observed in the correlationfunnel analysis, with GBM being the one slightly out of kilter.
Let’s now take a look at age, a predictor that, if you recall from the EDA, was NOT expected to have an impact on the target variable:
One thing we notice is that the range of variation in the average prediction (x-axis) is relatively shallow across the age spectrum (y-axis), confirming the finding from the exploratory analysis that this variable would have a low predictive power. Also, both GBM and random forest are using age in a non-linear way, whereas the elastic net model is unable to capture this non-linear dynamic.
Partial Dependence plots could also work as a diagnostic tool: looking at poutcome (outcome of the previous marketing campaign) reveals that GBM and random forest correctly picked up on a higher probability of signing up when the outcome of a previous campaign was success (scs).
However, the elastic net model fails to do the same, which could represent a serious flaw as success in a previous campaign had a very strong positive correlation with the target variable.
I’m going to finish with the month feature as it offers a great example of one of those cases where you may want to override the model’s outcome with industry knowledge and some common sense. Specifically, the GBM model seems to suggest that March, October and December are periods associated with much better odds of success.
Based on my previous analysis experience of similar financial products, I would not advise a banking organisation to ramp up their direct marketing activity around the weeks in the run to Christmas as this is a period of the year where the consumers’ focus shifts away from this type of purchases.
All in all random forest is my final model of choice: it appears the more balanced of the three and does not display some of the “oddities” seen with variables like month and poutcome.
I can now further refine my model and reduce its complexity by combining findings from the Exploratory analysis, insight from models’ assessment and a number of industry-specific/common sense considerations.
In particular, my final model:
Excludes a number of features (age, housing, loan, campaign, cons_price_idx) that have low predictive power
Removes previous, which shows little difference between its 2 levels in the PD plot - it’s also moderately correlated with pdays, suggesting that they may be capturing the same behaviour
Also drops emp_var_rate because of its strong correlation with nr_employed and also because conceptually they are controlling for a very similar economic behaviour
# response variable remains unalteredy <- "subscribed"# predictors set: remove response variable and 7 predictorsx_final <- setdiff(names(train_tbl %>% select(-c(age, housing, loan, campaign, previous, cons_price_idx, emp_var_rate)) %>% as.h2o()), y)
For the final model, I’m using the same specification as to the original random forest
# random forest modeldrf_final <- h2o.grid( algorithm = "randomForest", x = x_final, y = y, training_frame = train_tbl %>% as.h2o(), balance_classes = TRUE, nfolds = 10, ntrees = 1000, grid_id = "drf_grid_final", hyper_params = hyper_params_drf, search_criteria = search_criteria_all, seed = 1975 )
Once again, we sort the model by AUC score and retrieve the lead model
# Get the grid results, sorted by AUC drf_grid_perf_final <- h2o.getGrid(grid_id = "drf_grid_final", sort_by = "AUC", decreasing = TRUE)# Fetch the top DRF model, chosen by validation AUCdrf_final <- h2o.getModel(drf_grid_perf_final@model_ids[[1]])
For brevity, I am visualising the variable importance plot with the vip() function from the namesake package, which returns the ranked contribution of each variable.
vip::vip(drf_final, num_features = 12) + ggtitle("Variable Importance", "") + theme_minimal() + theme(plot.title = element_text(hjust = 0.5))
Removing emp_var_rate has allowed education to come into the top 10 features. Understandably, the variables hierarchy and relative predictive power has adjusted and changed slightly but it’s reassuring to see that the other 9 variables were in the previous model’s top 10.
Lastly, I’m comparing the model’s performance with the original random forest model.
drf_final %>% h2o.performance(newdata = test_tbl %>% as.h2o()) %>% h2o.auc()## [1] 0.7926509drf_model %>% h2o.performance(newdata = test_tbl %>% as.h2o()) %>% h2o.auc()## [1] 0.7993973
The AUC has only changed by a fraction of a percent, telling me that the model has maintained its predictive power.
Being already familiar with odds ratios in the context of a logistic regression, I set out to understand whether the same intuition could be extended to black-box classification models. During my research one very interesting post on Cross Validated stood out for drawing a parallel between odds ratio from decision tree and random forest.
Basically, this tells us that Partial Dependence plots can be used in a similar way to odds ratios to define what characteristics of a customer profile influence his/her propensity to performing a certain type of behaviour.
For example, features like job, month and contact would provide context around who, when and how to target:
Looking at job will tell us that a customer in an admin role is roughly 25% more likely to subscribe that a self employed.
Getting in touch with a prospective customer in the month of October will more than double the chance of a positive outcome than in May.
contacting your customer on their mobile increases the chances of subscription by nearly a quarter compared to a telephone call.
NOTE THAT Partial Dependence Plots for all final model’s predictors can be found on my webpage: on my webpage: Propensity Modelling — Estimate Several Models and Compare Their Performance Using a Model-agnostic Methodology.
Armed with such insight, one can help to shape overall marketing and communication plans to focus on customers more likely to subscribe to a term deposit.
However, these are based on model-level explainers, which reflect an overall, aggregated view. If you’re interested to understand how a model yields a prediction for a single observation (i.e. what factors influence the likelihood to engage at single customer level), you can resort to the Local Interpretable Model-agnostic Explanations (LIME) method that exploits the concept of a “local model”. I will be exploring the LIME methodology in a future post.
For the analysis part of this project, I opted for h2o as my modelling platform. h2o is not only very easy to use but also has a number of built-in functionalities that help speeding up data preparation: it takes care of class imbalance with no need for pre-modelling resampling, automatically __“binarises“ character/factor__ variables, and implements cross-validation without the need for a separate validation frame to be “carved out" of the training set.
After setting up a random grid to search for best hyper-parameters, I’ve estimated the number of models ( a logistic regression, a random forest and a gradient boosting machines) and used the DALEX library to assess and compare their performance through an array of metrics. This library employs a model-agnostic approach that enables to compare traditional “glass-box” models and “black-box” models on the same scale.
My final model of choice is the random forest, which I further refined by combining findings from the exploratory analysis, insight gathered from the models’ evaluation and a number of industry-specific/common sense considerations. This ensured a reduced model complexity without compromising on predictive power.
Now that I have my final model, the last piece of the puzzle is the final “So what?” question that puts all into perspective. The estimate for the probability of a customer to sign up for a term deposit can be used to create a number of optimised scenarios, ranging from minimising your marketing expenditure, maximising your overall acquisition targets, to driving a certain number of cross-sell opportunities.
Before I can do that, there are a couple of housekeeping tasks needed to “set up the work scene” and a couple of important concepts to introduce:
the threshold and the F1 score
precision and recall
The question the model is trying to answer is “ Has this customer signed up for a term deposit following a direct marketing campaign? “ and the cut-off (a.k.a. the threshold) is the value that divides the predictions into Yes and No.
To illustrate the point, I first calculate some predictions by passing the test_tbl data set to the h2o.performance function.
perf_drf_final <- h2o.performance(drf_final, newdata = test_tbl %>% as.h2o()) perf_drf_final@metrics$max_criteria_and_metric_scores## Maximum Metrics: Maximum metrics at their respective thresholds## metric threshold value idx## 1 max f1 0.189521 0.508408 216## 2 max f2 0.108236 0.560213 263## 3 max f0point5 0.342855 0.507884 143## 4 max accuracy 0.483760 0.903848 87## 5 max precision 0.770798 0.854167 22## 6 max recall 0.006315 1.000000 399## 7 max specificity 0.930294 0.999864 0## 8 max absolute_mcc 0.189521 0.444547 216## 9 max min_per_class_accuracy 0.071639 0.721231 300## 10 max mean_per_class_accuracy 0.108236 0.755047 263## 11 max tns 0.930294 7342.000000 0## 12 max fns 0.930294 894.000000 0## 13 max fps 0.006315 7343.000000 399## 14 max tps 0.006315 894.000000 399## 15 max tnr 0.930294 0.999864 0## 16 max fnr 0.930294 1.000000 0## 17 max fpr 0.006315 1.000000 399## 18 max tpr 0.006315 1.000000 399
Like many other machine learning modelling platforms, h2o uses the threshold value associated with the maximum F1 score, which is nothing but a weighted average between precision and recall. In this case, the threshold @ Max F1 is 0.190.
Now, I use the h2o.predict function to make predictions using the test set. The prediction output comes with three columns: the actual model predictions (predict), and the probabilities associated with that prediction (p0, and p1, corresponding to No and Yes respectively). As you can see, the p1 probability associated with the current cut-off is around 0.0646.
drf_predict <- h2o.predict(drf_final, newdata = test_tbl %>% as.h2o())# I converte to a tibble for ease of useas_tibble(drf_predict) %>% arrange(p0) %>% slice(3088:3093) %>% kable()predict p0 p1 1 0.9352865 0.0647135 1 0.9352865 0.0647135 1 0.9352865 0.0647135 0 0.9354453 0.0645547 0 0.9354453 0.0645547 0 0.9354453 0.0645547
However, the F1 score is only one way to identify the cut-off. Depending on our goal, we could also decide to use a threshold that, for instance, maximises precision or recall.
In a commercial setting, the pre-selected threshold @ Max F1 may not necessarily be the optimal choice: enter Precision and Recall!
Precision shows how sensitive models are to False Positives (i.e. predicting a customer is subscribing when he-she is actually NOT) whereas Recall looks at how sensitive models are to False Negatives (i.e. forecasting that a customer is NOT subscribing whilst he-she is in fact going to do so).
These metrics are very relevant in a business context because organisations are particularly interested in accurately predicting which customers are truly likely to subscribe (high precision) so that they can target them with advertising strategies and other incentives. At the same time they want to minimise efforts towards customers incorrectly classified as subscribing (high recall) who are instead unlikely to sign up.
However, as you can see from the chart below, when precision gets higher, recall gets lower and vice versa. This is often referred to as the Precision-Recall tradeoff.
To fully comprehend this dynamic and its implications, let’s start with taking a look at the cut-off zero and cut-off one points and then see what happens when you start moving the threshold between the two positions:
At threshold zero ( lowest precision, highest recall) the model classifies every customer as subscribed = Yes. In such a scenario, you would contact every single customer with direct marketing activity but waste precious resources by also including those less likely to subscribe. Clearly this is not an optimal strategy as you’d incur in a higher overall acquisition cost.
Conversely, at threshold one ( highest precision, lowest recall) the model tells you that nobody is likely to subscribe so you should contact no one. This would save you tons of money in marketing cost but you’d be missing out on the additional revenue from those customers who would’ve subscribed, had they been notified about the term deposit through direct marketing. Once again, not an optimal strategy.
When moving to a higher threshold the model becomes more “choosy” on who it classifies as subscribed = Yes. As a consequence, you become more conservative on who to contact ( higher precision) and reduce your acquisition cost, but at the same time you increase your chance of not reaching prospective subscribes ( lower recall), missing out on potential revenue.
The key question here is where do you stop? Is there a “sweet spot” and if so, how do you find it? Well, that will depend entirely on the goal you want to achieve. In the next section, I’ll be running a mini-optimisation with the goal to maximise profit.
For this mini-optimisation I’m implementing a simple profit maximisation based on generic costs connected to acquiring a new customer and benefits derived from said acquisition. This can be evolved to include more complex scenarios but it would be outside the scope of this exercise.
To understand which cut-off value is optimal to use we need to simulate the cost-benefit associated with each threshold point. This is a concept derived from the Expected Value Framework as seen on Data Science for Business
To do so I need 2 things:
Expected Rates for each threshold — These can be retrieved from the confusion matrix
Cost/Benefit for each customer — I will need to simulate these based on assumptions
Expected rates can be conveniently retrieved for all cut-off points using h2o.metric.
# Get expected rates by cutoffexpected_rates <- h2o.metric(perf_drf_final) %>% as.tibble() %>% select(threshold, tpr, fpr, fnr, tnr)
The cost-benefit matrix is a business assessment of the cost and benefit for each of four potential outcomes. To create such a matrix I will have to make a few assumptions about the expenses and advantages that an organisation should consider when carrying out an advertising-led procurement drive.
Let’s assume that the cost of selling term deposits is of £30 per customer. This would include the likes of performing the direct marketing activity (training the call centre reps, setting time aside for active calls, etc.) and incentives such as offering discounts on another financial product or onboarding onto membership schemes offering benefits and perks. A banking organisation will incur in this type of cost in two cases: when they correctly predict that a customer will subscribe ( true positive, TP), and when they incorrectly predict that a customer will subscribe ( false positive, FP).
Let’s also assume that the revenue of selling a term deposits to an existing customer is of £80 per customer. The organisation will guarantee this revenue stream when the model predicts that a customer will subscribe and they actually do ( true positive, TP).
Finally, there’s the true negative (TN) scenario where we correctly predict that a customer won’t subscribe. In this case, we won’t spend any money but won’t earn any revenue.
Here’s a quick recap of the cost scenarios:
True Positive (TP) — predict will subscribe, and they actually do: COST: -£30; REV £80
False Positive (FP) — predict will subscribe, when they actually wouldn’t: COST: -£30; REV £0
True Negative (TN) — predict won’t subscribe, and they actually don’t: COST: £0; REV £0
False Negative (FN) — predict won’t subscribe, but they actually do: COST: £0; REV £0
I create a function to calculate the expected cost using the probability of a positive case (p1) and the cost/benefit associated with a true positive (cb_tp) and a false positive (cb_fp). No need to include the true negative or false negative here as they’re both zero.
I’m also including the expected_rates data frame created previously with the expected rates for each threshold (400 thresholds, ranging from 0 to 1).
# Function to calculate expected profitexpected_profit_func <- function(p1, cb_tp, cb_fp) { tibble( p1 = p1, cb_tp = cb_tp, cb_fp = cb_fp ) %>% # add expected rates mutate(expected_rates = list(expected_rates)) %>% unnest() %>% # calculate the expected profit mutate( expected_profit = p1 * (tpr * cb_tp) + (1 - p1) * (fpr * cb_fp) ) %>% select(threshold, expected_profit)}
Now to understand how a multi customer dynamic would work, I’m creating a hypothetical 10 customer group to test my function on. This is a simplified view in that I’m applying the same cost and revenue structure to all customers but the cost/benefit framework can be tailored to the individual customer to reflect their separate product and service level set up and the process can be easily adapted to optimise towards different KPIs (like net profit, CLV, number of subscriptions, etc.)
# Ten Hypothetical Customers ten_cust <- tribble( ~"cust", ~"p1", ~"cb_tp", ~"cb_fp", 'ID1001', 0.1, 80 - 30, -30, 'ID1002', 0.2, 80 - 30, -30, 'ID1003', 0.3, 80 - 30, -30, 'ID1004', 0.4, 80 - 30, -30, 'ID1005', 0.5, 80 - 30, -30, 'ID1006', 0.6, 80 - 30, -30, 'ID1007', 0.7, 80 - 30, -30, 'ID1008', 0.8, 80 - 30, -30, 'ID1009', 0.9, 80 - 30, -30, 'ID1010', 1.0, 80 - 30, -30)
I use purrr to map the expected_profit_func() to each customer, returning a data frame of expected cost per customer by threshold value. This operation creates a nester tibble, which I have to unnest() to expand the data frame to one level.
# calculate expected cost for each at each thresholdexpected_profit_ten_cust <- ten_cust %>% # pmap to map expected_profit_func() to each item mutate(expected_profit = pmap(.l = list(p1, cb_tp, cb_fp), .f = expected_profit_func)) %>% unnest() %>% select(cust, p1, threshold, expected_profit)
Then, I can visualize the expected cost curves for each customer.
# Visualising Expected Cost expected_profit_ten_cust %>% ggplot(aes(threshold, expected_profit, colour = factor(cust)), group = cust) + geom_line(size = 1) + theme_minimal() + tidyquant::scale_color_tq() + labs(title = "Expected Profit Curves", colour = "Customer No." ) + theme(plot.title = element_text(hjust = 0.5))
Finally, I can aggregate the expected cost, visualise the final curve and highlight the optimal threshold.
# Aggregate expected cost by threshold total_expected_profit_ten_cust <- expected_profit_ten_cust %>% group_by(threshold) %>% summarise(expected_profit_total = sum(expected_profit)) # Get maximum optimal threshold max_expected_profit <- total_expected_profit_ten_cust %>% filter(expected_profit_total == max(expected_profit_total))# Visualize the total expected profit curvetotal_expected_profit_ten_cust %>% ggplot(aes(threshold, expected_profit_total)) + geom_line(size = 1) + geom_vline(xintercept = max_expected_profit$threshold) + theme_minimal() + labs(title = "Expected Profit Curve - Total Expected Profit", caption = paste0('threshold @ max = ', max_expected_profit$threshold %>% round(3))) + theme(plot.title = element_text(hjust = 0.5))
This has some important business implications. Based on our hypothetical 10-customer group, choosing the optimised threshold of 0.092 would yield a total profit of nearly £164 compared to the nearly £147 associated with the automatically selected cut-off of 0.190.
This would result in an additional expected profit of nearly £1.7 per customer. Assuming that we have a customer base of approximately 500,000, switching to the optimised model could generate an additional expected profit of £850k!
total_expected_profit_ten_cust %>% slice(184, 121) %>% round(3) %>% mutate(diff = expected_profit_total - lag(expected_profit_total)) %>% kable()threshold expected_profit_total diff 0.190 146.821 NA 0.092 163.753 16.932
It is easy to see that, depending on the size of your business, the magnitude of potential profit increase could be a significant.
In this project, I’ve used a publicly available dataset to estimate the likelihood of a bank’s existing customers to purchase a financial product following a direct marketing campaign.
Following a thorough exploration and cleansing of the data, I estimate several models and compare their performance and fit to the data using the DALEX library, which focuses on Model-Agnostic Interpretability. One of its key advantages is the ability to compare contributions of traditional “glass-box” models as well as black-box models on the same scale. However, being permutation-based, one of its main drawbacks is that it does not scale well to large number of predictors and larger datasets.
Lastly, I take my final model and implemented a multi-customer profit optimization that reveals a potential additional expected profit of nearly £1.7 per customer (or £850k if you had a 500,000 customer base). Furthermore, I discuss key concepts like the threshold and F1 score and the precision-recall tradeoff and explain why it’s highly important to decide which cutoff to adopt.
After exploring and cleansing the data, fitting and comparing multiple models and choosing the best one, sticking with the default threshold @ Max F1 would be stopping short of the ultimate “so what?” that puts all that hard work into prospective.
One final thing: don’t forget to shut-down the h2o instance when you’re done!
h2o.shutdown(prompt = FALSE)## [1] TRUE
The full R code and all relevant files can be found on my GitHub profile @ Propensity Modelling
For the original paper that used the data set see: A Data-Driven Approach to Predict the Success of Bank Telemarketing. Decision Support Systems, S. Moro, P. Cortez and P. Rita.
To Speed Up Exploratory Data Analysis see: correlationfunnel Package Vignette
For a technically rigorous but applied take on Machine Learning Interpretability see Bradley Boehmke’s Model Interpretability with DALEX
For a in-depth look at tools and techniques to examine fully-trained machine-learning models and compare their performance in a model-agnostic framework see: Explanatory Model Analysis, P. Biecek, T. Burzykowski
For an advanced tutorial on sales forecasting and product backorders optimisation see Matt Dancho’s Predictive Sales Analytics: Use Machine Learning to Predict and Optimize Product Backorders
For the Expected Value Framework see: Data Science for Business
Originally published at https://diegousai.io on May 1, 2020.
|
[
{
"code": null,
"e": 501,
"s": 171,
"text": "In this day and age, a business that leverages data to understand the drivers of customers’ behaviour has a true competitive advantage. Organisations can dramatically improve their performance in the market by analysing customer level data in an effective way and focus their efforts towards those that are more likely to engage."
},
{
"code": null,
"e": 1297,
"s": 501,
"text": "One trialled and tested approach to tease this type of insight out of data is Propensity Modelling, which combines information such as a customers’ demographics (age, race, religion, gender, family size, ethnicity, income, education level), psycho-graphic (social class, lifestyle and personality characteristics), engagement (emails opened, emails clicked, searches on a mobile app, webpage dwell time, etc.), user experience (customer service phone and email wait times, number of refunds, average shipping times), and user behaviour (purchase value on different time-scales, number of days since most recent purchase, the time between offer and conversion, etc.) to estimate the likelihood of a certain customer profile to perform a certain type of behaviour (e.g. the purchase of a product)."
},
{
"code": null,
"e": 1599,
"s": 1297,
"text": "Once you understand the probability of a certain customer to interact with a brand, buy a product or sign up for a service, you can use this information to create scenarios, be it minimising marketing expenditure, maximising acquisition targets, and optimise email send frequency or depth of discount."
},
{
"code": null,
"e": 1930,
"s": 1599,
"text": "In this project, I’m analysing the results of a bank direct marketing campaign to sell term a deposit its existing clients in order to identify what type of characteristics make a customer more likely to respond. The marketing campaigns were based on phone calls and more than one contact to the same person was required at times."
},
{
"code": null,
"e": 2055,
"s": 1930,
"text": "First, I am going to carry out extensive data exploration and use the results and insights to prepare the data for analysis."
},
{
"code": null,
"e": 2260,
"s": 2055,
"text": "Then, I’m estimating the number of models and assess their performance and fit to the data using a model-agnostic methodology that enables to compare traditional “glass-box” models and “black-box” models."
},
{
"code": null,
"e": 2421,
"s": 2260,
"text": "Last, I’ll fit one final model that combines findings from the exploratory analysis and insight from models’ selection and use it to run a revenue optimisation."
},
{
"code": null,
"e": 2600,
"s": 2421,
"text": "library(tidyverse)library(data.table)library(skimr)library(correlationfunnel)library(GGally)library(ggmosaic)library(knitr)library(h2o)library(DALEX)library(knitr)library(tictoc)"
},
{
"code": null,
"e": 2957,
"s": 2600,
"text": "The Data is the Portuguese Bank Marketing set from the UCI Machine Learning Repository and describes the direct marketing campaigns carried out by a Portuguese banking institution aimed at selling term deposits/certificate of deposits to their customers. The marketing campaigns were based on phone calls to potential buyers from May 2008 to November 2010."
},
{
"code": null,
"e": 3409,
"s": 2957,
"text": "The data I’m using (bank-direct-marketing.csv) is a modified version of the bank-additional-full.csv and contains 41,188 examples with 21 different variables (10 continuous, 10 categorical plus the target variable). In particular, the target subscribed is a binary response variable indicating whether the client subscribed (‘Yes’ or numeric value 1) to a term deposit or not (‘No’ or numeric value 0), which make this a binary classification problem."
},
{
"code": null,
"e": 3682,
"s": 3409,
"text": "The data required some manipulation to get into a usable format, details of which can be found on my webpage: Propensity Modelling — Data Preparation and Exploratory Data Analysis. Here I simply load up the pre-cleansed data I am hosting on my GitHub repo for this project"
},
{
"code": null,
"e": 3813,
"s": 3682,
"text": "data_clean <- readRDS(file = \"https://raw.githubusercontent.com/DiegoUsaiUK/Propensity_Modelling/master/01_data/data_clean.rds\")"
},
{
"code": null,
"e": 4268,
"s": 3813,
"text": "Although an integral part of any Data Science project and crucial to the full success of the analysis, Exploratory Data Analysis (EDA) can be an incredibly labour intensive and time consuming process. Recent years have seen a proliferation of approaches and libraries aimed at speeding up the process and in this project I’m going to sample one of the “new kids on the block” ( the correlationfunnel ) and combine its results with a more traditional EDA."
},
{
"code": null,
"e": 4528,
"s": 4268,
"text": "With 3 simple steps correlationfunnel can produce a graph that arranges predictors top to bottom in descending order of absolute correlation with the target variable. Features at the top of the funnel are expected to have stronger predictive power in a model."
},
{
"code": null,
"e": 4727,
"s": 4528,
"text": "This approach offers a quick way to identify a hierarchy of expected predictive power for all variables and gives an early indication of which predictors should feature strongly/weakly in any model."
},
{
"code": null,
"e": 5104,
"s": 4727,
"text": "data_clean %>% binarize(n_bins = 4, # bin number for converting features thresh_infreq = 0.01 # thresh. for assign categ. # features into \"Other\" ) %>% # correlate target variable to features correlate(target = subscribed__1) %>% # correlation funnel visualisation plot_correlation_funnel()"
},
{
"code": null,
"e": 5277,
"s": 5104,
"text": "Zooming in on the top 5 features we can see that certain characteristics have a greater correlation with the target variable (subscribing to the term deposit product) when:"
},
{
"code": null,
"e": 5357,
"s": 5277,
"text": "The duration of the last phone contact with the client is 319 seconds or longer"
},
{
"code": null,
"e": 5445,
"s": 5357,
"text": "The number of days that passed by after the client was last contacted is greater than 6"
},
{
"code": null,
"e": 5504,
"s": 5445,
"text": "The outcome of the previous marketing campaign was success"
},
{
"code": null,
"e": 5556,
"s": 5504,
"text": "The number of employed is 5,099 thousands or higher"
},
{
"code": null,
"e": 5613,
"s": 5556,
"text": "The value of the euribor 3 month rate is 1.344 or higher"
},
{
"code": null,
"e": 5912,
"s": 5613,
"text": "Conversely, variables at the bottom of the funnel, such as day_of_week, housing, and loan. show very little variation compared to the target variable (i.e.: they are very close to the zero correlation point to the response). For that reason, I’m not expecting these features to impact the response."
},
{
"code": null,
"e": 6357,
"s": 5912,
"text": "Guided by the results of this visual correlation analysis, I will continue to explore the relationship between the target and each of the predictors in the next section. For this, I am going to enlist the help of the brilliant GGally library to visualise a modified version of the correlation matrix with Ggpairs, and plot mosaic charts with the ggmosaic package, a great way to examine the relationship among two or more categorical variables."
},
{
"code": null,
"e": 6504,
"s": 6357,
"text": "First things first, the target variable: subscribed shows a strong class imbalance, with nearly 89% in the No category to 11% in the Yes category."
},
{
"code": null,
"e": 6783,
"s": 6504,
"text": "I am going to address class imbalance during the modelling phase by enabling re-sampling, in h2o. This will rebalance the dataset by “shrinking” the prevalent class (“No” or 0) and ensure that the model adequately detects what variables are driving the ‘yes’ and ‘no’ responses."
},
{
"code": null,
"e": 6835,
"s": 6783,
"text": "Let’s continue with some of the numerical features:"
},
{
"code": null,
"e": 7178,
"s": 6835,
"text": "Although the correlation funnel analysis revealed that duration has the strongest expected predictive power, it is unknown before a call (it’s obviously known afterwards) and offers very little actionable insight or predictive value. Therefore, it should be discarded from any realistic predictive model and will not be used in this analysis."
},
{
"code": null,
"e": 7364,
"s": 7178,
"text": "age ’s density plots have very similar variance compared to the target variable and are centred around the same area. For these reasons, it should not have a great impact on subscribed."
},
{
"code": null,
"e": 7651,
"s": 7364,
"text": "Despite continuous in nature, pdays and previous are in fact categorical features and are also all strongly right skewed. For these reasons, they will need to be discretised into groups. Both variables are also moderately correlated, suggesting that they may capture the same behaviour."
},
{
"code": null,
"e": 7714,
"s": 7651,
"text": "Next, I visualise the bank client data with the mosaic charts:"
},
{
"code": null,
"e": 8098,
"s": 7714,
"text": "In line with the correlationfunnel findings, job, education, marital and default all show a good level of variation compared to the target variable, indicating that they would impact the response. In contrast, housing and loan sat at the very bottom of the funnel and are expected to have little influence on the target, given the small variation when split by “subscribed” response."
},
{
"code": null,
"e": 8477,
"s": 8098,
"text": "default has only 3 observations in the ‘yes’ level, which will be rolled into the least frequent level as they’re not enough to make a proper inference. Level ‘unknown’ of the housing and loan variables have a small number of observations and will be rolled into the second smallest category. Lastly, job and education would also benefit from grouping up of least common levels."
},
{
"code": null,
"e": 8521,
"s": 8477,
"text": "Moving on to the other campaign attributes:"
},
{
"code": null,
"e": 8797,
"s": 8521,
"text": "Although continuous in principal, campaign is more categorical in nature and strongly right skewed, and will need to be discretised into groups. However, we have learned from the earlier correlation analysis that is not expected be a strong drivers of variation in any model."
},
{
"code": null,
"e": 9186,
"s": 8797,
"text": "On the other hand, poutcome is one of the attributes expected to be have a strong predictive power. The uneven distribution of levels would suggest to roll the least common occurring level (success or scs) into another category. However, contacting a client who previously purchased a term deposit is one of the catacteristics with highest predictive power and needs to be left ungrouped."
},
{
"code": null,
"e": 9233,
"s": 9186,
"text": "Then, I’m looking at last contact information:"
},
{
"code": null,
"e": 9421,
"s": 9233,
"text": "contact and month should impact the response variable as they both have a good level of variation compared to the target. month would also benefit from grouping up of least common levels."
},
{
"code": null,
"e": 9538,
"s": 9421,
"text": "In contrast, day_of_week does not appear to impact the response as there is not enough variation between the levels."
},
{
"code": null,
"e": 9594,
"s": 9538,
"text": "Last but not least, the social and economic attributes:"
},
{
"code": null,
"e": 9884,
"s": 9594,
"text": "All social and economic attributes show a good level of variation compared to the target variable, which suggests that they should all impact the response. They all display a high degree of multi-modality and do not have an even spread through the density plot, and will need to be binned."
},
{
"code": null,
"e": 10152,
"s": 9884,
"text": "It is also worth noting that, with the exception of consumer confidence index, all other social and economic attributes are strongly correlated to each other, indicating that only one could be included in the model as they are all “picking up” similar economic trend."
},
{
"code": null,
"e": 10271,
"s": 10152,
"text": "Correlation analysis with correlationfunnel helped identify a hierarchy of expected predictive power for all variables"
},
{
"code": null,
"e": 10416,
"s": 10271,
"text": "duration has strongest correlation with target variable whereas some of the bank client data like housing and loan shows the weakest correlation"
},
{
"code": null,
"e": 10628,
"s": 10416,
"text": "However, duration will NOT be used in the analysis as it is unknown before a call. As such it offers very little actionable insight or predictive value and should be discarded from any realistic predictive model"
},
{
"code": null,
"e": 10790,
"s": 10628,
"text": "The target variable subscribed shows strong class imbalance, with nearly 89% of No churn, which will need to be addressed before the modelling analysis can begin"
},
{
"code": null,
"e": 10860,
"s": 10790,
"text": "Most predictors would benefit from grouping up of least common levels"
},
{
"code": null,
"e": 11062,
"s": 10860,
"text": "Further feature exploration revealed the most social and economic context attributes are strongly correlated to each other, suggesting that only a selection of them could be considered in a final model"
},
{
"code": null,
"e": 11550,
"s": 11062,
"text": "Following up on the findings from the Exploratory Data Analysis, I’ve discretised categorical and continuous predictors by combining least common levels into “other’ category, set all variables but age as unordered factors ( h2o does not support ordered categorical variables) and shorted level names of some categorical variables to ease visualisations. You can find all the details and the full code on my webpage: Propensity Modelling - Data Preparation and Exploratory Data Analysis."
},
{
"code": null,
"e": 11616,
"s": 11550,
"text": "Here I simply load up the final dataset hosted on my GitHub repo:"
},
{
"code": null,
"e": 11747,
"s": 11616,
"text": "data_final <- readRDS(file = \"https://raw.githubusercontent.com/DiegoUsaiUK/Propensity_Modelling/master/01_data/data_final.rds\")"
},
{
"code": null,
"e": 11884,
"s": 11747,
"text": "In order to stick to a reasonable project running time, I’ve opted for h2o as my modelling platform as it offers a number of advantages:"
},
{
"code": null,
"e": 11970,
"s": 11884,
"text": "it’s very easy to use and you can estimate several Machine Learning models in no time"
},
{
"code": null,
"e": 12123,
"s": 11970,
"text": "it does not require to pre-treat character/factor variables by “binarising” them (this is done “internally”), which further reduces data formatting time"
},
{
"code": null,
"e": 12315,
"s": 12123,
"text": "it has a functionality that takes care of the class imbalance highlighted in the Data Exploration phase — I simply set balance_classes = TRUE in the model specification, more on this later on"
},
{
"code": null,
"e": 12435,
"s": 12315,
"text": "cross-validation can be enabled without the need for a separate validation frame to be “carved out” of the training set"
},
{
"code": null,
"e": 12607,
"s": 12435,
"text": "hyper-parameters fine tuning (a.k.a. grid search) can be implemented alogside a number of strategies that ensure running time is capped without compromising on performance"
},
{
"code": null,
"e": 12727,
"s": 12607,
"text": "I’m starting by creating a randomised training and validation set with rsample and save them as train_tbl and test_tbl."
},
{
"code": null,
"e": 12949,
"s": 12727,
"text": "set.seed(seed = 1975) train_test_split <- rsample::initial_split( data = data_final, prop = 0.80 ) train_tbl <- train_test_split %>% rsample::training() test_tbl <- train_test_split %>% rsample::testing()"
},
{
"code": null,
"e": 13090,
"s": 12949,
"text": "Then, I start an h2o cluster. I specify the size of the memory cluster to “16G” to help speed things up a bit and turn off the progress bar."
},
{
"code": null,
"e": 13191,
"s": 13090,
"text": "# initialize h2o session and switch off progress barh2o.no_progress() h2o.init(max_mem_size = \"16G\")"
},
{
"code": null,
"e": 13454,
"s": 13191,
"text": "Next, I sort out response and predictor variables sets. For a classification to be performed, I need to ensure that the response variable is a factor (otherwise h2o will carry out a regression). This was sorted out during the data cleansing and formatting phase."
},
{
"code": null,
"e": 13579,
"s": 13454,
"text": "# response variabley <- \"subscribed\"# predictors set: remove response variablex <- setdiff(names(train_tbl %>% as.h2o()), y)"
},
{
"code": null,
"e": 13770,
"s": 13579,
"text": "For this project, I’m estimating a Generalised Linear Model (a.k.a. Elastic Net), a Random Forest (which h2o refers to at Distributed Random Forest) and a Gradient Boosting Machine (or GBM)."
},
{
"code": null,
"e": 14033,
"s": 13770,
"text": "To implement a grid search for the tree-based models (DRF and GBM), I need to set up a random grid to search for optimal hyper-parameters for the h2o.grid() function. To do so, I start with defining the search parameters to be passed to the hyper_paramsargument:"
},
{
"code": null,
"e": 14096,
"s": 14033,
"text": "sample_rate is used to set the row sampling rate for each tree"
},
{
"code": null,
"e": 14163,
"s": 14096,
"text": "col_sample_rate_per_tree defines the column sampling for each tree"
},
{
"code": null,
"e": 14206,
"s": 14163,
"text": "max_depth specifies the maximum tree depth"
},
{
"code": null,
"e": 14266,
"s": 14206,
"text": "min_rows to fix the minimum number of observations per leaf"
},
{
"code": null,
"e": 14349,
"s": 14266,
"text": "mtries(DRF only) indicates the columns to randomly select on each node of the tree"
},
{
"code": null,
"e": 14437,
"s": 14349,
"text": "learn_rate(GBM only) specifies the rate at which the model learns when building a model"
},
{
"code": null,
"e": 15028,
"s": 14437,
"text": "# DRF hyperparametershyper_params_drf <- list( mtries = seq(2, 5, by = 1), sample_rate = c(0.65, 0.8, 0.95), col_sample_rate_per_tree = c(0.5, 0.9, 1.0), max_depth = seq(1, 30, by = 3), min_rows = c(1, 2, 5, 10) )# GBM hyperparametershyper_params_gbm <- list( learn_rate = c(0.01, 0.1), sample_rate = c(0.65, 0.8, 0.95), col_sample_rate_per_tree = c(0.5, 0.9, 1.0), max_depth = seq(1, 30, by = 3), min_rows = c(1, 2, 5, 10) )"
},
{
"code": null,
"e": 15149,
"s": 15028,
"text": "I also set up a second list for the search_criteria argument, which helps to manage the models’ estimation running time:"
},
{
"code": null,
"e": 15276,
"s": 15149,
"text": "The strategy argument is set to RandomDiscrete for the search to randomly select a combination from the grid search parameters"
},
{
"code": null,
"e": 15422,
"s": 15276,
"text": "Setting stopping_metric to AUC as the error metric for early stopping - the models will stop building new trees when the metric ceases to improve"
},
{
"code": null,
"e": 15524,
"s": 15422,
"text": "With stopping_rounds I’m specifying the number of training rounds before early stopping is considered"
},
{
"code": null,
"e": 15624,
"s": 15524,
"text": "I’m using stopping_tolerance to set minimal improvement needed for the training process to continue"
},
{
"code": null,
"e": 15689,
"s": 15624,
"text": "max_runtime_secs restricts the search time to one hour per model"
},
{
"code": null,
"e": 15904,
"s": 15689,
"text": "search_criteria_all <- list( strategy = \"RandomDiscrete\", stopping_metric = \"AUC\", stopping_rounds = 10, stopping_tolerance = 0.0001, max_runtime_secs = 60 * 60 )"
},
{
"code": null,
"e": 16002,
"s": 15904,
"text": "At last, I can set up the models’ formulations. Note that all models have 2 parameters in common:"
},
{
"code": null,
"e": 16183,
"s": 16002,
"text": "the nfolds parameter, which enables cross-validation to be carried out without the need for a validation_frame - if set to 5 for instance, it will perform a 5-fold cross-validation"
},
{
"code": null,
"e": 16421,
"s": 16183,
"text": "the balance_classes parameter is set to TRUE to account for the imbalance in the target variable highlighted during the exploratory analysis. When enabled, h2o will either under-sample the majority class or oversample the minority class."
},
{
"code": null,
"e": 17491,
"s": 16421,
"text": "# elastic net model glm_model <- h2o.glm( x = x, y = y, training_frame = train_tbl %>% as.h2o(), balance_classes = TRUE, nfolds = 10, family = \"binomial\", seed = 1975 )# random forest modeldrf_model_grid <- h2o.grid( algorithm = \"randomForest\", x = x, y = y, training_frame = train_tbl %>% as.h2o(), balance_classes = TRUE, nfolds = 10, ntrees = 1000, grid_id = \"drf_grid\", hyper_params = hyper_params_drf, search_criteria = search_criteria_all, seed = 1975 )# gradient boosting machine modelgbm_model_grid <- h2o.grid( algorithm = \"gbm\", x = x, y = y, training_frame = train_tbl %>% as.h2o(), balance_classes = TRUE, nfolds = 10, ntrees = 1000, grid_id = \"gbm_grid\", hyper_params = hyper_params_gbm, search_criteria = search_criteria_all, seed = 1975 )"
},
{
"code": null,
"e": 17575,
"s": 17491,
"text": "I sort the tree-based model by AUC score and retrieve the lead models from the grid"
},
{
"code": null,
"e": 18122,
"s": 17575,
"text": "# Get the DRM grid results, sorted by AUC drf_grid_perf <- h2o.getGrid(grid_id = \"drf_grid\", sort_by = \"AUC\", decreasing = TRUE)# Fetch the top DRF model, chosen by validation AUCdrf_model <- h2o.getModel(drf_grid_perf@model_ids[[1]])# Get the GBM grid results, sorted by AUC gbm_grid_perf <- h2o.getGrid(grid_id = \"gbm_grid\", sort_by = \"AUC\", decreasing = TRUE)# Fetch the top GBM model, chosen by validation AUCgbm_model <- h2o.getModel(gbm_grid_perf@model_ids[[1]])"
},
{
"code": null,
"e": 18369,
"s": 18122,
"text": "There are many libraries (like IML, PDP, VIP, and DALEX to name but the more popular) that help with Machine Learning Interpretability, feature explanation and general performance assessment and they all have gained in popularity in recent years."
},
{
"code": null,
"e": 18767,
"s": 18369,
"text": "There are a number of methodologies to interpret machine learning results (i.e. local interpretable model-agnostic explanations, partial dependence plots, permutation-based variable importance) but in this project, I examine the DALEX package, which focuses on Model-Agnostic Interpretability and provides a convenient way of comparing performance across multiple models with different structures."
},
{
"code": null,
"e": 19104,
"s": 18767,
"text": "One of the key advantages of the model-agnostic approach used by DALEX is that you can compare contributions of traditional “glass-box” models to black-box models on the same scale. However, being permutation-based, one of its main drawbacks is that it does not scale well with a large number of predictor variables and larger datasets."
},
{
"code": null,
"e": 19418,
"s": 19104,
"text": "Currently DALEX does not support some of the more recent ML packages like h2o or xgboost. To make it compatible with such objects, I’ve followed the procedure illustrated by Bradley Boehmke in his brilliant study Model Interpretability with DALEX, from which I’ve drawn lots of inspiration and borrowed some code."
},
{
"code": null,
"e": 19471,
"s": 19418,
"text": "First, the dataset needs to be in a specific format:"
},
{
"code": null,
"e": 19706,
"s": 19471,
"text": "# convert feature variables to a data framex_valid <- test_tbl %>% select(-subscribed) %>% as_tibble()# change response variable to a numeric binary vectory_valid <- as.vector(as.numeric(as.character(test_tbl$subscribed)))"
},
{
"code": null,
"e": 19861,
"s": 19706,
"text": "Then, I create a predict function returning a vector of numeric values, which extracts the probability of the response for binary classification problems."
},
{
"code": null,
"e": 20063,
"s": 19861,
"text": "# create custom predict functionpred <- function(model, newdata) { results <- as.data.frame(h2o.predict(model, newdata %>% as.h2o())) return(results[[3L]]) }"
},
{
"code": null,
"e": 20210,
"s": 20063,
"text": "Now I can convert my machine learning models into DALEK “explainers” with the explain() function, which works as a “container” for the parameters."
},
{
"code": null,
"e": 20951,
"s": 20210,
"text": "# generalised linear model explainerexplainer_glm <- explain( model = glm_model, type = \"classification\", data = x_valid, y = y_valid, predict_function = pred, label = \"h2o_glm\" )# random forest model explainerexplainer_drf <- explain( model = drf_model, type = \"classification\", data = x_valid, y = y_valid, predict_function = pred, label = \"h2o_drf\" )# gradient boosting machine explainerexplainer_gbm <- explain( model = gbm_model, type = \"classification\", data = x_valid, y = y_valid, predict_function = pred, label = \"h2o_gbm\" )"
},
{
"code": null,
"e": 21324,
"s": 20951,
"text": "At last, I’m ready to pass the explainer objects to several DALEX functions that will help assess and compare the performance of the different models. Given that performance measures may reflect a different aspect of the predictive performance of a model, it is important to evaluate and compare several metrics when appraising a model and with DALEX you can do just that!"
},
{
"code": null,
"e": 21548,
"s": 21324,
"text": "To evaluate and compare my models’ performance, I’ve drawn inspiration from the framework used by Przemyslaw Biecek and Tomasz Burzykowski in their book, Explanatory Model Analysis, which is structured around key questions:"
},
{
"code": null,
"e": 21580,
"s": 21548,
"text": "1 — Are the models well fitted?"
},
{
"code": null,
"e": 21628,
"s": 21580,
"text": "2 — How do the models compare with one another?"
},
{
"code": null,
"e": 21677,
"s": 21628,
"text": "3 — Which variables are important in the models?"
},
{
"code": null,
"e": 21739,
"s": 21677,
"text": "4 — How does a single variable affect the average prediction?"
},
{
"code": null,
"e": 21914,
"s": 21739,
"text": "To get an initial feel for how well my models fit the data, I can use the self-explanatory model_performance() function, which calculates selected model performance measures."
},
{
"code": null,
"e": 23310,
"s": 21914,
"text": "model_performance(explainer_glm)## Measures for: classification## recall : 0 ## precision: NaN ## f1 : NaN ## accuracy : 0.8914653 ## auc : 0.7500738## ## Residuals:## 0% 10% 20% 30% 40% 50% ## -0.48867133 -0.16735197 -0.09713539 -0.07193152 -0.06273300 -0.05418778 ## 60% 70% 80% 90% 100% ## -0.04661088 -0.03971492 -0.03265955 0.63246516 0.98072521model_performance(explainer_drf)## Measures for: classification## recall : 0.1700224 ## precision: 0.76 ## f1 : 0.2778793 ## accuracy : 0.9040913 ## auc : 0.7993824## ## Residuals:## 0% 10% 20% 30% 40% 50% ## -0.87841486 -0.13473277 -0.07933048 -0.06305297 -0.05556507 -0.04869549 ## 60% 70% 80% 90% 100% ## -0.04172427 -0.03453394 -0.02891645 0.33089059 0.98046626model_performance(explainer_gbm)## Measures for: classification## recall : 0.2192394 ## precision: 0.7340824 ## f1 : 0.33764 ## accuracy : 0.9066408 ## auc : 0.7988382## ## Residuals:## 0% 10% 20% 30% 40% 50% ## -0.83600975 -0.14609749 -0.08115376 -0.06542395 -0.05572322 -0.04789869 ## 60% 70% 80% 90% 100% ## -0.04068165 -0.03371074 -0.02750033 0.29004942 0.98274727"
},
{
"code": null,
"e": 23594,
"s": 23310,
"text": "Based on the metrics available for all models ( accuracy and AUC), I can see that elastic net and gradient boosting are performing roughly on par with one another, with random forest not far behind. AUC ranges between .78-.80 whereas accuracy has a slightly narrower range of .89-.90"
},
{
"code": null,
"e": 23754,
"s": 23594,
"text": "As shown in the previous paragraph, model_performance() also produces residual quantiles that can be plotted to compare absolute residual values across models."
},
{
"code": null,
"e": 24378,
"s": 23754,
"text": "# compute and assign residuals to an objectresids_glm <- model_performance(explainer_glm)resids_drf <- model_performance(explainer_drf)resids_gbm <- model_performance(explainer_gbm)# compare residuals plotsp1 <- plot(resids_glm, resids_drf, resids_gbm) + theme_minimal() + theme(legend.position = 'bottom', plot.title = element_text(hjust = 0.5)) + labs(y = '')p2 <- plot(resids_glm, resids_drf, resids_gbm, geom = \"boxplot\") + theme_minimal() + theme(legend.position = 'bottom', plot.title = element_text(hjust = 0.5)) gridExtra::grid.arrange(p2, p1, nrow = 1)"
},
{
"code": null,
"e": 24820,
"s": 24378,
"text": "The DRF and GBM models appear to perform on a par with one another, given the median absolute residuals. Looking at the residuals distribution on the right-hand side, you can see that the median residuals are the lowest for these two models, with the GLM seeing a higher number of tail residuals. This is also mirrored by the boxplots on the left-hand side, where the tree-based models both achieve the lowest median absolute residual value."
},
{
"code": null,
"e": 25143,
"s": 24820,
"text": "The Receiver Operating Characteristic (ROC) curve is a graphical method that allows to visualise a classification model performance against a random guess, which is represented by the striped line on the graph. The curve plots the true positive rate (TPR) on the y-axis against the false positive rate (FPR) on the x-axis."
},
{
"code": null,
"e": 25509,
"s": 25143,
"text": "eva_glm <- DALEX::model_performance(explainer_glm)eva_dfr <- DALEX::model_performance(explainer_drf)eva_gbm <- DALEX::model_performance(explainer_gbm)plot(eva_glm, eva_dfr, eva_gbm, geom = \"roc\") + ggtitle(\"ROC Curves - All Models\", \"AUC_glm = 0.750 AUC_drf = 0.799 AUC_gbm = 0.798\") + theme_minimal() + theme(plot.title = element_text(hjust = 0.5))"
},
{
"code": null,
"e": 25551,
"s": 25509,
"text": "The insight from a ROC curve is two-fold:"
},
{
"code": null,
"e": 25622,
"s": 25551,
"text": "Direct read: All models are performing much better than a random guess"
},
{
"code": null,
"e": 25793,
"s": 25622,
"text": "Compared read: the AUC (Area Under the Curve) summarises the ROC curve and can be used to directly compare models performance — the perfect classifier would have AUC = 1."
},
{
"code": null,
"e": 25928,
"s": 25793,
"text": "All models performs much better that random guessing and achieves a AUC of .75-.80, with the DRF achieving the highest score of 0.799."
},
{
"code": null,
"e": 26178,
"s": 25928,
"text": "Each ML algorithm has its own way to assess the importance of each variable: linear models, for instance, refer to their coefficients, whereas tree-based models look at impurity, which makes it difficult to compare variable importance across models."
},
{
"code": null,
"e": 26492,
"s": 26178,
"text": "DALEX calculates variable importance measures via permutation, which is model agnostics and allows for direct comparison between models of different structure. However, when variable importance scores are based on permutations, we should remember that calculations slow down when the number of features increases."
},
{
"code": null,
"e": 26941,
"s": 26492,
"text": "Once again, I’m passing the “explainer” for each single model to the feature_importance() function and setting n_sample to 8000 to use practically all available observations. Although not exorbitant, the total execution time was nearly 30 minute but this is based on a relatively small dataset and the number of variables. Don’t forget that computation speed can be increased by reducing n_sample, which is especially important for larger datasets."
},
{
"code": null,
"e": 27562,
"s": 26941,
"text": "# measure execution timetictoc::tic()# compute permutation-based variable importancevip_glm <- feature_importance(explainer_glm, n_sample = 8000, loss_function = loss_root_mean_square) vip_drf <- feature_importance(explainer_drf, n_sample = 8000, loss_function = loss_root_mean_square)vip_gbm <- feature_importance(explainer_gbm, n_sample = 8000, loss_function = loss_root_mean_square)# show total execution timetictoc::toc()## 1803.65 sec elapsed"
},
{
"code": null,
"e": 27960,
"s": 27562,
"text": "Now I only have to pass the vip objects to a plotting function: as suggested by the auto-generated x-axis label ( Drop-out loss), the main intuition behind how variable importance is calculated lies in how much the model fit would decrease if the contribution of a selected explanatory variable was removed. The larger the segment, the larger the loss when that variable is dropped from the model."
},
{
"code": null,
"e": 28275,
"s": 27960,
"text": "# plotting top 10 feature only for clarity of readingplot(vip_glm, vip_drf, vip_gbm, max_vars = 10) + ggtitle(\"Permutation variable importance\", \"Average variable importance based on 8,000 permutations\") + theme_minimal() + theme(plot.title = element_text(hjust = 0.5))"
},
{
"code": null,
"e": 28339,
"s": 28275,
"text": "I like this plot as it brings together a wealth of information."
},
{
"code": null,
"e": 28775,
"s": 28339,
"text": "First of all, you can notice that, although with slightly different relative weights, the top 5 features are common to each model, with nr_employed ( employed in the economy) being the single most important predictor in all of them. This consistency is reassuring as it tells us that all models are picking up the same structure and interactions in the data, and gives us the assurance that these features have strong predictive power."
},
{
"code": null,
"e": 29106,
"s": 28775,
"text": "You can also notice the distinct starting point for the x-axis left edge, which reflects the difference in the RMSE loss between the three models: in this case the elastic net model has the highest RMSE, suggesting the higher number of tail residuals seen earlier in the residual diagnostics is probably penalising the RMSE score."
},
{
"code": null,
"e": 29448,
"s": 29106,
"text": "After we have identified the relative predictive power of each variable, we may want to investigate how their relationship with the predicted response differ across all three models. Partial Dependence (PD) plots, sometimes also referred to as PD profiles, offer a great way to inspect how each model is responding to a particular predictor."
},
{
"code": null,
"e": 29531,
"s": 29448,
"text": "We can start with having a look at the single most important feature, nr_employed:"
},
{
"code": null,
"e": 30192,
"s": 29531,
"text": "# compute PDP for a given variablepdp_glm <- model_profile(explainer_glm, variable = \"nr_employed\", type = \"partial\")pdp_drf <- model_profile(explainer_drf, variable = \"nr_employed\", type = \"partial\")pdp_gbm <- model_profile(explainer_gbm, variable = \"nr_employed\", type = \"partial\")plot(pdp_glm$agr_profiles, pdp_drf$agr_profiles, pdp_gbm$agr_profiles) + ggtitle(\"Contrastive Partial Dependence Profiles\", \"\") + theme_minimal() + theme(plot.title = element_text(hjust = 0.5))"
},
{
"code": null,
"e": 30679,
"s": 30192,
"text": "Although with different average prediction weights, all three models found that bank customers are more likely to sign up to a term deposit when the level of employed in the economy is up to 5.099m (nInf_5099.1). Both elastic net and random forest have found the exact same hierarchy of predictive power among the 3 different levels of nr_employed (less pronounced for the random forest) that we observed in the correlationfunnel analysis, with GBM being the one slightly out of kilter."
},
{
"code": null,
"e": 30814,
"s": 30679,
"text": "Let’s now take a look at age, a predictor that, if you recall from the EDA, was NOT expected to have an impact on the target variable:"
},
{
"code": null,
"e": 31207,
"s": 30814,
"text": "One thing we notice is that the range of variation in the average prediction (x-axis) is relatively shallow across the age spectrum (y-axis), confirming the finding from the exploratory analysis that this variable would have a low predictive power. Also, both GBM and random forest are using age in a non-linear way, whereas the elastic net model is unable to capture this non-linear dynamic."
},
{
"code": null,
"e": 31487,
"s": 31207,
"text": "Partial Dependence plots could also work as a diagnostic tool: looking at poutcome (outcome of the previous marketing campaign) reveals that GBM and random forest correctly picked up on a higher probability of signing up when the outcome of a previous campaign was success (scs)."
},
{
"code": null,
"e": 31676,
"s": 31487,
"text": "However, the elastic net model fails to do the same, which could represent a serious flaw as success in a previous campaign had a very strong positive correlation with the target variable."
},
{
"code": null,
"e": 32003,
"s": 31676,
"text": "I’m going to finish with the month feature as it offers a great example of one of those cases where you may want to override the model’s outcome with industry knowledge and some common sense. Specifically, the GBM model seems to suggest that March, October and December are periods associated with much better odds of success."
},
{
"code": null,
"e": 32301,
"s": 32003,
"text": "Based on my previous analysis experience of similar financial products, I would not advise a banking organisation to ramp up their direct marketing activity around the weeks in the run to Christmas as this is a period of the year where the consumers’ focus shifts away from this type of purchases."
},
{
"code": null,
"e": 32486,
"s": 32301,
"text": "All in all random forest is my final model of choice: it appears the more balanced of the three and does not display some of the “oddities” seen with variables like month and poutcome."
},
{
"code": null,
"e": 32694,
"s": 32486,
"text": "I can now further refine my model and reduce its complexity by combining findings from the Exploratory analysis, insight from models’ assessment and a number of industry-specific/common sense considerations."
},
{
"code": null,
"e": 32725,
"s": 32694,
"text": "In particular, my final model:"
},
{
"code": null,
"e": 32833,
"s": 32725,
"text": "Excludes a number of features (age, housing, loan, campaign, cons_price_idx) that have low predictive power"
},
{
"code": null,
"e": 33020,
"s": 32833,
"text": "Removes previous, which shows little difference between its 2 levels in the PD plot - it’s also moderately correlated with pdays, suggesting that they may be capturing the same behaviour"
},
{
"code": null,
"e": 33184,
"s": 33020,
"text": "Also drops emp_var_rate because of its strong correlation with nr_employed and also because conceptually they are controlling for a very similar economic behaviour"
},
{
"code": null,
"e": 33544,
"s": 33184,
"text": "# response variable remains unalteredy <- \"subscribed\"# predictors set: remove response variable and 7 predictorsx_final <- setdiff(names(train_tbl %>% select(-c(age, housing, loan, campaign, previous, cons_price_idx, emp_var_rate)) %>% as.h2o()), y)"
},
{
"code": null,
"e": 33631,
"s": 33544,
"text": "For the final model, I’m using the same specification as to the original random forest"
},
{
"code": null,
"e": 34056,
"s": 33631,
"text": "# random forest modeldrf_final <- h2o.grid( algorithm = \"randomForest\", x = x_final, y = y, training_frame = train_tbl %>% as.h2o(), balance_classes = TRUE, nfolds = 10, ntrees = 1000, grid_id = \"drf_grid_final\", hyper_params = hyper_params_drf, search_criteria = search_criteria_all, seed = 1975 )"
},
{
"code": null,
"e": 34127,
"s": 34056,
"text": "Once again, we sort the model by AUC score and retrieve the lead model"
},
{
"code": null,
"e": 34408,
"s": 34127,
"text": "# Get the grid results, sorted by AUC drf_grid_perf_final <- h2o.getGrid(grid_id = \"drf_grid_final\", sort_by = \"AUC\", decreasing = TRUE)# Fetch the top DRF model, chosen by validation AUCdrf_final <- h2o.getModel(drf_grid_perf_final@model_ids[[1]])"
},
{
"code": null,
"e": 34574,
"s": 34408,
"text": "For brevity, I am visualising the variable importance plot with the vip() function from the namesake package, which returns the ranked contribution of each variable."
},
{
"code": null,
"e": 34720,
"s": 34574,
"text": "vip::vip(drf_final, num_features = 12) + ggtitle(\"Variable Importance\", \"\") + theme_minimal() + theme(plot.title = element_text(hjust = 0.5))"
},
{
"code": null,
"e": 34993,
"s": 34720,
"text": "Removing emp_var_rate has allowed education to come into the top 10 features. Understandably, the variables hierarchy and relative predictive power has adjusted and changed slightly but it’s reassuring to see that the other 9 variables were in the previous model’s top 10."
},
{
"code": null,
"e": 35078,
"s": 34993,
"text": "Lastly, I’m comparing the model’s performance with the original random forest model."
},
{
"code": null,
"e": 35267,
"s": 35078,
"text": "drf_final %>% h2o.performance(newdata = test_tbl %>% as.h2o()) %>% h2o.auc()## [1] 0.7926509drf_model %>% h2o.performance(newdata = test_tbl %>% as.h2o()) %>% h2o.auc()## [1] 0.7993973"
},
{
"code": null,
"e": 35383,
"s": 35267,
"text": "The AUC has only changed by a fraction of a percent, telling me that the model has maintained its predictive power."
},
{
"code": null,
"e": 35723,
"s": 35383,
"text": "Being already familiar with odds ratios in the context of a logistic regression, I set out to understand whether the same intuition could be extended to black-box classification models. During my research one very interesting post on Cross Validated stood out for drawing a parallel between odds ratio from decision tree and random forest."
},
{
"code": null,
"e": 35947,
"s": 35723,
"text": "Basically, this tells us that Partial Dependence plots can be used in a similar way to odds ratios to define what characteristics of a customer profile influence his/her propensity to performing a certain type of behaviour."
},
{
"code": null,
"e": 36055,
"s": 35947,
"text": "For example, features like job, month and contact would provide context around who, when and how to target:"
},
{
"code": null,
"e": 36178,
"s": 36055,
"text": "Looking at job will tell us that a customer in an admin role is roughly 25% more likely to subscribe that a self employed."
},
{
"code": null,
"e": 36315,
"s": 36178,
"text": "Getting in touch with a prospective customer in the month of October will more than double the chance of a positive outcome than in May."
},
{
"code": null,
"e": 36444,
"s": 36315,
"text": "contacting your customer on their mobile increases the chances of subscription by nearly a quarter compared to a telephone call."
},
{
"code": null,
"e": 36668,
"s": 36444,
"text": "NOTE THAT Partial Dependence Plots for all final model’s predictors can be found on my webpage: on my webpage: Propensity Modelling — Estimate Several Models and Compare Their Performance Using a Model-agnostic Methodology."
},
{
"code": null,
"e": 36823,
"s": 36668,
"text": "Armed with such insight, one can help to shape overall marketing and communication plans to focus on customers more likely to subscribe to a term deposit."
},
{
"code": null,
"e": 37280,
"s": 36823,
"text": "However, these are based on model-level explainers, which reflect an overall, aggregated view. If you’re interested to understand how a model yields a prediction for a single observation (i.e. what factors influence the likelihood to engage at single customer level), you can resort to the Local Interpretable Model-agnostic Explanations (LIME) method that exploits the concept of a “local model”. I will be exploring the LIME methodology in a future post."
},
{
"code": null,
"e": 37739,
"s": 37280,
"text": "For the analysis part of this project, I opted for h2o as my modelling platform. h2o is not only very easy to use but also has a number of built-in functionalities that help speeding up data preparation: it takes care of class imbalance with no need for pre-modelling resampling, automatically __“binarises“ character/factor__ variables, and implements cross-validation without the need for a separate validation frame to be “carved out\" of the training set."
},
{
"code": null,
"e": 38158,
"s": 37739,
"text": "After setting up a random grid to search for best hyper-parameters, I’ve estimated the number of models ( a logistic regression, a random forest and a gradient boosting machines) and used the DALEX library to assess and compare their performance through an array of metrics. This library employs a model-agnostic approach that enables to compare traditional “glass-box” models and “black-box” models on the same scale."
},
{
"code": null,
"e": 38472,
"s": 38158,
"text": "My final model of choice is the random forest, which I further refined by combining findings from the exploratory analysis, insight gathered from the models’ evaluation and a number of industry-specific/common sense considerations. This ensured a reduced model complexity without compromising on predictive power."
},
{
"code": null,
"e": 38884,
"s": 38472,
"text": "Now that I have my final model, the last piece of the puzzle is the final “So what?” question that puts all into perspective. The estimate for the probability of a customer to sign up for a term deposit can be used to create a number of optimised scenarios, ranging from minimising your marketing expenditure, maximising your overall acquisition targets, to driving a certain number of cross-sell opportunities."
},
{
"code": null,
"e": 39030,
"s": 38884,
"text": "Before I can do that, there are a couple of housekeeping tasks needed to “set up the work scene” and a couple of important concepts to introduce:"
},
{
"code": null,
"e": 39061,
"s": 39030,
"text": "the threshold and the F1 score"
},
{
"code": null,
"e": 39082,
"s": 39061,
"text": "precision and recall"
},
{
"code": null,
"e": 39316,
"s": 39082,
"text": "The question the model is trying to answer is “ Has this customer signed up for a term deposit following a direct marketing campaign? “ and the cut-off (a.k.a. the threshold) is the value that divides the predictions into Yes and No."
},
{
"code": null,
"e": 39442,
"s": 39316,
"text": "To illustrate the point, I first calculate some predictions by passing the test_tbl data set to the h2o.performance function."
},
{
"code": null,
"e": 40765,
"s": 39442,
"text": "perf_drf_final <- h2o.performance(drf_final, newdata = test_tbl %>% as.h2o()) perf_drf_final@metrics$max_criteria_and_metric_scores## Maximum Metrics: Maximum metrics at their respective thresholds## metric threshold value idx## 1 max f1 0.189521 0.508408 216## 2 max f2 0.108236 0.560213 263## 3 max f0point5 0.342855 0.507884 143## 4 max accuracy 0.483760 0.903848 87## 5 max precision 0.770798 0.854167 22## 6 max recall 0.006315 1.000000 399## 7 max specificity 0.930294 0.999864 0## 8 max absolute_mcc 0.189521 0.444547 216## 9 max min_per_class_accuracy 0.071639 0.721231 300## 10 max mean_per_class_accuracy 0.108236 0.755047 263## 11 max tns 0.930294 7342.000000 0## 12 max fns 0.930294 894.000000 0## 13 max fps 0.006315 7343.000000 399## 14 max tps 0.006315 894.000000 399## 15 max tnr 0.930294 0.999864 0## 16 max fnr 0.930294 1.000000 0## 17 max fpr 0.006315 1.000000 399## 18 max tpr 0.006315 1.000000 399"
},
{
"code": null,
"e": 41003,
"s": 40765,
"text": "Like many other machine learning modelling platforms, h2o uses the threshold value associated with the maximum F1 score, which is nothing but a weighted average between precision and recall. In this case, the threshold @ Max F1 is 0.190."
},
{
"code": null,
"e": 41366,
"s": 41003,
"text": "Now, I use the h2o.predict function to make predictions using the test set. The prediction output comes with three columns: the actual model predictions (predict), and the probabilities associated with that prediction (p0, and p1, corresponding to No and Yes respectively). As you can see, the p1 probability associated with the current cut-off is around 0.0646."
},
{
"code": null,
"e": 41860,
"s": 41366,
"text": "drf_predict <- h2o.predict(drf_final, newdata = test_tbl %>% as.h2o())# I converte to a tibble for ease of useas_tibble(drf_predict) %>% arrange(p0) %>% slice(3088:3093) %>% kable()predict p0 p1 1 0.9352865 0.0647135 1 0.9352865 0.0647135 1 0.9352865 0.0647135 0 0.9354453 0.0645547 0 0.9354453 0.0645547 0 0.9354453 0.0645547"
},
{
"code": null,
"e": 42037,
"s": 41860,
"text": "However, the F1 score is only one way to identify the cut-off. Depending on our goal, we could also decide to use a threshold that, for instance, maximises precision or recall."
},
{
"code": null,
"e": 42169,
"s": 42037,
"text": "In a commercial setting, the pre-selected threshold @ Max F1 may not necessarily be the optimal choice: enter Precision and Recall!"
},
{
"code": null,
"e": 42464,
"s": 42169,
"text": "Precision shows how sensitive models are to False Positives (i.e. predicting a customer is subscribing when he-she is actually NOT) whereas Recall looks at how sensitive models are to False Negatives (i.e. forecasting that a customer is NOT subscribing whilst he-she is in fact going to do so)."
},
{
"code": null,
"e": 42889,
"s": 42464,
"text": "These metrics are very relevant in a business context because organisations are particularly interested in accurately predicting which customers are truly likely to subscribe (high precision) so that they can target them with advertising strategies and other incentives. At the same time they want to minimise efforts towards customers incorrectly classified as subscribing (high recall) who are instead unlikely to sign up."
},
{
"code": null,
"e": 43057,
"s": 42889,
"text": "However, as you can see from the chart below, when precision gets higher, recall gets lower and vice versa. This is often referred to as the Precision-Recall tradeoff."
},
{
"code": null,
"e": 43275,
"s": 43057,
"text": "To fully comprehend this dynamic and its implications, let’s start with taking a look at the cut-off zero and cut-off one points and then see what happens when you start moving the threshold between the two positions:"
},
{
"code": null,
"e": 43649,
"s": 43275,
"text": "At threshold zero ( lowest precision, highest recall) the model classifies every customer as subscribed = Yes. In such a scenario, you would contact every single customer with direct marketing activity but waste precious resources by also including those less likely to subscribe. Clearly this is not an optimal strategy as you’d incur in a higher overall acquisition cost."
},
{
"code": null,
"e": 44057,
"s": 43649,
"text": "Conversely, at threshold one ( highest precision, lowest recall) the model tells you that nobody is likely to subscribe so you should contact no one. This would save you tons of money in marketing cost but you’d be missing out on the additional revenue from those customers who would’ve subscribed, had they been notified about the term deposit through direct marketing. Once again, not an optimal strategy."
},
{
"code": null,
"e": 44420,
"s": 44057,
"text": "When moving to a higher threshold the model becomes more “choosy” on who it classifies as subscribed = Yes. As a consequence, you become more conservative on who to contact ( higher precision) and reduce your acquisition cost, but at the same time you increase your chance of not reaching prospective subscribes ( lower recall), missing out on potential revenue."
},
{
"code": null,
"e": 44675,
"s": 44420,
"text": "The key question here is where do you stop? Is there a “sweet spot” and if so, how do you find it? Well, that will depend entirely on the goal you want to achieve. In the next section, I’ll be running a mini-optimisation with the goal to maximise profit."
},
{
"code": null,
"e": 44959,
"s": 44675,
"text": "For this mini-optimisation I’m implementing a simple profit maximisation based on generic costs connected to acquiring a new customer and benefits derived from said acquisition. This can be evolved to include more complex scenarios but it would be outside the scope of this exercise."
},
{
"code": null,
"e": 45183,
"s": 44959,
"text": "To understand which cut-off value is optimal to use we need to simulate the cost-benefit associated with each threshold point. This is a concept derived from the Expected Value Framework as seen on Data Science for Business"
},
{
"code": null,
"e": 45209,
"s": 45183,
"text": "To do so I need 2 things:"
},
{
"code": null,
"e": 45294,
"s": 45209,
"text": "Expected Rates for each threshold — These can be retrieved from the confusion matrix"
},
{
"code": null,
"e": 45378,
"s": 45294,
"text": "Cost/Benefit for each customer — I will need to simulate these based on assumptions"
},
{
"code": null,
"e": 45464,
"s": 45378,
"text": "Expected rates can be conveniently retrieved for all cut-off points using h2o.metric."
},
{
"code": null,
"e": 45605,
"s": 45464,
"text": "# Get expected rates by cutoffexpected_rates <- h2o.metric(perf_drf_final) %>% as.tibble() %>% select(threshold, tpr, fpr, fnr, tnr)"
},
{
"code": null,
"e": 45904,
"s": 45605,
"text": "The cost-benefit matrix is a business assessment of the cost and benefit for each of four potential outcomes. To create such a matrix I will have to make a few assumptions about the expenses and advantages that an organisation should consider when carrying out an advertising-led procurement drive."
},
{
"code": null,
"e": 46504,
"s": 45904,
"text": "Let’s assume that the cost of selling term deposits is of £30 per customer. This would include the likes of performing the direct marketing activity (training the call centre reps, setting time aside for active calls, etc.) and incentives such as offering discounts on another financial product or onboarding onto membership schemes offering benefits and perks. A banking organisation will incur in this type of cost in two cases: when they correctly predict that a customer will subscribe ( true positive, TP), and when they incorrectly predict that a customer will subscribe ( false positive, FP)."
},
{
"code": null,
"e": 46764,
"s": 46504,
"text": "Let’s also assume that the revenue of selling a term deposits to an existing customer is of £80 per customer. The organisation will guarantee this revenue stream when the model predicts that a customer will subscribe and they actually do ( true positive, TP)."
},
{
"code": null,
"e": 46940,
"s": 46764,
"text": "Finally, there’s the true negative (TN) scenario where we correctly predict that a customer won’t subscribe. In this case, we won’t spend any money but won’t earn any revenue."
},
{
"code": null,
"e": 46984,
"s": 46940,
"text": "Here’s a quick recap of the cost scenarios:"
},
{
"code": null,
"e": 47071,
"s": 46984,
"text": "True Positive (TP) — predict will subscribe, and they actually do: COST: -£30; REV £80"
},
{
"code": null,
"e": 47165,
"s": 47071,
"text": "False Positive (FP) — predict will subscribe, when they actually wouldn’t: COST: -£30; REV £0"
},
{
"code": null,
"e": 47253,
"s": 47165,
"text": "True Negative (TN) — predict won’t subscribe, and they actually don’t: COST: £0; REV £0"
},
{
"code": null,
"e": 47339,
"s": 47253,
"text": "False Negative (FN) — predict won’t subscribe, but they actually do: COST: £0; REV £0"
},
{
"code": null,
"e": 47609,
"s": 47339,
"text": "I create a function to calculate the expected cost using the probability of a positive case (p1) and the cost/benefit associated with a true positive (cb_tp) and a false positive (cb_fp). No need to include the true negative or false negative here as they’re both zero."
},
{
"code": null,
"e": 47759,
"s": 47609,
"text": "I’m also including the expected_rates data frame created previously with the expected rates for each threshold (400 thresholds, ranging from 0 to 1)."
},
{
"code": null,
"e": 48271,
"s": 47759,
"text": "# Function to calculate expected profitexpected_profit_func <- function(p1, cb_tp, cb_fp) { tibble( p1 = p1, cb_tp = cb_tp, cb_fp = cb_fp ) %>% # add expected rates mutate(expected_rates = list(expected_rates)) %>% unnest() %>% # calculate the expected profit mutate( expected_profit = p1 * (tpr * cb_tp) + (1 - p1) * (fpr * cb_fp) ) %>% select(threshold, expected_profit)}"
},
{
"code": null,
"e": 48760,
"s": 48271,
"text": "Now to understand how a multi customer dynamic would work, I’m creating a hypothetical 10 customer group to test my function on. This is a simplified view in that I’m applying the same cost and revenue structure to all customers but the cost/benefit framework can be tailored to the individual customer to reflect their separate product and service level set up and the process can be easily adapted to optimise towards different KPIs (like net profit, CLV, number of subscriptions, etc.)"
},
{
"code": null,
"e": 49263,
"s": 48760,
"text": "# Ten Hypothetical Customers ten_cust <- tribble( ~\"cust\", ~\"p1\", ~\"cb_tp\", ~\"cb_fp\", 'ID1001', 0.1, 80 - 30, -30, 'ID1002', 0.2, 80 - 30, -30, 'ID1003', 0.3, 80 - 30, -30, 'ID1004', 0.4, 80 - 30, -30, 'ID1005', 0.5, 80 - 30, -30, 'ID1006', 0.6, 80 - 30, -30, 'ID1007', 0.7, 80 - 30, -30, 'ID1008', 0.8, 80 - 30, -30, 'ID1009', 0.9, 80 - 30, -30, 'ID1010', 1.0, 80 - 30, -30)"
},
{
"code": null,
"e": 49504,
"s": 49263,
"text": "I use purrr to map the expected_profit_func() to each customer, returning a data frame of expected cost per customer by threshold value. This operation creates a nester tibble, which I have to unnest() to expand the data frame to one level."
},
{
"code": null,
"e": 49844,
"s": 49504,
"text": "# calculate expected cost for each at each thresholdexpected_profit_ten_cust <- ten_cust %>% # pmap to map expected_profit_func() to each item mutate(expected_profit = pmap(.l = list(p1, cb_tp, cb_fp), .f = expected_profit_func)) %>% unnest() %>% select(cust, p1, threshold, expected_profit)"
},
{
"code": null,
"e": 49910,
"s": 49844,
"text": "Then, I can visualize the expected cost curves for each customer."
},
{
"code": null,
"e": 50286,
"s": 49910,
"text": "# Visualising Expected Cost expected_profit_ten_cust %>% ggplot(aes(threshold, expected_profit, colour = factor(cust)), group = cust) + geom_line(size = 1) + theme_minimal() + tidyquant::scale_color_tq() + labs(title = \"Expected Profit Curves\", colour = \"Customer No.\" ) + theme(plot.title = element_text(hjust = 0.5))"
},
{
"code": null,
"e": 50393,
"s": 50286,
"text": "Finally, I can aggregate the expected cost, visualise the final curve and highlight the optimal threshold."
},
{
"code": null,
"e": 51203,
"s": 50393,
"text": "# Aggregate expected cost by threshold total_expected_profit_ten_cust <- expected_profit_ten_cust %>% group_by(threshold) %>% summarise(expected_profit_total = sum(expected_profit)) # Get maximum optimal threshold max_expected_profit <- total_expected_profit_ten_cust %>% filter(expected_profit_total == max(expected_profit_total))# Visualize the total expected profit curvetotal_expected_profit_ten_cust %>% ggplot(aes(threshold, expected_profit_total)) + geom_line(size = 1) + geom_vline(xintercept = max_expected_profit$threshold) + theme_minimal() + labs(title = \"Expected Profit Curve - Total Expected Profit\", caption = paste0('threshold @ max = ', max_expected_profit$threshold %>% round(3))) + theme(plot.title = element_text(hjust = 0.5))"
},
{
"code": null,
"e": 51468,
"s": 51203,
"text": "This has some important business implications. Based on our hypothetical 10-customer group, choosing the optimised threshold of 0.092 would yield a total profit of nearly £164 compared to the nearly £147 associated with the automatically selected cut-off of 0.190."
},
{
"code": null,
"e": 51700,
"s": 51468,
"text": "This would result in an additional expected profit of nearly £1.7 per customer. Assuming that we have a customer base of approximately 500,000, switching to the optimised model could generate an additional expected profit of £850k!"
},
{
"code": null,
"e": 51995,
"s": 51700,
"text": "total_expected_profit_ten_cust %>% slice(184, 121) %>% round(3) %>% mutate(diff = expected_profit_total - lag(expected_profit_total)) %>% kable()threshold expected_profit_total diff 0.190 146.821 NA 0.092 163.753 16.932"
},
{
"code": null,
"e": 52126,
"s": 51995,
"text": "It is easy to see that, depending on the size of your business, the magnitude of potential profit increase could be a significant."
},
{
"code": null,
"e": 52311,
"s": 52126,
"text": "In this project, I’ve used a publicly available dataset to estimate the likelihood of a bank’s existing customers to purchase a financial product following a direct marketing campaign."
},
{
"code": null,
"e": 52811,
"s": 52311,
"text": "Following a thorough exploration and cleansing of the data, I estimate several models and compare their performance and fit to the data using the DALEX library, which focuses on Model-Agnostic Interpretability. One of its key advantages is the ability to compare contributions of traditional “glass-box” models as well as black-box models on the same scale. However, being permutation-based, one of its main drawbacks is that it does not scale well to large number of predictors and larger datasets."
},
{
"code": null,
"e": 53194,
"s": 52811,
"text": "Lastly, I take my final model and implemented a multi-customer profit optimization that reveals a potential additional expected profit of nearly £1.7 per customer (or £850k if you had a 500,000 customer base). Furthermore, I discuss key concepts like the threshold and F1 score and the precision-recall tradeoff and explain why it’s highly important to decide which cutoff to adopt."
},
{
"code": null,
"e": 53442,
"s": 53194,
"text": "After exploring and cleansing the data, fitting and comparing multiple models and choosing the best one, sticking with the default threshold @ Max F1 would be stopping short of the ultimate “so what?” that puts all that hard work into prospective."
},
{
"code": null,
"e": 53520,
"s": 53442,
"text": "One final thing: don’t forget to shut-down the h2o instance when you’re done!"
},
{
"code": null,
"e": 53560,
"s": 53520,
"text": "h2o.shutdown(prompt = FALSE)## [1] TRUE"
},
{
"code": null,
"e": 53656,
"s": 53560,
"text": "The full R code and all relevant files can be found on my GitHub profile @ Propensity Modelling"
},
{
"code": null,
"e": 53834,
"s": 53656,
"text": "For the original paper that used the data set see: A Data-Driven Approach to Predict the Success of Bank Telemarketing. Decision Support Systems, S. Moro, P. Cortez and P. Rita."
},
{
"code": null,
"e": 53912,
"s": 53834,
"text": "To Speed Up Exploratory Data Analysis see: correlationfunnel Package Vignette"
},
{
"code": null,
"e": 54049,
"s": 53912,
"text": "For a technically rigorous but applied take on Machine Learning Interpretability see Bradley Boehmke’s Model Interpretability with DALEX"
},
{
"code": null,
"e": 54261,
"s": 54049,
"text": "For a in-depth look at tools and techniques to examine fully-trained machine-learning models and compare their performance in a model-agnostic framework see: Explanatory Model Analysis, P. Biecek, T. Burzykowski"
},
{
"code": null,
"e": 54453,
"s": 54261,
"text": "For an advanced tutorial on sales forecasting and product backorders optimisation see Matt Dancho’s Predictive Sales Analytics: Use Machine Learning to Predict and Optimize Product Backorders"
},
{
"code": null,
"e": 54517,
"s": 54453,
"text": "For the Expected Value Framework see: Data Science for Business"
}
] |
How to load and use static files in Django? - GeeksforGeeks
|
16 Mar, 2021
Static Files such as Images, CSS or JS files are often loaded via a different app in production websites to avoid loading multiple stuff from the same server. This article revolves arouund, how you can setup static app in Django and server Static Files from the same.
let’s create a new project first for that let’s create a virtual environment first. Download the package if you haven’t downloaded it
pip install virtualenv
virtualenv geeks
geeks\Scripts\Activate
This is how it will look
now install Django
pip install django
now we will create our django project with the name “checkstatic”
//django-admin startproject projectname (template code)
django-admin startproject checkstatic
now enter your project
for windows “cd checkstatic”
now we will create a new app name “showstatic” for the project
//python3 manage.py startapp appname (template code)
python3 manage.py startapp showstatic
now we will walk in the IDE, I am using Visual studio code if you are using same the type (code .) in cmd
the first thing we would do is in setting.py add your app in line 32 add like this (you will see this from the apps.py file of the app)
INSTALLED_APPS = [
'showstatic.apps.ShowstaticConfig',
'django.contrib.admin',
'django.contrib.auth,
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
now try to runserver once to confirm everything is working smoothly
python3 manage.py runserver
if you see this page the congrats you taken your first step successfully
Now we create a static folder inside the main folder (checkstatic) where we will keep our static files. One can add your files (pdf, images, text files, or anything you want) in the static folder.
Folder structure –
now you need to make Django know that you have created a static folder so now add this line in settings.py file,
in line 121 below STATIC_URL = ‘/static/’
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Now tell django to look where for the static files you have added write this above STATIC_URL = ‘/static/’
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'checkstatic/static/')
]
Now we will write a command that will bring/collect all the static files from our project and bring it to one single folder
python manage.py collectstatic
this is how it will look if everything was fine, most of the files are from admin we don’t need to worry about it,
in your project folder, you will see a new folder added named “static” and your file is inside it!!
Now to check just create the “templates” folder in showstatic and create a file name home.html to view our static files
{% load static %}
<img src = "{% static 'logo.png' %}" height="200" width="200" class="d-inline-block align-top">
<br>
<h1>Hi its working</h1>
now to view this page we need to give a route for it so now just add this in url.py of checkstatic
from django.contrib import admin
from django.urls import path
from showstatic import views
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.home,name='home'),
]
and in views.py of showstatic add this
def home(request):
return render(request,'home.html')
now run the server and see
python3 manage.py runserver
Bingo its working!!
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python
|
[
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n16 Mar, 2021"
},
{
"code": null,
"e": 24169,
"s": 23901,
"text": "Static Files such as Images, CSS or JS files are often loaded via a different app in production websites to avoid loading multiple stuff from the same server. This article revolves arouund, how you can setup static app in Django and server Static Files from the same."
},
{
"code": null,
"e": 24304,
"s": 24169,
"text": " let’s create a new project first for that let’s create a virtual environment first. Download the package if you haven’t downloaded it"
},
{
"code": null,
"e": 24367,
"s": 24304,
"text": "pip install virtualenv\nvirtualenv geeks\ngeeks\\Scripts\\Activate"
},
{
"code": null,
"e": 24392,
"s": 24367,
"text": "This is how it will look"
},
{
"code": null,
"e": 24411,
"s": 24392,
"text": "now install Django"
},
{
"code": null,
"e": 24430,
"s": 24411,
"text": "pip install django"
},
{
"code": null,
"e": 24496,
"s": 24430,
"text": "now we will create our django project with the name “checkstatic”"
},
{
"code": null,
"e": 24591,
"s": 24496,
"text": "//django-admin startproject projectname (template code)\ndjango-admin startproject checkstatic"
},
{
"code": null,
"e": 24614,
"s": 24591,
"text": "now enter your project"
},
{
"code": null,
"e": 24644,
"s": 24614,
"text": "for windows “cd checkstatic”"
},
{
"code": null,
"e": 24707,
"s": 24644,
"text": "now we will create a new app name “showstatic” for the project"
},
{
"code": null,
"e": 24798,
"s": 24707,
"text": "//python3 manage.py startapp appname (template code)\npython3 manage.py startapp showstatic"
},
{
"code": null,
"e": 24904,
"s": 24798,
"text": "now we will walk in the IDE, I am using Visual studio code if you are using same the type (code .) in cmd"
},
{
"code": null,
"e": 25040,
"s": 24904,
"text": "the first thing we would do is in setting.py add your app in line 32 add like this (you will see this from the apps.py file of the app)"
},
{
"code": null,
"e": 25258,
"s": 25040,
"text": "INSTALLED_APPS = [\n'showstatic.apps.ShowstaticConfig',\n'django.contrib.admin',\n'django.contrib.auth,\n'django.contrib.contenttypes',\n'django.contrib.sessions',\n'django.contrib.messages',\n'django.contrib.staticfiles',\n]"
},
{
"code": null,
"e": 25326,
"s": 25258,
"text": "now try to runserver once to confirm everything is working smoothly"
},
{
"code": null,
"e": 25354,
"s": 25326,
"text": "python3 manage.py runserver"
},
{
"code": null,
"e": 25427,
"s": 25354,
"text": "if you see this page the congrats you taken your first step successfully"
},
{
"code": null,
"e": 25625,
"s": 25427,
"text": "Now we create a static folder inside the main folder (checkstatic) where we will keep our static files. One can add your files (pdf, images, text files, or anything you want) in the static folder."
},
{
"code": null,
"e": 25645,
"s": 25625,
"text": "Folder structure – "
},
{
"code": null,
"e": 25758,
"s": 25645,
"text": "now you need to make Django know that you have created a static folder so now add this line in settings.py file,"
},
{
"code": null,
"e": 25800,
"s": 25758,
"text": "in line 121 below STATIC_URL = ‘/static/’"
},
{
"code": null,
"e": 25847,
"s": 25800,
"text": "STATIC_ROOT = os.path.join(BASE_DIR, 'static')"
},
{
"code": null,
"e": 25954,
"s": 25847,
"text": "Now tell django to look where for the static files you have added write this above STATIC_URL = ‘/static/’"
},
{
"code": null,
"e": 26026,
"s": 25954,
"text": "STATICFILES_DIRS = [\n os.path.join(BASE_DIR, 'checkstatic/static/')\n]"
},
{
"code": null,
"e": 26150,
"s": 26026,
"text": "Now we will write a command that will bring/collect all the static files from our project and bring it to one single folder"
},
{
"code": null,
"e": 26181,
"s": 26150,
"text": "python manage.py collectstatic"
},
{
"code": null,
"e": 26296,
"s": 26181,
"text": "this is how it will look if everything was fine, most of the files are from admin we don’t need to worry about it,"
},
{
"code": null,
"e": 26396,
"s": 26296,
"text": "in your project folder, you will see a new folder added named “static” and your file is inside it!!"
},
{
"code": null,
"e": 26516,
"s": 26396,
"text": "Now to check just create the “templates” folder in showstatic and create a file name home.html to view our static files"
},
{
"code": null,
"e": 26659,
"s": 26516,
"text": "{% load static %}\n<img src = \"{% static 'logo.png' %}\" height=\"200\" width=\"200\" class=\"d-inline-block align-top\">\n<br>\n<h1>Hi its working</h1>"
},
{
"code": null,
"e": 26758,
"s": 26659,
"text": "now to view this page we need to give a route for it so now just add this in url.py of checkstatic"
},
{
"code": null,
"e": 26939,
"s": 26758,
"text": "from django.contrib import admin\nfrom django.urls import path\nfrom showstatic import views\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('',views.home,name='home'),\n]"
},
{
"code": null,
"e": 26980,
"s": 26939,
"text": " and in views.py of showstatic add this "
},
{
"code": null,
"e": 27037,
"s": 26980,
"text": "def home(request):\n return render(request,'home.html')"
},
{
"code": null,
"e": 27065,
"s": 27037,
"text": " now run the server and see"
},
{
"code": null,
"e": 27093,
"s": 27065,
"text": "python3 manage.py runserver"
},
{
"code": null,
"e": 27113,
"s": 27093,
"text": "Bingo its working!!"
},
{
"code": null,
"e": 27127,
"s": 27113,
"text": "Python Django"
},
{
"code": null,
"e": 27134,
"s": 27127,
"text": "Python"
},
{
"code": null,
"e": 27232,
"s": 27134,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27241,
"s": 27232,
"text": "Comments"
},
{
"code": null,
"e": 27254,
"s": 27241,
"text": "Old Comments"
},
{
"code": null,
"e": 27286,
"s": 27254,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27342,
"s": 27286,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27384,
"s": 27342,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27426,
"s": 27384,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27462,
"s": 27426,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 27501,
"s": 27462,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27523,
"s": 27501,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27554,
"s": 27523,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27581,
"s": 27554,
"text": "Python Classes and Objects"
}
] |
Represent Int64 as a Hexadecimal String in C#
|
To represent Int64 as a Binary string in C#, use the ToString() method and set the base as the ToString() method’s second parameter i.e.16 for Hexadecimal.
Int64 represents a 64-bit signed integer.
Firstly, set an Int64 variable.
long val = 947645;
Now, convert it to a hex string by including 16 as the second parameter.
Convert.ToString(val, 16)
Live Demo
using System;
class Demo {
static void Main() {
long val = 947645;
Console.WriteLine("Long: "+val);
Console.Write("Hex String: "+Convert.ToString(val, 16));
}
}
Long: 947645
Hex String: e75bd
|
[
{
"code": null,
"e": 1218,
"s": 1062,
"text": "To represent Int64 as a Binary string in C#, use the ToString() method and set the base as the ToString() method’s second parameter i.e.16 for Hexadecimal."
},
{
"code": null,
"e": 1260,
"s": 1218,
"text": "Int64 represents a 64-bit signed integer."
},
{
"code": null,
"e": 1292,
"s": 1260,
"text": "Firstly, set an Int64 variable."
},
{
"code": null,
"e": 1311,
"s": 1292,
"text": "long val = 947645;"
},
{
"code": null,
"e": 1384,
"s": 1311,
"text": "Now, convert it to a hex string by including 16 as the second parameter."
},
{
"code": null,
"e": 1410,
"s": 1384,
"text": "Convert.ToString(val, 16)"
},
{
"code": null,
"e": 1420,
"s": 1410,
"text": "Live Demo"
},
{
"code": null,
"e": 1605,
"s": 1420,
"text": "using System;\nclass Demo {\n static void Main() {\n long val = 947645;\n Console.WriteLine(\"Long: \"+val);\n Console.Write(\"Hex String: \"+Convert.ToString(val, 16));\n }\n}"
},
{
"code": null,
"e": 1636,
"s": 1605,
"text": "Long: 947645\nHex String: e75bd"
}
] |
Python - noise() function in Wand - GeeksforGeeks
|
08 May, 2020
Image noise is random variation of brightness or color information in images, and is usually an aspect of electronic noise. We can add noise to the image using noise() function. noise function can be useful when applied before a blur operation to defuse an image.
Following are the noise we can add using noise() function:
gaussian
impulse
laplacian
multiplicative_gaussian
poisson
random
uniform
Syntax :
wand.image.noise(noise_type, attenuate, channel)
Parameters :
Source Image:
Example 1:
# Import Image from wand.image modulefrom wand.image import Image # Read image using Image() functionwith Image(filename ="koala.jpeg") as img: # Generate noise image using spread() function img.noise("poisson", attenuate = 0.9) img.save(filename ="noisekoala.jpeg")
Output:
Example 2:
# Import Image from wand.image modulefrom wand.image import Image # Read image using Image() functionwith Image(filename ="koala.jpeg") as img: # Generate noise image using spread() function img.noise("laplacian", attenuate = 1.0) img.save(filename ="noisekoala2.jpeg")
Output:
Python-wand
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
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
Selecting rows in pandas DataFrame based on conditions
|
[
{
"code": null,
"e": 24186,
"s": 24158,
"text": "\n08 May, 2020"
},
{
"code": null,
"e": 24450,
"s": 24186,
"text": "Image noise is random variation of brightness or color information in images, and is usually an aspect of electronic noise. We can add noise to the image using noise() function. noise function can be useful when applied before a blur operation to defuse an image."
},
{
"code": null,
"e": 24509,
"s": 24450,
"text": "Following are the noise we can add using noise() function:"
},
{
"code": null,
"e": 24518,
"s": 24509,
"text": "gaussian"
},
{
"code": null,
"e": 24526,
"s": 24518,
"text": "impulse"
},
{
"code": null,
"e": 24536,
"s": 24526,
"text": "laplacian"
},
{
"code": null,
"e": 24560,
"s": 24536,
"text": "multiplicative_gaussian"
},
{
"code": null,
"e": 24568,
"s": 24560,
"text": "poisson"
},
{
"code": null,
"e": 24575,
"s": 24568,
"text": "random"
},
{
"code": null,
"e": 24583,
"s": 24575,
"text": "uniform"
},
{
"code": null,
"e": 24592,
"s": 24583,
"text": "Syntax :"
},
{
"code": null,
"e": 24642,
"s": 24592,
"text": "wand.image.noise(noise_type, attenuate, channel)\n"
},
{
"code": null,
"e": 24655,
"s": 24642,
"text": "Parameters :"
},
{
"code": null,
"e": 24669,
"s": 24655,
"text": "Source Image:"
},
{
"code": null,
"e": 24680,
"s": 24669,
"text": "Example 1:"
},
{
"code": "# Import Image from wand.image modulefrom wand.image import Image # Read image using Image() functionwith Image(filename =\"koala.jpeg\") as img: # Generate noise image using spread() function img.noise(\"poisson\", attenuate = 0.9) img.save(filename =\"noisekoala.jpeg\")",
"e": 24959,
"s": 24680,
"text": null
},
{
"code": null,
"e": 24967,
"s": 24959,
"text": "Output:"
},
{
"code": null,
"e": 24978,
"s": 24967,
"text": "Example 2:"
},
{
"code": "# Import Image from wand.image modulefrom wand.image import Image # Read image using Image() functionwith Image(filename =\"koala.jpeg\") as img: # Generate noise image using spread() function img.noise(\"laplacian\", attenuate = 1.0) img.save(filename =\"noisekoala2.jpeg\")",
"e": 25260,
"s": 24978,
"text": null
},
{
"code": null,
"e": 25268,
"s": 25260,
"text": "Output:"
},
{
"code": null,
"e": 25280,
"s": 25268,
"text": "Python-wand"
},
{
"code": null,
"e": 25287,
"s": 25280,
"text": "Python"
},
{
"code": null,
"e": 25385,
"s": 25287,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25394,
"s": 25385,
"text": "Comments"
},
{
"code": null,
"e": 25407,
"s": 25394,
"text": "Old Comments"
},
{
"code": null,
"e": 25425,
"s": 25407,
"text": "Python Dictionary"
},
{
"code": null,
"e": 25460,
"s": 25425,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 25482,
"s": 25460,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 25514,
"s": 25482,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25544,
"s": 25514,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 25586,
"s": 25544,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 25612,
"s": 25586,
"text": "Python String | replace()"
},
{
"code": null,
"e": 25649,
"s": 25612,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 25692,
"s": 25649,
"text": "Python program to convert a list to string"
}
] |
A True End-to-End ML Example: Lead Scoring | by Adam Barnhard | Towards Data Science
|
Selling something can be hard work. A business might have many potential customers leads but most of those customers won’t turn into actual, paying customers in the end. A sales team has to sort through a long list of potential customers and figure out how to spend their time. That’s where lead scoring comes in. This is a system that analyzes attributes about each new lead in relation to the chances of that lead actually becoming a customer, and uses that analysis to score and rank all of the potential customers. With that new ranking, the sales team can then prioritize their time, and only spend time on the leads that are highly likely to become paying customers.
Cool, that sounds great! How do I do it?
Well, I’m glad you asked! In this post, we will walk through the full end-to-end implementation of a custom built lead-scoring model. This includes pulling the data, building the model, deploying that model, and finally pushing those results directly to where they matter most — the tools that a sales team uses.
If you want to test out this model without going through the full process, we have a fully-functioning lead scoring model on Booklet.ai. We’ve posted all code, in the form of a Jupyter Notebook on GitHub.
This will be a technical tutorial that requires a bit of coding and data science understanding to get through. To get the most out of this, you should have at least a bit of exposure to:
Python (we will stay within Jupyter notebooks the whole time)
Machine Learning (we will use a Random Forest model)
The command line (yes, it can be scary, but we just use a few simple commands)
AWS (we can hold your hand through this one!)
Also, you should have a few things installed to make sure you can move quickly through the tutorial:
An AWS username with access through awscli (we will cover this below!)
Python 3 of some kind with a few packages:
Pandas pip install pandas
MLflow pip install mlflow
SKlearn pip install scikit-learn
Docker (pretty quick and easy to install here)
We’re going to touch on a lot of tools and ideas in a short amount of time. Before we dive right in, it’s important to take a step back to understand what’s happening here. There are a few tools that we will be using:
Jupyter Notebook: A go-to for data scientists. Allows you to run python scripts in the form of a notebook and get results in-line.
MLflow: An open source model management system.
Sagemaker: A full-stack machine learning platform from AWS.
Booklet.ai: A model testing and integration system.
Intercom: A customer messaging platform that is commonly used by customer service and sales teams to manage customer relationships.
Here is a diagram that outlines how these different tools are used:
At the highest level, we will use a Jupyter notebook to pull leads data and train a model. Next, we will send that model to MLflow to keep track of the model version. Then, we will send both a docker container and the model into AWS Sagemaker to deploy the model. Finally, we will use Booklet to put that model to use and start piping lead scores into Intercom.
Now that we got that out of the way, let’s get started!
First, we need to access data about our leads. This data should have two types of information:
(A) The response variable: Whether or not the lead converted into a paying customer
(B) The features: Details about each lead that will help us the response variable
For this exercise, we are going to use an example leads dataset from Kaggle. This dataset provides a large list of simulated leads for a company called X Education, which sells online courses. We have a variety of features for each lead as well as whether or not that lead converted into a paying customer. Thanks Ashish for providing this dataset and for the awesome analysis on Kaggle.
To import this data, simply read the leads_cleaned dataset into Pandas. If you are reading this data from a database instead, replace this with pd.read_sql_query instead.
Next, we want to pick out a few columns that matter to us. To do that, we will create lists of columns that fit into different categories: numeric, categorical, and the response variable. This will make the processing and cleaning processing easier.
From here, we can create our train/test datasets that will be used for training:
Now that we have a test dataset, let’s go ahead and create a scaler for our numeric variables. It is important to only run this on the training dataset so that we don’t “leak” any information about the test set.
Now, we need to make some adjustments to the model to prepare for modeling. We’ve created a function to perform a few things:
Select the columns that we’ve defined as important
Use the fitted scaler to center and scale the numeric columns
Turn categorical variables into one-hot encoded variables
Ensure that all columns from the training dataset are also in the outputted, processed dataset (This is important so that all levels of dummy variables are created, even if the dataset we import doesn’t have each individual level.)
Here’s how it looks when we put it all together and run both the training and test dataset through our preprocessing function:
This bring us to the exciting part! Let’s use our newly cleaned and split datasets to train a random forest model that predicts the chances of someone converting into a paying customer of X Education. First, let’s define a few standard hyperparameters and initialize the SKLearn model:
From here, we can quickly calculate a few accuracy metrics in our test set to see how the model did.
We have an accuracy of 82% and an AUC score of 80% in our held-out test set! Not too shabby. There is definitely room to improve, but for the sake of this tutorial, let’s move forward with this model.
Before we go setting this up, let’s have a quick chat about MLflow. Officially, MLflow is “An open source platform for the machine learning lifecycle.” Databricks developed this open source project to help machine learning builders more easily manage and deploy machine learning models. Let’s break that down:
Managing models: While building an ML model, you will likely go through multiple iterations and test a variety of model types. It’s important to keep track of metadata about those tests as well as the model objects themselves. What if you discover an awesome model on your 2nd of 100 tries and want to go back to use that? MLflow has you covered!
Deploying models: In order to make a model accessible, you need to deploy the model. This means hosting your model as an API endpoint, so that it is easy to reference and score against your model in a standard way. There is a super long list of tools that deploy models for you. MLflow isn’t actually one of those tools. Instead, MLflow allows easy deployment of your managed model to a variety of different tools. It could be on your local machine, Microsoft Azure, or AWS Sagemaker. We will use Sagemaker in this tutorial.
The MLflow tracking server is a nice UI and API that wraps around the important features. We will need to set this up before we can use MLflow to start managing and deploying models.
Make sure you have the MLflow package installed (check out the Pre-reqs if not!). From there, run the following command in your terminal:
mlflow ui
After this, you should see the shiny new UI running at http://localhost:5000/
If you run into issues getting this setup, check out the MLflow tracking server docs here. Also, if you’d prefer not to setup the tracking server on your own machine, Databricks offers a free hosted version as well.
Once you have the tracking server running, let’s point Python to our tracking server and setup an experiment. An experiment is a collection of models inside of the MLflow tracking server.
If you are working with a model that has no preprocessing associated with your data, logging the model is fairly simple. In our case, we actually need to setup this preprocessing logic alongside the model itself. This will allow leads to be sent to our model as-is and the model will handle the data prep. A quick visual to show this:
To do this, we will utilize MLflow’s pyfunc model-type (more info here) which allows us to wrap up both a model and the preprocessing logic into one nice Python class. We will need to send two different inputs to this class: objects (i.e. list of columns that are numeric or the random forest model itself) and logic (i.e. preprocessing function that we created). Both of these entities will be used inside the class.
Now, let’s setup the class. First, check out the code and then we will talk through the different pieces:
The class leadsModel by based on MLflow’s pyfunc class. This will allow us to push this model into MLflow and eventually Sagemaker.
Next we setup all of the objects that we need within the __init__. This contains both the objects and the logic function.
Finally, we setup the predict function:
First, we take in the model_input (which is the dataframe that is sent to the deployed object after deployment) and ensure that all of the column names are lowercase.
Next, we send this dataframe into the preprocessing function that we had created and used earlier for model training. This time, we keep the response columns blank since we won’t need them for deployment!
Then, we reference the original training dataset’s column names and fill in any missing columns with 0’s. This is important since we will have levels of on-hot-encoded variables that aren’t calculated when we send datasets to the model after deployment.
Finally, we send this nice, clean dataset to our Random Forest model for prediction.
Now that we have all of our logic and objects ready to go within one class, we can log this model into MLflow!
Before we package everything up and log the model, we need to setup the Anaconda environment that will be used when the model runs on Sagemaker. For more information about Anaconda, here’s a detailed overview.
Now, we start a run within MLflow. Within that run, we log our hyperparameters, accuracy metrics, and finally the model itself!
If you head over to the MLflow UI that we checked out earlier, you’ll see the newly created model along with all of the metrics and parameters that we just defined. Woot woot!
Sagemaker is a suite of tools that Amazon Web Services (AWS) created to support Machine Learning development and deployment. There’s a ton of tools available within Sagemaker (too many to list here) and we will be using their model deployment tool specifically. There are some great Sagemaker examples in their GitHub repo here.
First things first, you need to get permissions worked out. AWS permissions are never simple, but we will try to keep this easy! You’ll need to setup two different settings: a user for yourself and a role for Sagemaker.
The first is a user account so that you can access AWS as you send the model to Sagemaker. To do this, you’ll need to head over to the Identity and Access Management (IAM) console and setup a user account with Administrator permissions. If your security team pushes back, “Sagemaker Full Access” should work too! At the end of the setup flow, you’ll be given an AWS Access Key ID and a AWS Secret Access Key. Make sure to save those! They are not accessible after that first time. Now, head to your terminal and type aws configure. This will prompt you to enter your AWS keys that you just collected. Once you have that setup, you’ll now have AWS access from both the terminal and from Python! Here are more details from AWS.
The second is a role (which is essentially a user account for services within AWS) for Sagemaker. To set this up, head to the roles section of IAM. You’ll want to assign this role to Sagemaker and then pick the policy called “SagemakerFullAccess.” At the end of this process, you’ll get something called an ARN for this role! We’ll need this for deployment so keep this handy. More details from AWS here.
Finally, we need to push an MLflow docker container into AWS. Assuming you have the permissions setup correctly above and docker installed (see prerequisites section for docker setup), you’ll want to run the following command in your terminal:
mlflow sagemaker build-and-push-container
This will push a docker container into AWS, which will be used during deployment.
Now that we have everything setup, it’s time to push our model to Sagemaker!
The deploy function usually takes a 5 to 10 minutes to complete and the status is checked every so often with this function until completion. Once the deployment is complete, you’ll be able to find a running model in the Sagemaker UI!
Congrats, your model is now deployed! Our next goal is to make this model helpful to the sales team. To do that, we’ll want to use the deployed model to create lead scores for new sales leads and send those results to the tools that the sales team uses. We now need to create a system that regularly pulls in new sales leads, sends each lead’s info to our deployed model, and then send those model results to Intercom, the sales team’s tool.
There are a few custom-built ways to set this up:
We can setup a custom Python script that regularly collects new Intercom user data in our data warehouse, sends that data to our deployed endpoint using the Sagemaker Python SDK, and then sends the results back to Intercom with their API.
We can utilize Sagemaker’s Batch Transform functionality (great example here) to score batches of Intercom users. All data starts and ends in S3 for batch transform, so we’ll need to pull data into S3 for scoring, and then push data from S3 to Intercom to serve that up to sales teams
We knew there had to be a more efficient way to push the model results into the tools where they are most useful, so we built Booklet.ai to make these steps easier.
Booklet adds a web testing interface and data integrations to each of your Machine Learning endpoints, without requiring code changes. With Booklet, you can quickly try out model test-cases to ensure results are performing as expected, as well as send these results to the tools that matter most. For a lead scoring model, we can send results back to our data warehouse (Redshift in this case) or the sale’s team’s tool (Intercom).
Using Booklet, we quickly setup a demo to test the lead scoring model. This is connected to the endpoint that we created in this tutorial so far. You can try out different inputs and see how the model classifies each theoretical lead. To build a web app yourself, you can sign up for Booklet for free and check out the getting started documentation.
Once you feel comfortable with the output of the model from testing, you can start sending those results to systems where that output is most useful. We’ve already set up our source in Redshift, which pulls data to feed into the model. We’ve also setup both a Redshift destination and an Intercom destination, where the results will be sent. To kick off an example dataflow, which pulls data from the source, scores that data with the model, and sends results to both destinations, you can try out a dataflow here.
Tada! We’ve now made our lead scoring model impactful by sending results directly into Intercom. To get a sense of how this might show up for a sales team member, here you can see each example lead now has a custom attribute listing whether or not they are likely to convert:
With these labels easily available for each potential lead, a sales team member can start to prioritize their time and pick who they will reach out to first. This will hopefully lead to better efficiency, and more sales for your business! There are many ways to measure the success of these outcomes, but we’ll visit that at another time!
If you’ve made it this far, thank you! You’ve successfully navigated an entire end-to-end machine learning project. From idea inception to business impact, and all of the steps in between. If you have any thoughts, questions, or run into issues as you follow along, please drop in a comment below.
A big thank you to Ashish for the dataset, Bing for a helpful review, and Kyle for an awesome blog to reference on MLflow and Sagemaker.
|
[
{
"code": null,
"e": 844,
"s": 171,
"text": "Selling something can be hard work. A business might have many potential customers leads but most of those customers won’t turn into actual, paying customers in the end. A sales team has to sort through a long list of potential customers and figure out how to spend their time. That’s where lead scoring comes in. This is a system that analyzes attributes about each new lead in relation to the chances of that lead actually becoming a customer, and uses that analysis to score and rank all of the potential customers. With that new ranking, the sales team can then prioritize their time, and only spend time on the leads that are highly likely to become paying customers."
},
{
"code": null,
"e": 885,
"s": 844,
"text": "Cool, that sounds great! How do I do it?"
},
{
"code": null,
"e": 1198,
"s": 885,
"text": "Well, I’m glad you asked! In this post, we will walk through the full end-to-end implementation of a custom built lead-scoring model. This includes pulling the data, building the model, deploying that model, and finally pushing those results directly to where they matter most — the tools that a sales team uses."
},
{
"code": null,
"e": 1403,
"s": 1198,
"text": "If you want to test out this model without going through the full process, we have a fully-functioning lead scoring model on Booklet.ai. We’ve posted all code, in the form of a Jupyter Notebook on GitHub."
},
{
"code": null,
"e": 1590,
"s": 1403,
"text": "This will be a technical tutorial that requires a bit of coding and data science understanding to get through. To get the most out of this, you should have at least a bit of exposure to:"
},
{
"code": null,
"e": 1652,
"s": 1590,
"text": "Python (we will stay within Jupyter notebooks the whole time)"
},
{
"code": null,
"e": 1705,
"s": 1652,
"text": "Machine Learning (we will use a Random Forest model)"
},
{
"code": null,
"e": 1784,
"s": 1705,
"text": "The command line (yes, it can be scary, but we just use a few simple commands)"
},
{
"code": null,
"e": 1830,
"s": 1784,
"text": "AWS (we can hold your hand through this one!)"
},
{
"code": null,
"e": 1931,
"s": 1830,
"text": "Also, you should have a few things installed to make sure you can move quickly through the tutorial:"
},
{
"code": null,
"e": 2002,
"s": 1931,
"text": "An AWS username with access through awscli (we will cover this below!)"
},
{
"code": null,
"e": 2045,
"s": 2002,
"text": "Python 3 of some kind with a few packages:"
},
{
"code": null,
"e": 2071,
"s": 2045,
"text": "Pandas pip install pandas"
},
{
"code": null,
"e": 2097,
"s": 2071,
"text": "MLflow pip install mlflow"
},
{
"code": null,
"e": 2130,
"s": 2097,
"text": "SKlearn pip install scikit-learn"
},
{
"code": null,
"e": 2177,
"s": 2130,
"text": "Docker (pretty quick and easy to install here)"
},
{
"code": null,
"e": 2395,
"s": 2177,
"text": "We’re going to touch on a lot of tools and ideas in a short amount of time. Before we dive right in, it’s important to take a step back to understand what’s happening here. There are a few tools that we will be using:"
},
{
"code": null,
"e": 2526,
"s": 2395,
"text": "Jupyter Notebook: A go-to for data scientists. Allows you to run python scripts in the form of a notebook and get results in-line."
},
{
"code": null,
"e": 2574,
"s": 2526,
"text": "MLflow: An open source model management system."
},
{
"code": null,
"e": 2634,
"s": 2574,
"text": "Sagemaker: A full-stack machine learning platform from AWS."
},
{
"code": null,
"e": 2686,
"s": 2634,
"text": "Booklet.ai: A model testing and integration system."
},
{
"code": null,
"e": 2818,
"s": 2686,
"text": "Intercom: A customer messaging platform that is commonly used by customer service and sales teams to manage customer relationships."
},
{
"code": null,
"e": 2886,
"s": 2818,
"text": "Here is a diagram that outlines how these different tools are used:"
},
{
"code": null,
"e": 3248,
"s": 2886,
"text": "At the highest level, we will use a Jupyter notebook to pull leads data and train a model. Next, we will send that model to MLflow to keep track of the model version. Then, we will send both a docker container and the model into AWS Sagemaker to deploy the model. Finally, we will use Booklet to put that model to use and start piping lead scores into Intercom."
},
{
"code": null,
"e": 3304,
"s": 3248,
"text": "Now that we got that out of the way, let’s get started!"
},
{
"code": null,
"e": 3399,
"s": 3304,
"text": "First, we need to access data about our leads. This data should have two types of information:"
},
{
"code": null,
"e": 3483,
"s": 3399,
"text": "(A) The response variable: Whether or not the lead converted into a paying customer"
},
{
"code": null,
"e": 3565,
"s": 3483,
"text": "(B) The features: Details about each lead that will help us the response variable"
},
{
"code": null,
"e": 3953,
"s": 3565,
"text": "For this exercise, we are going to use an example leads dataset from Kaggle. This dataset provides a large list of simulated leads for a company called X Education, which sells online courses. We have a variety of features for each lead as well as whether or not that lead converted into a paying customer. Thanks Ashish for providing this dataset and for the awesome analysis on Kaggle."
},
{
"code": null,
"e": 4124,
"s": 3953,
"text": "To import this data, simply read the leads_cleaned dataset into Pandas. If you are reading this data from a database instead, replace this with pd.read_sql_query instead."
},
{
"code": null,
"e": 4374,
"s": 4124,
"text": "Next, we want to pick out a few columns that matter to us. To do that, we will create lists of columns that fit into different categories: numeric, categorical, and the response variable. This will make the processing and cleaning processing easier."
},
{
"code": null,
"e": 4455,
"s": 4374,
"text": "From here, we can create our train/test datasets that will be used for training:"
},
{
"code": null,
"e": 4667,
"s": 4455,
"text": "Now that we have a test dataset, let’s go ahead and create a scaler for our numeric variables. It is important to only run this on the training dataset so that we don’t “leak” any information about the test set."
},
{
"code": null,
"e": 4793,
"s": 4667,
"text": "Now, we need to make some adjustments to the model to prepare for modeling. We’ve created a function to perform a few things:"
},
{
"code": null,
"e": 4844,
"s": 4793,
"text": "Select the columns that we’ve defined as important"
},
{
"code": null,
"e": 4906,
"s": 4844,
"text": "Use the fitted scaler to center and scale the numeric columns"
},
{
"code": null,
"e": 4964,
"s": 4906,
"text": "Turn categorical variables into one-hot encoded variables"
},
{
"code": null,
"e": 5196,
"s": 4964,
"text": "Ensure that all columns from the training dataset are also in the outputted, processed dataset (This is important so that all levels of dummy variables are created, even if the dataset we import doesn’t have each individual level.)"
},
{
"code": null,
"e": 5323,
"s": 5196,
"text": "Here’s how it looks when we put it all together and run both the training and test dataset through our preprocessing function:"
},
{
"code": null,
"e": 5609,
"s": 5323,
"text": "This bring us to the exciting part! Let’s use our newly cleaned and split datasets to train a random forest model that predicts the chances of someone converting into a paying customer of X Education. First, let’s define a few standard hyperparameters and initialize the SKLearn model:"
},
{
"code": null,
"e": 5710,
"s": 5609,
"text": "From here, we can quickly calculate a few accuracy metrics in our test set to see how the model did."
},
{
"code": null,
"e": 5911,
"s": 5710,
"text": "We have an accuracy of 82% and an AUC score of 80% in our held-out test set! Not too shabby. There is definitely room to improve, but for the sake of this tutorial, let’s move forward with this model."
},
{
"code": null,
"e": 6221,
"s": 5911,
"text": "Before we go setting this up, let’s have a quick chat about MLflow. Officially, MLflow is “An open source platform for the machine learning lifecycle.” Databricks developed this open source project to help machine learning builders more easily manage and deploy machine learning models. Let’s break that down:"
},
{
"code": null,
"e": 6568,
"s": 6221,
"text": "Managing models: While building an ML model, you will likely go through multiple iterations and test a variety of model types. It’s important to keep track of metadata about those tests as well as the model objects themselves. What if you discover an awesome model on your 2nd of 100 tries and want to go back to use that? MLflow has you covered!"
},
{
"code": null,
"e": 7093,
"s": 6568,
"text": "Deploying models: In order to make a model accessible, you need to deploy the model. This means hosting your model as an API endpoint, so that it is easy to reference and score against your model in a standard way. There is a super long list of tools that deploy models for you. MLflow isn’t actually one of those tools. Instead, MLflow allows easy deployment of your managed model to a variety of different tools. It could be on your local machine, Microsoft Azure, or AWS Sagemaker. We will use Sagemaker in this tutorial."
},
{
"code": null,
"e": 7276,
"s": 7093,
"text": "The MLflow tracking server is a nice UI and API that wraps around the important features. We will need to set this up before we can use MLflow to start managing and deploying models."
},
{
"code": null,
"e": 7414,
"s": 7276,
"text": "Make sure you have the MLflow package installed (check out the Pre-reqs if not!). From there, run the following command in your terminal:"
},
{
"code": null,
"e": 7424,
"s": 7414,
"text": "mlflow ui"
},
{
"code": null,
"e": 7502,
"s": 7424,
"text": "After this, you should see the shiny new UI running at http://localhost:5000/"
},
{
"code": null,
"e": 7718,
"s": 7502,
"text": "If you run into issues getting this setup, check out the MLflow tracking server docs here. Also, if you’d prefer not to setup the tracking server on your own machine, Databricks offers a free hosted version as well."
},
{
"code": null,
"e": 7906,
"s": 7718,
"text": "Once you have the tracking server running, let’s point Python to our tracking server and setup an experiment. An experiment is a collection of models inside of the MLflow tracking server."
},
{
"code": null,
"e": 8241,
"s": 7906,
"text": "If you are working with a model that has no preprocessing associated with your data, logging the model is fairly simple. In our case, we actually need to setup this preprocessing logic alongside the model itself. This will allow leads to be sent to our model as-is and the model will handle the data prep. A quick visual to show this:"
},
{
"code": null,
"e": 8659,
"s": 8241,
"text": "To do this, we will utilize MLflow’s pyfunc model-type (more info here) which allows us to wrap up both a model and the preprocessing logic into one nice Python class. We will need to send two different inputs to this class: objects (i.e. list of columns that are numeric or the random forest model itself) and logic (i.e. preprocessing function that we created). Both of these entities will be used inside the class."
},
{
"code": null,
"e": 8765,
"s": 8659,
"text": "Now, let’s setup the class. First, check out the code and then we will talk through the different pieces:"
},
{
"code": null,
"e": 8897,
"s": 8765,
"text": "The class leadsModel by based on MLflow’s pyfunc class. This will allow us to push this model into MLflow and eventually Sagemaker."
},
{
"code": null,
"e": 9019,
"s": 8897,
"text": "Next we setup all of the objects that we need within the __init__. This contains both the objects and the logic function."
},
{
"code": null,
"e": 9059,
"s": 9019,
"text": "Finally, we setup the predict function:"
},
{
"code": null,
"e": 9226,
"s": 9059,
"text": "First, we take in the model_input (which is the dataframe that is sent to the deployed object after deployment) and ensure that all of the column names are lowercase."
},
{
"code": null,
"e": 9431,
"s": 9226,
"text": "Next, we send this dataframe into the preprocessing function that we had created and used earlier for model training. This time, we keep the response columns blank since we won’t need them for deployment!"
},
{
"code": null,
"e": 9685,
"s": 9431,
"text": "Then, we reference the original training dataset’s column names and fill in any missing columns with 0’s. This is important since we will have levels of on-hot-encoded variables that aren’t calculated when we send datasets to the model after deployment."
},
{
"code": null,
"e": 9770,
"s": 9685,
"text": "Finally, we send this nice, clean dataset to our Random Forest model for prediction."
},
{
"code": null,
"e": 9881,
"s": 9770,
"text": "Now that we have all of our logic and objects ready to go within one class, we can log this model into MLflow!"
},
{
"code": null,
"e": 10091,
"s": 9881,
"text": "Before we package everything up and log the model, we need to setup the Anaconda environment that will be used when the model runs on Sagemaker. For more information about Anaconda, here’s a detailed overview."
},
{
"code": null,
"e": 10219,
"s": 10091,
"text": "Now, we start a run within MLflow. Within that run, we log our hyperparameters, accuracy metrics, and finally the model itself!"
},
{
"code": null,
"e": 10395,
"s": 10219,
"text": "If you head over to the MLflow UI that we checked out earlier, you’ll see the newly created model along with all of the metrics and parameters that we just defined. Woot woot!"
},
{
"code": null,
"e": 10724,
"s": 10395,
"text": "Sagemaker is a suite of tools that Amazon Web Services (AWS) created to support Machine Learning development and deployment. There’s a ton of tools available within Sagemaker (too many to list here) and we will be using their model deployment tool specifically. There are some great Sagemaker examples in their GitHub repo here."
},
{
"code": null,
"e": 10944,
"s": 10724,
"text": "First things first, you need to get permissions worked out. AWS permissions are never simple, but we will try to keep this easy! You’ll need to setup two different settings: a user for yourself and a role for Sagemaker."
},
{
"code": null,
"e": 11670,
"s": 10944,
"text": "The first is a user account so that you can access AWS as you send the model to Sagemaker. To do this, you’ll need to head over to the Identity and Access Management (IAM) console and setup a user account with Administrator permissions. If your security team pushes back, “Sagemaker Full Access” should work too! At the end of the setup flow, you’ll be given an AWS Access Key ID and a AWS Secret Access Key. Make sure to save those! They are not accessible after that first time. Now, head to your terminal and type aws configure. This will prompt you to enter your AWS keys that you just collected. Once you have that setup, you’ll now have AWS access from both the terminal and from Python! Here are more details from AWS."
},
{
"code": null,
"e": 12075,
"s": 11670,
"text": "The second is a role (which is essentially a user account for services within AWS) for Sagemaker. To set this up, head to the roles section of IAM. You’ll want to assign this role to Sagemaker and then pick the policy called “SagemakerFullAccess.” At the end of this process, you’ll get something called an ARN for this role! We’ll need this for deployment so keep this handy. More details from AWS here."
},
{
"code": null,
"e": 12319,
"s": 12075,
"text": "Finally, we need to push an MLflow docker container into AWS. Assuming you have the permissions setup correctly above and docker installed (see prerequisites section for docker setup), you’ll want to run the following command in your terminal:"
},
{
"code": null,
"e": 12361,
"s": 12319,
"text": "mlflow sagemaker build-and-push-container"
},
{
"code": null,
"e": 12443,
"s": 12361,
"text": "This will push a docker container into AWS, which will be used during deployment."
},
{
"code": null,
"e": 12520,
"s": 12443,
"text": "Now that we have everything setup, it’s time to push our model to Sagemaker!"
},
{
"code": null,
"e": 12755,
"s": 12520,
"text": "The deploy function usually takes a 5 to 10 minutes to complete and the status is checked every so often with this function until completion. Once the deployment is complete, you’ll be able to find a running model in the Sagemaker UI!"
},
{
"code": null,
"e": 13197,
"s": 12755,
"text": "Congrats, your model is now deployed! Our next goal is to make this model helpful to the sales team. To do that, we’ll want to use the deployed model to create lead scores for new sales leads and send those results to the tools that the sales team uses. We now need to create a system that regularly pulls in new sales leads, sends each lead’s info to our deployed model, and then send those model results to Intercom, the sales team’s tool."
},
{
"code": null,
"e": 13247,
"s": 13197,
"text": "There are a few custom-built ways to set this up:"
},
{
"code": null,
"e": 13486,
"s": 13247,
"text": "We can setup a custom Python script that regularly collects new Intercom user data in our data warehouse, sends that data to our deployed endpoint using the Sagemaker Python SDK, and then sends the results back to Intercom with their API."
},
{
"code": null,
"e": 13771,
"s": 13486,
"text": "We can utilize Sagemaker’s Batch Transform functionality (great example here) to score batches of Intercom users. All data starts and ends in S3 for batch transform, so we’ll need to pull data into S3 for scoring, and then push data from S3 to Intercom to serve that up to sales teams"
},
{
"code": null,
"e": 13936,
"s": 13771,
"text": "We knew there had to be a more efficient way to push the model results into the tools where they are most useful, so we built Booklet.ai to make these steps easier."
},
{
"code": null,
"e": 14368,
"s": 13936,
"text": "Booklet adds a web testing interface and data integrations to each of your Machine Learning endpoints, without requiring code changes. With Booklet, you can quickly try out model test-cases to ensure results are performing as expected, as well as send these results to the tools that matter most. For a lead scoring model, we can send results back to our data warehouse (Redshift in this case) or the sale’s team’s tool (Intercom)."
},
{
"code": null,
"e": 14718,
"s": 14368,
"text": "Using Booklet, we quickly setup a demo to test the lead scoring model. This is connected to the endpoint that we created in this tutorial so far. You can try out different inputs and see how the model classifies each theoretical lead. To build a web app yourself, you can sign up for Booklet for free and check out the getting started documentation."
},
{
"code": null,
"e": 15233,
"s": 14718,
"text": "Once you feel comfortable with the output of the model from testing, you can start sending those results to systems where that output is most useful. We’ve already set up our source in Redshift, which pulls data to feed into the model. We’ve also setup both a Redshift destination and an Intercom destination, where the results will be sent. To kick off an example dataflow, which pulls data from the source, scores that data with the model, and sends results to both destinations, you can try out a dataflow here."
},
{
"code": null,
"e": 15509,
"s": 15233,
"text": "Tada! We’ve now made our lead scoring model impactful by sending results directly into Intercom. To get a sense of how this might show up for a sales team member, here you can see each example lead now has a custom attribute listing whether or not they are likely to convert:"
},
{
"code": null,
"e": 15848,
"s": 15509,
"text": "With these labels easily available for each potential lead, a sales team member can start to prioritize their time and pick who they will reach out to first. This will hopefully lead to better efficiency, and more sales for your business! There are many ways to measure the success of these outcomes, but we’ll visit that at another time!"
},
{
"code": null,
"e": 16146,
"s": 15848,
"text": "If you’ve made it this far, thank you! You’ve successfully navigated an entire end-to-end machine learning project. From idea inception to business impact, and all of the steps in between. If you have any thoughts, questions, or run into issues as you follow along, please drop in a comment below."
}
] |
Cascading of Input/Output Operators in C++ - GeeksforGeeks
|
28 Dec, 2020
Prerequisite: Operator Overloading in C++, Types of Operator Overloading
When an object calls an operator function by passing an argument and the returned value of the operator function calls the next operator function in the same expression, it is called as cascading of operators. Below are the examples for illustration of Cascading Of Operations:
Program 1:
C++
// C++ program to illustrate the// cascading operators#include <iostream>using namespace std; // Height Classclass Height {private: int feet, inches; public: // Default Constructor Height() { feet = 0; inches = 0; } // Function to assign value to // the object of class Height void setData(int x, int y) { feet = x; inches = y; } // Function to print the object // of the class void showData() { cout << feet << "'" << inches; } // Function for overloading // of operator + Height operator+(Height H) { Height temp; // Add the feets temp.feet = feet + H.feet; // Add the inches temp.inches = inches + H.inches; return temp; } // Function to normalize the height // into proper terms of 1 feet // per 12 inches void normalize() { // Update the feets if (inches == 12 || inches > 12) { feet = feet + inches / 12; } // Update Inches inches = inches % 12; }}; // Driver Codeint main(){ Height h1, h2, h3, h4; // Initialize the three heights h1.setData(5, 9); h2.setData(5, 2); h3.setData(6, 2); // Add all the heights using // cascading of operators h4 = h1 + h2 + h3; // Normalize the heights h4.normalize(); // Print the height h4 h4.showData(); return 0;}
Explanation:In this code, Cascading of the operator is taking place here:
h4 = h1 + h2 + h3;
Here at first h1 object called (+) operator and passes h2 as an argument in the operator function call and the returned value of this operator function calls again (+) operator and passes h3 as an argument in the same expression, at last, the returned value of this second operator function is assigned in h4.
Program 2: The multiple uses of input or output operators (“>>” or ”<<”) in one statement is also an example of cascading of Input/Output operator.
cout is an object of predefined ostream class.
There are several insertions (“<<”) operator functions defined in ostream class for different primitive data types. For Non-primitive data types, you have to define them using the friend function.
Below is the program for overloading of ‘>>’ and ‘<<‘ operators, which takes a number N as an input continuously and insert the number N in the linked list until N = -1.
C++
// C++ program to demonstrate the// overloading of '<<' and '>>'// operators#include <iostream>using namespace std; // Class for each node object// of the linked listclass node {public: // Node of the linked list int data; node* next; // Constructor of node class node(int d) { data = d; next = NULL; }}; // Insert a node at head of linked// listvoid insertAtHead(node*& head, int d){ node* n = new node(d); n->next = head; head = n;} // Insert a node at tail of linked// listvoid insertAtTail(node* head, int data){ // Make new node using // constructor node* n = new node(data); node* temp = head; // Traverse till we get to end of // the linked list while (temp->next != NULL) temp = temp->next; // Append the new node n at the end // of the linked list temp->next = n;} // Print the node at the linked listvoid print(node* head){ // Print the first Node if (head != NULL) { cout << head->data; head = head->next; } // Traverse till head traverse // till end while (head != NULL) { cout << "->" << head->data; head = head->next; }} // Function that takes continuous input// until user enter -1 while initializing// the linked list.void takeInput(node*& head){ int n; cin >> n; // If n is not equals to -1 insert // the node in the linked list while (n != -1) { // If head is NULL, insert at // the beginning of list if (head == NULL) insertAtHead(head, n); else insertAtTail(head, n); cin >> n; }} // Overloading the ostream operator '<<'// to print the complete linked list from// beginningostream& operator<<(ostream& os, node* head){ print(head);} // Overloading the istream operator '>>'// to take continuous input into the linked// list until user inputs -1istream& operator>>(istream& is, node*& head){ takeInput(head);} // Driver Codeint main(){ // initialise head to NULL node* head = NULL; // Overloading of '>>' for inserting // element in the linked list cin >> head; // Overloading of '<<' for printing // element in the linked list cout << head; return 0;}
Input:
Output:
Some important points about the cascading of operators:
There is no limit on the cascading of operators in a program.
The operator function called must return an object of the same class whose object called this operator function otherwise how will the returned value will call the operator function of the same class.
C++-Operator Overloading
C-Operators
cpp-operator
cpp-operator-overloading
Operator Overloading
Operators
C++
C++ Programs
cpp-operator
Operators
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Header files in C/C++ and its uses
Program to print ASCII Value of a character
C++ Program for QuickSort
How to return multiple values from a function in C or C++?
Sorting a Map by value in C++ STL
|
[
{
"code": null,
"e": 25477,
"s": 25449,
"text": "\n28 Dec, 2020"
},
{
"code": null,
"e": 25550,
"s": 25477,
"text": "Prerequisite: Operator Overloading in C++, Types of Operator Overloading"
},
{
"code": null,
"e": 25828,
"s": 25550,
"text": "When an object calls an operator function by passing an argument and the returned value of the operator function calls the next operator function in the same expression, it is called as cascading of operators. Below are the examples for illustration of Cascading Of Operations:"
},
{
"code": null,
"e": 25839,
"s": 25828,
"text": "Program 1:"
},
{
"code": null,
"e": 25843,
"s": 25839,
"text": "C++"
},
{
"code": "// C++ program to illustrate the// cascading operators#include <iostream>using namespace std; // Height Classclass Height {private: int feet, inches; public: // Default Constructor Height() { feet = 0; inches = 0; } // Function to assign value to // the object of class Height void setData(int x, int y) { feet = x; inches = y; } // Function to print the object // of the class void showData() { cout << feet << \"'\" << inches; } // Function for overloading // of operator + Height operator+(Height H) { Height temp; // Add the feets temp.feet = feet + H.feet; // Add the inches temp.inches = inches + H.inches; return temp; } // Function to normalize the height // into proper terms of 1 feet // per 12 inches void normalize() { // Update the feets if (inches == 12 || inches > 12) { feet = feet + inches / 12; } // Update Inches inches = inches % 12; }}; // Driver Codeint main(){ Height h1, h2, h3, h4; // Initialize the three heights h1.setData(5, 9); h2.setData(5, 2); h3.setData(6, 2); // Add all the heights using // cascading of operators h4 = h1 + h2 + h3; // Normalize the heights h4.normalize(); // Print the height h4 h4.showData(); return 0;}",
"e": 27265,
"s": 25843,
"text": null
},
{
"code": null,
"e": 27339,
"s": 27265,
"text": "Explanation:In this code, Cascading of the operator is taking place here:"
},
{
"code": null,
"e": 27358,
"s": 27339,
"text": "h4 = h1 + h2 + h3;"
},
{
"code": null,
"e": 27668,
"s": 27358,
"text": "Here at first h1 object called (+) operator and passes h2 as an argument in the operator function call and the returned value of this operator function calls again (+) operator and passes h3 as an argument in the same expression, at last, the returned value of this second operator function is assigned in h4."
},
{
"code": null,
"e": 27816,
"s": 27668,
"text": "Program 2: The multiple uses of input or output operators (“>>” or ”<<”) in one statement is also an example of cascading of Input/Output operator."
},
{
"code": null,
"e": 27863,
"s": 27816,
"text": "cout is an object of predefined ostream class."
},
{
"code": null,
"e": 28060,
"s": 27863,
"text": "There are several insertions (“<<”) operator functions defined in ostream class for different primitive data types. For Non-primitive data types, you have to define them using the friend function."
},
{
"code": null,
"e": 28230,
"s": 28060,
"text": "Below is the program for overloading of ‘>>’ and ‘<<‘ operators, which takes a number N as an input continuously and insert the number N in the linked list until N = -1."
},
{
"code": null,
"e": 28234,
"s": 28230,
"text": "C++"
},
{
"code": "// C++ program to demonstrate the// overloading of '<<' and '>>'// operators#include <iostream>using namespace std; // Class for each node object// of the linked listclass node {public: // Node of the linked list int data; node* next; // Constructor of node class node(int d) { data = d; next = NULL; }}; // Insert a node at head of linked// listvoid insertAtHead(node*& head, int d){ node* n = new node(d); n->next = head; head = n;} // Insert a node at tail of linked// listvoid insertAtTail(node* head, int data){ // Make new node using // constructor node* n = new node(data); node* temp = head; // Traverse till we get to end of // the linked list while (temp->next != NULL) temp = temp->next; // Append the new node n at the end // of the linked list temp->next = n;} // Print the node at the linked listvoid print(node* head){ // Print the first Node if (head != NULL) { cout << head->data; head = head->next; } // Traverse till head traverse // till end while (head != NULL) { cout << \"->\" << head->data; head = head->next; }} // Function that takes continuous input// until user enter -1 while initializing// the linked list.void takeInput(node*& head){ int n; cin >> n; // If n is not equals to -1 insert // the node in the linked list while (n != -1) { // If head is NULL, insert at // the beginning of list if (head == NULL) insertAtHead(head, n); else insertAtTail(head, n); cin >> n; }} // Overloading the ostream operator '<<'// to print the complete linked list from// beginningostream& operator<<(ostream& os, node* head){ print(head);} // Overloading the istream operator '>>'// to take continuous input into the linked// list until user inputs -1istream& operator>>(istream& is, node*& head){ takeInput(head);} // Driver Codeint main(){ // initialise head to NULL node* head = NULL; // Overloading of '>>' for inserting // element in the linked list cin >> head; // Overloading of '<<' for printing // element in the linked list cout << head; return 0;}",
"e": 30469,
"s": 28234,
"text": null
},
{
"code": null,
"e": 30476,
"s": 30469,
"text": "Input:"
},
{
"code": null,
"e": 30484,
"s": 30476,
"text": "Output:"
},
{
"code": null,
"e": 30540,
"s": 30484,
"text": "Some important points about the cascading of operators:"
},
{
"code": null,
"e": 30602,
"s": 30540,
"text": "There is no limit on the cascading of operators in a program."
},
{
"code": null,
"e": 30803,
"s": 30602,
"text": "The operator function called must return an object of the same class whose object called this operator function otherwise how will the returned value will call the operator function of the same class."
},
{
"code": null,
"e": 30828,
"s": 30803,
"text": "C++-Operator Overloading"
},
{
"code": null,
"e": 30840,
"s": 30828,
"text": "C-Operators"
},
{
"code": null,
"e": 30853,
"s": 30840,
"text": "cpp-operator"
},
{
"code": null,
"e": 30878,
"s": 30853,
"text": "cpp-operator-overloading"
},
{
"code": null,
"e": 30899,
"s": 30878,
"text": "Operator Overloading"
},
{
"code": null,
"e": 30909,
"s": 30899,
"text": "Operators"
},
{
"code": null,
"e": 30913,
"s": 30909,
"text": "C++"
},
{
"code": null,
"e": 30926,
"s": 30913,
"text": "C++ Programs"
},
{
"code": null,
"e": 30939,
"s": 30926,
"text": "cpp-operator"
},
{
"code": null,
"e": 30949,
"s": 30939,
"text": "Operators"
},
{
"code": null,
"e": 30953,
"s": 30949,
"text": "CPP"
},
{
"code": null,
"e": 31051,
"s": 30953,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31079,
"s": 31051,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 31099,
"s": 31079,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 31132,
"s": 31099,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 31156,
"s": 31132,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 31181,
"s": 31156,
"text": "std::string class in C++"
},
{
"code": null,
"e": 31216,
"s": 31181,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 31260,
"s": 31216,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 31286,
"s": 31260,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 31345,
"s": 31286,
"text": "How to return multiple values from a function in C or C++?"
}
] |
How to change the font size of a text using JavaScript?
|
This method causes a string to be displayed in the specified size as if it were in a <font size= "size"> tag.
You can try to run the following code to change the font size of a text using JavaScript −
Live Demo
<html>
<head>
<title>JavaScript String fontsize() Method</title>
</head>
<body>
<script>
var str = new String("Demo Text");
document.write(str.fontsize(10));
alert(str.fontsize( 10 ));
</script>
</body>
</html>
|
[
{
"code": null,
"e": 1297,
"s": 1187,
"text": "This method causes a string to be displayed in the specified size as if it were in a <font size= \"size\"> tag."
},
{
"code": null,
"e": 1388,
"s": 1297,
"text": "You can try to run the following code to change the font size of a text using JavaScript −"
},
{
"code": null,
"e": 1398,
"s": 1388,
"text": "Live Demo"
},
{
"code": null,
"e": 1667,
"s": 1398,
"text": "<html>\n <head>\n <title>JavaScript String fontsize() Method</title>\n </head>\n\n <body>\n <script>\n var str = new String(\"Demo Text\");\n document.write(str.fontsize(10));\n alert(str.fontsize( 10 ));\n </script>\n </body>\n</html>"
}
] |
JavaScript Interview Questions and Answers
|
05 Nov, 2019
What are the differences between Java and JavaScript ?JavaScript is a client-side scripting language and Java is object Oriented Programming language, both of them are totally different from each other.JavaScript: It is a light-weighted programming language (“scripting language”) and used to develop interactive web pages. It can insert dynamic text into HTML element. JavaScript is also known as the browser’s language.Java: Java is one of the most popular and widely used programming language. It is an object-oriented programming language and has a virtual machine platform that allows you to create compiled programs that run on nearly every platform. Java promised, “Write Once, Run Anywhere”. What are JavaScript Data Types ?There are three major Datatypes in JavaScript.PrimitiveNumbersStringsBooleanTrivialNullUndefinedCompositeObjectsFunctionsArrays Which symbol is used for comments in JavaScript ?Comments are used to prevent the execution of statements. Comments are ignored while the compiler executes the code. There are two type of symbols used to represent comment in JavaScript:Double slash: It is known as single line comment.// Single line commentSlash with Asterisk: It is known as multi-line comment./*
Multi-line comments
...
*/ What would be the result of 3+2+”7′′ ?Here 3 and 2 behave like an integer and “7” behaves like a string. So 3 plus 2 will 5. Then the output will be 5+”7′′ = 57. What is the use of isNaN function ?The Number.isNan function in JavaScript is used to determines whether the passed value is NaN (Not a Number) and is of the type “Number”. In JavaScript, the value NaN is considered a type of number. It returns true if the argument is not a number else it returns false. Which is faster in JavaScript and ASP script ?The JavaScript is faster compare to ASP Script because JavaScript is a client-side scripting language and does not depend on the server to execute it but the ASP script is a server-side scripting language always dependable on the server. What is negative infinity ?The negative infinity in JavaScript is a constant value that is used to represent the lowest available value. It means that no other number is lesser than this value. It can be generated using a self-made function or by an arithmetic operation. JavaScript shows the NEGATIVE_INFINITY value as -Infinity. Is it possible to break JavaScript Code into several lines ?Yes, it is possible to break the JavaScript code into several lines in string statement. It can be break by using the backslash ‘\’. For example:document.write("A Online Computer Science Portal\ for Geeks")The code-breaking line is avoided by JavaScript which is not preferable.var gfg= 10, GFG = 5,
Geeks =
gfg + GFG; Which company developed JavaScript ?Netscape developed the JavaScript and created by Brenden Eich in the year of 1995. What are undeclared and undefined variables ?Undefined: It occurs when a variable has been declared but has not been assigned with any value. Undefined is not a keyword.Undeclared: It occurs when we try to access any variable which is not initialized or declared earlier using var or const keyword. If we use ‘typeof’ operator to get the value of an undeclared variable, we will face the runtime error with return value as “undefined”. The scope of the undeclared variables is always global. Write a JavaScript code for adding new elements dynamically ?<!DOCTYPE html><html> <head> <title> JavaScript code for adding new elements dynamically </title></head> <body> <button onclick="create()"> Click Here! </button> <script> function create() { var geeks = document.createElement('geeks'); geeks.textContent = "Geeksforgeeks"; geeks.setAttribute('class', 'note'); document.body.appendChild(geeks); } </script></body> </html> What are global variables? How are these variable declared and what are the problems associated with them ?In contrast, global variables are the variables that are defined outside of functions. These variables have a global scope, so they can be used by any function without passing them to the function as parameters.Example:<script> var petName = "Rocky"; //Global Variable myFunction(); function myFunction() { document.getElementById("geeks").innerHTML = typeof petName + "- " + "My pet name is " + petName; } document.getElementById("Geeks").innerHTML = typeof petName + "- " + "My pet name is " + petName; </script> It is difficult to debug and test the code that relies on global variables. What do you mean by NULL in JavaScript ?The NULL value represents the no value or no object. It can be called as empty value/object. How to delete property specific value ?The delete keyword is used to delete the whole property and all the values at once likevar gfg={Course: "DSA", Duration:30};
delete gfg.Course; What is a prompt box ?It is used to display a dialog box with an optional message prompting the user to input some text. It is often used if the user wants to input a value before entering a page. It returns a string containing the text entered by the user, or null. What is ‘this’ keyword in JavaScript ?Functions in JavaScript are essential objects. Like objects, they can be assigned to variables, passed to other functions and returned from functions. And much like objects, they have their own properties.‘this’ stores the current execution context of the JavaScript program. Thus, when it used inside a function, the value of ‘this’ will change depending on how the function is defined, how it is invoked and the default execution context. Explain the working of timers in JavaScript? Also elucidate the drawbacks of using the timer, if any ?Timer is used to execute some specific code at specific time or any small amount of code in repetition to do that you need to use the function setTimout, setInterval and clearInterval. If JavaScript code set the timer of 2 minutes and when the times up then the page display an alert message “times up”. The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds. What is the difference between ViewState and SessionState ?ViewState: It is specific to a single page in a session.SessionState: It is user specific that can access all the data in the webpages. How can you submit a form using JavaScript ?You can use document.form[0].submit() method to submit the form in JavaScript. Does JavaScript support automatic type conversion ?Yes, JavaScript supports automatic type conversion.
What are the differences between Java and JavaScript ?JavaScript is a client-side scripting language and Java is object Oriented Programming language, both of them are totally different from each other.JavaScript: It is a light-weighted programming language (“scripting language”) and used to develop interactive web pages. It can insert dynamic text into HTML element. JavaScript is also known as the browser’s language.Java: Java is one of the most popular and widely used programming language. It is an object-oriented programming language and has a virtual machine platform that allows you to create compiled programs that run on nearly every platform. Java promised, “Write Once, Run Anywhere”.
JavaScript: It is a light-weighted programming language (“scripting language”) and used to develop interactive web pages. It can insert dynamic text into HTML element. JavaScript is also known as the browser’s language.
Java: Java is one of the most popular and widely used programming language. It is an object-oriented programming language and has a virtual machine platform that allows you to create compiled programs that run on nearly every platform. Java promised, “Write Once, Run Anywhere”.
What are JavaScript Data Types ?There are three major Datatypes in JavaScript.PrimitiveNumbersStringsBooleanTrivialNullUndefinedCompositeObjectsFunctionsArrays
PrimitiveNumbersStringsBoolean
Numbers
Strings
Boolean
TrivialNullUndefined
Null
Undefined
CompositeObjectsFunctionsArrays
Objects
Functions
Arrays
Which symbol is used for comments in JavaScript ?Comments are used to prevent the execution of statements. Comments are ignored while the compiler executes the code. There are two type of symbols used to represent comment in JavaScript:Double slash: It is known as single line comment.// Single line commentSlash with Asterisk: It is known as multi-line comment./*
Multi-line comments
...
*/
Double slash: It is known as single line comment.// Single line comment
// Single line comment
Slash with Asterisk: It is known as multi-line comment./*
Multi-line comments
...
*/
/*
Multi-line comments
...
*/
What would be the result of 3+2+”7′′ ?Here 3 and 2 behave like an integer and “7” behaves like a string. So 3 plus 2 will 5. Then the output will be 5+”7′′ = 57.
What is the use of isNaN function ?The Number.isNan function in JavaScript is used to determines whether the passed value is NaN (Not a Number) and is of the type “Number”. In JavaScript, the value NaN is considered a type of number. It returns true if the argument is not a number else it returns false.
Which is faster in JavaScript and ASP script ?The JavaScript is faster compare to ASP Script because JavaScript is a client-side scripting language and does not depend on the server to execute it but the ASP script is a server-side scripting language always dependable on the server.
What is negative infinity ?The negative infinity in JavaScript is a constant value that is used to represent the lowest available value. It means that no other number is lesser than this value. It can be generated using a self-made function or by an arithmetic operation. JavaScript shows the NEGATIVE_INFINITY value as -Infinity.
Is it possible to break JavaScript Code into several lines ?Yes, it is possible to break the JavaScript code into several lines in string statement. It can be break by using the backslash ‘\’. For example:document.write("A Online Computer Science Portal\ for Geeks")The code-breaking line is avoided by JavaScript which is not preferable.var gfg= 10, GFG = 5,
Geeks =
gfg + GFG;
document.write("A Online Computer Science Portal\ for Geeks")
The code-breaking line is avoided by JavaScript which is not preferable.
var gfg= 10, GFG = 5,
Geeks =
gfg + GFG;
Which company developed JavaScript ?Netscape developed the JavaScript and created by Brenden Eich in the year of 1995.
What are undeclared and undefined variables ?Undefined: It occurs when a variable has been declared but has not been assigned with any value. Undefined is not a keyword.Undeclared: It occurs when we try to access any variable which is not initialized or declared earlier using var or const keyword. If we use ‘typeof’ operator to get the value of an undeclared variable, we will face the runtime error with return value as “undefined”. The scope of the undeclared variables is always global.
Undefined: It occurs when a variable has been declared but has not been assigned with any value. Undefined is not a keyword.
Undeclared: It occurs when we try to access any variable which is not initialized or declared earlier using var or const keyword. If we use ‘typeof’ operator to get the value of an undeclared variable, we will face the runtime error with return value as “undefined”. The scope of the undeclared variables is always global.
Write a JavaScript code for adding new elements dynamically ?<!DOCTYPE html><html> <head> <title> JavaScript code for adding new elements dynamically </title></head> <body> <button onclick="create()"> Click Here! </button> <script> function create() { var geeks = document.createElement('geeks'); geeks.textContent = "Geeksforgeeks"; geeks.setAttribute('class', 'note'); document.body.appendChild(geeks); } </script></body> </html>
<!DOCTYPE html><html> <head> <title> JavaScript code for adding new elements dynamically </title></head> <body> <button onclick="create()"> Click Here! </button> <script> function create() { var geeks = document.createElement('geeks'); geeks.textContent = "Geeksforgeeks"; geeks.setAttribute('class', 'note'); document.body.appendChild(geeks); } </script></body> </html>
What are global variables? How are these variable declared and what are the problems associated with them ?In contrast, global variables are the variables that are defined outside of functions. These variables have a global scope, so they can be used by any function without passing them to the function as parameters.Example:<script> var petName = "Rocky"; //Global Variable myFunction(); function myFunction() { document.getElementById("geeks").innerHTML = typeof petName + "- " + "My pet name is " + petName; } document.getElementById("Geeks").innerHTML = typeof petName + "- " + "My pet name is " + petName; </script> It is difficult to debug and test the code that relies on global variables.
<script> var petName = "Rocky"; //Global Variable myFunction(); function myFunction() { document.getElementById("geeks").innerHTML = typeof petName + "- " + "My pet name is " + petName; } document.getElementById("Geeks").innerHTML = typeof petName + "- " + "My pet name is " + petName; </script>
It is difficult to debug and test the code that relies on global variables.
What do you mean by NULL in JavaScript ?The NULL value represents the no value or no object. It can be called as empty value/object.
How to delete property specific value ?The delete keyword is used to delete the whole property and all the values at once likevar gfg={Course: "DSA", Duration:30};
delete gfg.Course;
var gfg={Course: "DSA", Duration:30};
delete gfg.Course;
What is a prompt box ?It is used to display a dialog box with an optional message prompting the user to input some text. It is often used if the user wants to input a value before entering a page. It returns a string containing the text entered by the user, or null.
What is ‘this’ keyword in JavaScript ?Functions in JavaScript are essential objects. Like objects, they can be assigned to variables, passed to other functions and returned from functions. And much like objects, they have their own properties.‘this’ stores the current execution context of the JavaScript program. Thus, when it used inside a function, the value of ‘this’ will change depending on how the function is defined, how it is invoked and the default execution context.
Explain the working of timers in JavaScript? Also elucidate the drawbacks of using the timer, if any ?Timer is used to execute some specific code at specific time or any small amount of code in repetition to do that you need to use the function setTimout, setInterval and clearInterval. If JavaScript code set the timer of 2 minutes and when the times up then the page display an alert message “times up”. The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.
What is the difference between ViewState and SessionState ?ViewState: It is specific to a single page in a session.SessionState: It is user specific that can access all the data in the webpages.
ViewState: It is specific to a single page in a session.
SessionState: It is user specific that can access all the data in the webpages.
How can you submit a form using JavaScript ?You can use document.form[0].submit() method to submit the form in JavaScript.
Does JavaScript support automatic type conversion ?Yes, JavaScript supports automatic type conversion.
Related Article: Commonly asked JavaScript Interview Questions | Set 1
interview-preparation
Marketing
JavaScript
Web Technologies
Web technologies Questions
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
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
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": 52,
"s": 24,
"text": "\n05 Nov, 2019"
},
{
"code": null,
"e": 6778,
"s": 52,
"text": "What are the differences between Java and JavaScript ?JavaScript is a client-side scripting language and Java is object Oriented Programming language, both of them are totally different from each other.JavaScript: It is a light-weighted programming language (“scripting language”) and used to develop interactive web pages. It can insert dynamic text into HTML element. JavaScript is also known as the browser’s language.Java: Java is one of the most popular and widely used programming language. It is an object-oriented programming language and has a virtual machine platform that allows you to create compiled programs that run on nearly every platform. Java promised, “Write Once, Run Anywhere”. What are JavaScript Data Types ?There are three major Datatypes in JavaScript.PrimitiveNumbersStringsBooleanTrivialNullUndefinedCompositeObjectsFunctionsArrays Which symbol is used for comments in JavaScript ?Comments are used to prevent the execution of statements. Comments are ignored while the compiler executes the code. There are two type of symbols used to represent comment in JavaScript:Double slash: It is known as single line comment.// Single line commentSlash with Asterisk: It is known as multi-line comment./* \nMulti-line comments\n...\n*/ What would be the result of 3+2+”7′′ ?Here 3 and 2 behave like an integer and “7” behaves like a string. So 3 plus 2 will 5. Then the output will be 5+”7′′ = 57. What is the use of isNaN function ?The Number.isNan function in JavaScript is used to determines whether the passed value is NaN (Not a Number) and is of the type “Number”. In JavaScript, the value NaN is considered a type of number. It returns true if the argument is not a number else it returns false. Which is faster in JavaScript and ASP script ?The JavaScript is faster compare to ASP Script because JavaScript is a client-side scripting language and does not depend on the server to execute it but the ASP script is a server-side scripting language always dependable on the server. What is negative infinity ?The negative infinity in JavaScript is a constant value that is used to represent the lowest available value. It means that no other number is lesser than this value. It can be generated using a self-made function or by an arithmetic operation. JavaScript shows the NEGATIVE_INFINITY value as -Infinity. Is it possible to break JavaScript Code into several lines ?Yes, it is possible to break the JavaScript code into several lines in string statement. It can be break by using the backslash ‘\\’. For example:document.write(\"A Online Computer Science Portal\\ for Geeks\")The code-breaking line is avoided by JavaScript which is not preferable.var gfg= 10, GFG = 5,\nGeeks =\ngfg + GFG; Which company developed JavaScript ?Netscape developed the JavaScript and created by Brenden Eich in the year of 1995. What are undeclared and undefined variables ?Undefined: It occurs when a variable has been declared but has not been assigned with any value. Undefined is not a keyword.Undeclared: It occurs when we try to access any variable which is not initialized or declared earlier using var or const keyword. If we use ‘typeof’ operator to get the value of an undeclared variable, we will face the runtime error with return value as “undefined”. The scope of the undeclared variables is always global. Write a JavaScript code for adding new elements dynamically ?<!DOCTYPE html><html> <head> <title> JavaScript code for adding new elements dynamically </title></head> <body> <button onclick=\"create()\"> Click Here! </button> <script> function create() { var geeks = document.createElement('geeks'); geeks.textContent = \"Geeksforgeeks\"; geeks.setAttribute('class', 'note'); document.body.appendChild(geeks); } </script></body> </html> What are global variables? How are these variable declared and what are the problems associated with them ?In contrast, global variables are the variables that are defined outside of functions. These variables have a global scope, so they can be used by any function without passing them to the function as parameters.Example:<script> var petName = \"Rocky\"; //Global Variable myFunction(); function myFunction() { document.getElementById(\"geeks\").innerHTML = typeof petName + \"- \" + \"My pet name is \" + petName; } document.getElementById(\"Geeks\").innerHTML = typeof petName + \"- \" + \"My pet name is \" + petName; </script> It is difficult to debug and test the code that relies on global variables. What do you mean by NULL in JavaScript ?The NULL value represents the no value or no object. It can be called as empty value/object. How to delete property specific value ?The delete keyword is used to delete the whole property and all the values at once likevar gfg={Course: \"DSA\", Duration:30};\ndelete gfg.Course; What is a prompt box ?It is used to display a dialog box with an optional message prompting the user to input some text. It is often used if the user wants to input a value before entering a page. It returns a string containing the text entered by the user, or null. What is ‘this’ keyword in JavaScript ?Functions in JavaScript are essential objects. Like objects, they can be assigned to variables, passed to other functions and returned from functions. And much like objects, they have their own properties.‘this’ stores the current execution context of the JavaScript program. Thus, when it used inside a function, the value of ‘this’ will change depending on how the function is defined, how it is invoked and the default execution context. Explain the working of timers in JavaScript? Also elucidate the drawbacks of using the timer, if any ?Timer is used to execute some specific code at specific time or any small amount of code in repetition to do that you need to use the function setTimout, setInterval and clearInterval. If JavaScript code set the timer of 2 minutes and when the times up then the page display an alert message “times up”. The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds. What is the difference between ViewState and SessionState ?ViewState: It is specific to a single page in a session.SessionState: It is user specific that can access all the data in the webpages. How can you submit a form using JavaScript ?You can use document.form[0].submit() method to submit the form in JavaScript. Does JavaScript support automatic type conversion ?Yes, JavaScript supports automatic type conversion."
},
{
"code": null,
"e": 7478,
"s": 6778,
"text": "What are the differences between Java and JavaScript ?JavaScript is a client-side scripting language and Java is object Oriented Programming language, both of them are totally different from each other.JavaScript: It is a light-weighted programming language (“scripting language”) and used to develop interactive web pages. It can insert dynamic text into HTML element. JavaScript is also known as the browser’s language.Java: Java is one of the most popular and widely used programming language. It is an object-oriented programming language and has a virtual machine platform that allows you to create compiled programs that run on nearly every platform. Java promised, “Write Once, Run Anywhere”."
},
{
"code": null,
"e": 7698,
"s": 7478,
"text": "JavaScript: It is a light-weighted programming language (“scripting language”) and used to develop interactive web pages. It can insert dynamic text into HTML element. JavaScript is also known as the browser’s language."
},
{
"code": null,
"e": 7977,
"s": 7698,
"text": "Java: Java is one of the most popular and widely used programming language. It is an object-oriented programming language and has a virtual machine platform that allows you to create compiled programs that run on nearly every platform. Java promised, “Write Once, Run Anywhere”."
},
{
"code": null,
"e": 8141,
"s": 7981,
"text": "What are JavaScript Data Types ?There are three major Datatypes in JavaScript.PrimitiveNumbersStringsBooleanTrivialNullUndefinedCompositeObjectsFunctionsArrays"
},
{
"code": null,
"e": 8172,
"s": 8141,
"text": "PrimitiveNumbersStringsBoolean"
},
{
"code": null,
"e": 8180,
"s": 8172,
"text": "Numbers"
},
{
"code": null,
"e": 8188,
"s": 8180,
"text": "Strings"
},
{
"code": null,
"e": 8196,
"s": 8188,
"text": "Boolean"
},
{
"code": null,
"e": 8217,
"s": 8196,
"text": "TrivialNullUndefined"
},
{
"code": null,
"e": 8222,
"s": 8217,
"text": "Null"
},
{
"code": null,
"e": 8232,
"s": 8222,
"text": "Undefined"
},
{
"code": null,
"e": 8264,
"s": 8232,
"text": "CompositeObjectsFunctionsArrays"
},
{
"code": null,
"e": 8272,
"s": 8264,
"text": "Objects"
},
{
"code": null,
"e": 8282,
"s": 8272,
"text": "Functions"
},
{
"code": null,
"e": 8289,
"s": 8282,
"text": "Arrays"
},
{
"code": null,
"e": 8686,
"s": 8293,
"text": "Which symbol is used for comments in JavaScript ?Comments are used to prevent the execution of statements. Comments are ignored while the compiler executes the code. There are two type of symbols used to represent comment in JavaScript:Double slash: It is known as single line comment.// Single line commentSlash with Asterisk: It is known as multi-line comment./* \nMulti-line comments\n...\n*/"
},
{
"code": null,
"e": 8758,
"s": 8686,
"text": "Double slash: It is known as single line comment.// Single line comment"
},
{
"code": null,
"e": 8781,
"s": 8758,
"text": "// Single line comment"
},
{
"code": null,
"e": 8867,
"s": 8781,
"text": "Slash with Asterisk: It is known as multi-line comment./* \nMulti-line comments\n...\n*/"
},
{
"code": null,
"e": 8898,
"s": 8867,
"text": "/* \nMulti-line comments\n...\n*/"
},
{
"code": null,
"e": 9064,
"s": 8902,
"text": "What would be the result of 3+2+”7′′ ?Here 3 and 2 behave like an integer and “7” behaves like a string. So 3 plus 2 will 5. Then the output will be 5+”7′′ = 57."
},
{
"code": null,
"e": 9373,
"s": 9068,
"text": "What is the use of isNaN function ?The Number.isNan function in JavaScript is used to determines whether the passed value is NaN (Not a Number) and is of the type “Number”. In JavaScript, the value NaN is considered a type of number. It returns true if the argument is not a number else it returns false."
},
{
"code": null,
"e": 9661,
"s": 9377,
"text": "Which is faster in JavaScript and ASP script ?The JavaScript is faster compare to ASP Script because JavaScript is a client-side scripting language and does not depend on the server to execute it but the ASP script is a server-side scripting language always dependable on the server."
},
{
"code": null,
"e": 9996,
"s": 9665,
"text": "What is negative infinity ?The negative infinity in JavaScript is a constant value that is used to represent the lowest available value. It means that no other number is lesser than this value. It can be generated using a self-made function or by an arithmetic operation. JavaScript shows the NEGATIVE_INFINITY value as -Infinity."
},
{
"code": null,
"e": 10379,
"s": 10000,
"text": "Is it possible to break JavaScript Code into several lines ?Yes, it is possible to break the JavaScript code into several lines in string statement. It can be break by using the backslash ‘\\’. For example:document.write(\"A Online Computer Science Portal\\ for Geeks\")The code-breaking line is avoided by JavaScript which is not preferable.var gfg= 10, GFG = 5,\nGeeks =\ngfg + GFG;"
},
{
"code": null,
"e": 10441,
"s": 10379,
"text": "document.write(\"A Online Computer Science Portal\\ for Geeks\")"
},
{
"code": null,
"e": 10514,
"s": 10441,
"text": "The code-breaking line is avoided by JavaScript which is not preferable."
},
{
"code": null,
"e": 10555,
"s": 10514,
"text": "var gfg= 10, GFG = 5,\nGeeks =\ngfg + GFG;"
},
{
"code": null,
"e": 10678,
"s": 10559,
"text": "Which company developed JavaScript ?Netscape developed the JavaScript and created by Brenden Eich in the year of 1995."
},
{
"code": null,
"e": 11174,
"s": 10682,
"text": "What are undeclared and undefined variables ?Undefined: It occurs when a variable has been declared but has not been assigned with any value. Undefined is not a keyword.Undeclared: It occurs when we try to access any variable which is not initialized or declared earlier using var or const keyword. If we use ‘typeof’ operator to get the value of an undeclared variable, we will face the runtime error with return value as “undefined”. The scope of the undeclared variables is always global."
},
{
"code": null,
"e": 11299,
"s": 11174,
"text": "Undefined: It occurs when a variable has been declared but has not been assigned with any value. Undefined is not a keyword."
},
{
"code": null,
"e": 11622,
"s": 11299,
"text": "Undeclared: It occurs when we try to access any variable which is not initialized or declared earlier using var or const keyword. If we use ‘typeof’ operator to get the value of an undeclared variable, we will face the runtime error with return value as “undefined”. The scope of the undeclared variables is always global."
},
{
"code": null,
"e": 12164,
"s": 11626,
"text": "Write a JavaScript code for adding new elements dynamically ?<!DOCTYPE html><html> <head> <title> JavaScript code for adding new elements dynamically </title></head> <body> <button onclick=\"create()\"> Click Here! </button> <script> function create() { var geeks = document.createElement('geeks'); geeks.textContent = \"Geeksforgeeks\"; geeks.setAttribute('class', 'note'); document.body.appendChild(geeks); } </script></body> </html>"
},
{
"code": "<!DOCTYPE html><html> <head> <title> JavaScript code for adding new elements dynamically </title></head> <body> <button onclick=\"create()\"> Click Here! </button> <script> function create() { var geeks = document.createElement('geeks'); geeks.textContent = \"Geeksforgeeks\"; geeks.setAttribute('class', 'note'); document.body.appendChild(geeks); } </script></body> </html>",
"e": 12641,
"s": 12164,
"text": null
},
{
"code": null,
"e": 13471,
"s": 12645,
"text": "What are global variables? How are these variable declared and what are the problems associated with them ?In contrast, global variables are the variables that are defined outside of functions. These variables have a global scope, so they can be used by any function without passing them to the function as parameters.Example:<script> var petName = \"Rocky\"; //Global Variable myFunction(); function myFunction() { document.getElementById(\"geeks\").innerHTML = typeof petName + \"- \" + \"My pet name is \" + petName; } document.getElementById(\"Geeks\").innerHTML = typeof petName + \"- \" + \"My pet name is \" + petName; </script> It is difficult to debug and test the code that relies on global variables."
},
{
"code": "<script> var petName = \"Rocky\"; //Global Variable myFunction(); function myFunction() { document.getElementById(\"geeks\").innerHTML = typeof petName + \"- \" + \"My pet name is \" + petName; } document.getElementById(\"Geeks\").innerHTML = typeof petName + \"- \" + \"My pet name is \" + petName; </script> ",
"e": 13896,
"s": 13471,
"text": null
},
{
"code": null,
"e": 13972,
"s": 13896,
"text": "It is difficult to debug and test the code that relies on global variables."
},
{
"code": null,
"e": 14109,
"s": 13976,
"text": "What do you mean by NULL in JavaScript ?The NULL value represents the no value or no object. It can be called as empty value/object."
},
{
"code": null,
"e": 14296,
"s": 14113,
"text": "How to delete property specific value ?The delete keyword is used to delete the whole property and all the values at once likevar gfg={Course: \"DSA\", Duration:30};\ndelete gfg.Course;"
},
{
"code": null,
"e": 14353,
"s": 14296,
"text": "var gfg={Course: \"DSA\", Duration:30};\ndelete gfg.Course;"
},
{
"code": null,
"e": 14624,
"s": 14357,
"text": "What is a prompt box ?It is used to display a dialog box with an optional message prompting the user to input some text. It is often used if the user wants to input a value before entering a page. It returns a string containing the text entered by the user, or null."
},
{
"code": null,
"e": 15107,
"s": 14628,
"text": "What is ‘this’ keyword in JavaScript ?Functions in JavaScript are essential objects. Like objects, they can be assigned to variables, passed to other functions and returned from functions. And much like objects, they have their own properties.‘this’ stores the current execution context of the JavaScript program. Thus, when it used inside a function, the value of ‘this’ will change depending on how the function is defined, how it is invoked and the default execution context."
},
{
"code": null,
"e": 15627,
"s": 15111,
"text": "Explain the working of timers in JavaScript? Also elucidate the drawbacks of using the timer, if any ?Timer is used to execute some specific code at specific time or any small amount of code in repetition to do that you need to use the function setTimout, setInterval and clearInterval. If JavaScript code set the timer of 2 minutes and when the times up then the page display an alert message “times up”. The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds."
},
{
"code": null,
"e": 15826,
"s": 15631,
"text": "What is the difference between ViewState and SessionState ?ViewState: It is specific to a single page in a session.SessionState: It is user specific that can access all the data in the webpages."
},
{
"code": null,
"e": 15883,
"s": 15826,
"text": "ViewState: It is specific to a single page in a session."
},
{
"code": null,
"e": 15963,
"s": 15883,
"text": "SessionState: It is user specific that can access all the data in the webpages."
},
{
"code": null,
"e": 16090,
"s": 15967,
"text": "How can you submit a form using JavaScript ?You can use document.form[0].submit() method to submit the form in JavaScript."
},
{
"code": null,
"e": 16197,
"s": 16094,
"text": "Does JavaScript support automatic type conversion ?Yes, JavaScript supports automatic type conversion."
},
{
"code": null,
"e": 16268,
"s": 16197,
"text": "Related Article: Commonly asked JavaScript Interview Questions | Set 1"
},
{
"code": null,
"e": 16290,
"s": 16268,
"text": "interview-preparation"
},
{
"code": null,
"e": 16300,
"s": 16290,
"text": "Marketing"
},
{
"code": null,
"e": 16311,
"s": 16300,
"text": "JavaScript"
},
{
"code": null,
"e": 16328,
"s": 16311,
"text": "Web Technologies"
},
{
"code": null,
"e": 16355,
"s": 16328,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 16453,
"s": 16355,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 16514,
"s": 16453,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 16586,
"s": 16514,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 16626,
"s": 16586,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 16678,
"s": 16626,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 16719,
"s": 16678,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 16781,
"s": 16719,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 16814,
"s": 16781,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 16875,
"s": 16814,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 16925,
"s": 16875,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Convert PDF File Text to Audio Speech using Python
|
15 Jul, 2021
Let us see how to read a PDF that is converting a textual PDF file into audio.
Packages Used:
pyttsx3: It is a Python library for Text to Speech. It has many functions which will help the machine to communicate with us. It will help the machine to speak to us
PyPDF2: It will help to the text from the PDF. A Pure-Python library built as a PDF toolkit. It is capable of extracting document information, splitting documents page by page, merging documents page by page etc.
Both these modules need to be installed
pip install pyttsx3
pip install PyPDF2
Making Audio Book From Any PDF Using Python | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersMaking Audio Book From Any PDF Using Python | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 17:12•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=bLGyDfc1x2A" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
You also need to know about the open() function which will help us to open the PDF in read mode. Knowledge about the OOPS Concept is also recommended.
Here is the link of the PDF which is read in the example: https://drive.google.com/file/d/1zhf7-_v6CVUtgd_XMK562mg6ciewi1QR/view?usp=sharing
Approach:
Import the PyPDF2 and pyttx3 modules.
Open the PDF file.
Use PdfFileReader() to read the PDF. We just have to give the path of the PDF as the argument.
Use the getPage() method to select the page to be read.
Extract the text from the page using extractText().
Instantiate a pyttx3 object.
Use the say() and runwait() methods to speak out the text.
Now here the code for it
Python3
# importing the modulesimport PyPDF2import pyttsx3 # path of the PDF filepath = open('file.pdf', 'rb') # creating a PdfFileReader objectpdfReader = PyPDF2.PdfFileReader(path) # the page with which you want to start# this will read the page of 25th page.from_page = pdfReader.getPage(24) # extracting the text from the PDFtext = from_page.extractText() # reading the textspeak = pyttsx3.init()speak.say(text)speak.runAndWait()
Output:
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n15 Jul, 2021"
},
{
"code": null,
"e": 131,
"s": 52,
"text": "Let us see how to read a PDF that is converting a textual PDF file into audio."
},
{
"code": null,
"e": 146,
"s": 131,
"text": "Packages Used:"
},
{
"code": null,
"e": 312,
"s": 146,
"text": "pyttsx3: It is a Python library for Text to Speech. It has many functions which will help the machine to communicate with us. It will help the machine to speak to us"
},
{
"code": null,
"e": 525,
"s": 312,
"text": "PyPDF2: It will help to the text from the PDF. A Pure-Python library built as a PDF toolkit. It is capable of extracting document information, splitting documents page by page, merging documents page by page etc."
},
{
"code": null,
"e": 565,
"s": 525,
"text": "Both these modules need to be installed"
},
{
"code": null,
"e": 605,
"s": 565,
"text": "pip install pyttsx3\npip install PyPDF2\n"
},
{
"code": null,
"e": 1510,
"s": 605,
"text": "Making Audio Book From Any PDF Using Python | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersMaking Audio Book From Any PDF Using Python | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 17:12•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=bLGyDfc1x2A\" 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": 1661,
"s": 1510,
"text": "You also need to know about the open() function which will help us to open the PDF in read mode. Knowledge about the OOPS Concept is also recommended."
},
{
"code": null,
"e": 1802,
"s": 1661,
"text": "Here is the link of the PDF which is read in the example: https://drive.google.com/file/d/1zhf7-_v6CVUtgd_XMK562mg6ciewi1QR/view?usp=sharing"
},
{
"code": null,
"e": 1812,
"s": 1802,
"text": "Approach:"
},
{
"code": null,
"e": 1850,
"s": 1812,
"text": "Import the PyPDF2 and pyttx3 modules."
},
{
"code": null,
"e": 1869,
"s": 1850,
"text": "Open the PDF file."
},
{
"code": null,
"e": 1964,
"s": 1869,
"text": "Use PdfFileReader() to read the PDF. We just have to give the path of the PDF as the argument."
},
{
"code": null,
"e": 2020,
"s": 1964,
"text": "Use the getPage() method to select the page to be read."
},
{
"code": null,
"e": 2072,
"s": 2020,
"text": "Extract the text from the page using extractText()."
},
{
"code": null,
"e": 2101,
"s": 2072,
"text": "Instantiate a pyttx3 object."
},
{
"code": null,
"e": 2160,
"s": 2101,
"text": "Use the say() and runwait() methods to speak out the text."
},
{
"code": null,
"e": 2185,
"s": 2160,
"text": "Now here the code for it"
},
{
"code": null,
"e": 2193,
"s": 2185,
"text": "Python3"
},
{
"code": "# importing the modulesimport PyPDF2import pyttsx3 # path of the PDF filepath = open('file.pdf', 'rb') # creating a PdfFileReader objectpdfReader = PyPDF2.PdfFileReader(path) # the page with which you want to start# this will read the page of 25th page.from_page = pdfReader.getPage(24) # extracting the text from the PDFtext = from_page.extractText() # reading the textspeak = pyttsx3.init()speak.say(text)speak.runAndWait()",
"e": 2624,
"s": 2193,
"text": null
},
{
"code": null,
"e": 2632,
"s": 2624,
"text": "Output:"
},
{
"code": null,
"e": 2647,
"s": 2632,
"text": "python-utility"
},
{
"code": null,
"e": 2654,
"s": 2647,
"text": "Python"
},
{
"code": null,
"e": 2752,
"s": 2654,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2784,
"s": 2752,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2811,
"s": 2784,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2832,
"s": 2811,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2855,
"s": 2832,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2911,
"s": 2855,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2942,
"s": 2911,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2984,
"s": 2942,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3026,
"s": 2984,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3065,
"s": 3026,
"text": "Python | Get unique values from a list"
}
] |
Maximum area of triangle having different vertex colors
|
19 Apr, 2022
Given a matrix of N rows and M columns, consists of three value {r, g, b}. The task is to find the area of the largest triangle that has one side parallel to y-axis i.e vertical and the color of all three vertices are different.Examples:
Input : N = 4, M =5
mat[][] =
{
r, r, r, r, r,
r, r, r, r, g,
r, r, r, r, r,
b, b, b, b, b,
}
Output : 10
The maximum area of triangle is 10.
Triangle coordinates are (0,0) containing r, (1,4) containing g, (3,0) containing b.
We know area of a triangle = 1/2 * base *height, so we need to maximize the base and height of the triangle. Since one side is parallel to the y-axis, we can consider that side as the base of the triangle.To maximize base, we can find the first and last occurrence of {r, g, b} for each column. So we have two sets of 3 values for each column. For base in any column, one vertex is from the first set and the second vertex from the second set such that they have different values.To maximize height, for any column as a base, the third vertex must be chosen such that the vertex should be farthest from the column, on the left or right side of the column having a value different from the other two vertices. Now for each column find the maximum area of the triangle.Below is the implementation of this approach:
C++
Python3
// C++ program to find maximum area of triangle// having different vertex color in a matrix.#include<bits/stdc++.h>using namespace std;#define R 4#define C 5 // return the color value so that their corresponding// index can be access.int mapcolor(char c){ if (c == 'r') return 0; else if (c == 'g') return 1; else if (c == 'b') return 2;} // Returns the maximum area of triangle from all// the possible trianglesdouble findarea(char mat[R][C], int r, int c, int top[3][C], int bottom[3][C], int left[3], int right[3]){ double ans = (double)1; // for each column for (int i = 0; i < c; i++) // for each top vertex for (int x = 0; x < 3; x++) // for each bottom vertex for (int y = 0; y < 3; y++) { // finding the third color of // vertex either on right or left. int z = 3 - x - y; // finding area of triangle on left side of column. if (x != y && top[x][i] != INT_MAX && bottom[y][i] != INT_MIN && left[z] != INT_MAX) { ans = max(ans, ((double)1/(double)2) * (bottom[y][i] - top[x][i]) * (i - left[z])); } // finding area of triangle on right side of column. if (x != y && top[x][i] != INT_MAX && bottom[y][i] != INT_MIN && right[z] != INT_MIN) { ans = max(ans, ((double)1/(double)2) * (bottom[y][i] - top[x][i]) * (right[z] - i)); } } return ans;} // Precompute the vertices of top, bottom, left// and right and then computing the maximum area.double maxarea(char mat[R][C], int r, int c){ int left[3], right[3]; int top[3][C], bottom[3][C]; memset(left, INT_MAX, sizeof left); memset(right, INT_MIN, sizeof right); memset(top, INT_MAX, sizeof top); memset(bottom, INT_MIN, sizeof bottom); // finding the r, b, g cells for the left // and right vertices. for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { left[mapcolor(mat[i][j])] = min(left[mapcolor(mat[i][j])], j); right[mapcolor(mat[i][j])] = max(left[mapcolor(mat[i][j])], j); } } // finding set of {r, g, b} of top and // bottom for each column. for (int j = 0; j < c; j++) { for( int i = 0; i < r; i++) { top[mapcolor(mat[i][j])][j] = min(top[mapcolor(mat[i][j])][j], i); bottom[mapcolor(mat[i][j])][j] = max(bottom[mapcolor(mat[i][j])][j], i); } } return findarea(mat, R, C, top, bottom, left, right);} // Driven Programint main(){ char mat[R][C] = { 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'g', 'r', 'r', 'r', 'r', 'r', 'b', 'b', 'b', 'b', 'b', }; cout << maxarea(mat, R, C) << endl; return 0;}
# Python3 program to find the maximum# area of triangle having different# vertex color in a matrix. # Return the color value so that their# corresponding index can be access.def mapcolor(c): if c == 'r': return 0 elif c == 'g': return 1 elif c == 'b': return 2 # Returns the maximum area of triangle# from all the possible trianglesdef findarea(mat, r, c, top, bottom, left, right): ans = 1 # for each column for i in range(0, c): # for each top vertex for x in range(0, 3): # for each bottom vertex for y in range(0, 3): # finding the third color of # vertex either on right or left. z = 3 - x - y # finding area of triangle on # left side of column. if (x != y and top[x][i] != INT_MAX and bottom[y][i] != INT_MIN and left[z] != INT_MAX): ans = max(ans, 0.5 * (bottom[y][i] - top[x][i]) * (i - left[z])) # finding area of triangle on right side of column. if (x != y and top[x][i] != INT_MAX and bottom[y][i] != INT_MIN and right[z] != INT_MIN): ans = max(ans, 0.5 * (bottom[y][i] - top[x][i]) * (right[z] - i)) return ans # Precompute the vertices of top, bottom, left# and right and then computing the maximum area.def maxarea(mat, r, c): left = [-1] * 3 right = [0] * 3 top = [[-1 for i in range(C)] for j in range(3)] bottom = [[0 for i in range(C)] for j in range(3)] # finding the r, b, g cells for # the left and right vertices. for i in range(0, r): for j in range(0, c): left[mapcolor(mat[i][j])] = \ min(left[mapcolor(mat[i][j])], j) right[mapcolor(mat[i][j])] = \ max(left[mapcolor(mat[i][j])], j) # finding set of r, g, b of top # and bottom for each column. for j in range(0, c): for i in range(0, r): top[mapcolor(mat[i][j])][j] = \ min(top[mapcolor(mat[i][j])][j], i) bottom[mapcolor(mat[i][j])][j] = \ max(bottom[mapcolor(mat[i][j])][j], i) return int(findarea(mat, R, C, top, bottom, left, right)) # Driver Codeif __name__ == "__main__": R, C = 4, 5 mat = [['r', 'r', 'r', 'r', 'r'], ['r', 'r', 'r', 'r', 'g'], ['r', 'r', 'r', 'r', 'r'], ['b', 'b', 'b', 'b', 'b']] INT_MAX, INT_MIN = float('inf'), float('-inf') print(maxarea(mat, R, C)) # This code is contributed by Rituraj Jain
Output:
10
Time Complexity : O(R * C)Auxiliary Space: O(R + C) Source: http://stackoverflow.com/questions/40078660/maximum-area-of-triangle-having-all-vertices-of-different-colorThis article is contributed by Anuj Chauhan(anuj0503). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
rituraj_jain
pankajsharmagfg
simmytarika5
area-volume-programs
Directi
triangle
Algorithms
Directi
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 Apr, 2022"
},
{
"code": null,
"e": 292,
"s": 52,
"text": "Given a matrix of N rows and M columns, consists of three value {r, g, b}. The task is to find the area of the largest triangle that has one side parallel to y-axis i.e vertical and the color of all three vertices are different.Examples: "
},
{
"code": null,
"e": 534,
"s": 292,
"text": "Input : N = 4, M =5\n mat[][] =\n {\n r, r, r, r, r,\n r, r, r, r, g,\n r, r, r, r, r,\n b, b, b, b, b,\n }\nOutput : 10\nThe maximum area of triangle is 10.\nTriangle coordinates are (0,0) containing r, (1,4) containing g, (3,0) containing b."
},
{
"code": null,
"e": 1350,
"s": 536,
"text": "We know area of a triangle = 1/2 * base *height, so we need to maximize the base and height of the triangle. Since one side is parallel to the y-axis, we can consider that side as the base of the triangle.To maximize base, we can find the first and last occurrence of {r, g, b} for each column. So we have two sets of 3 values for each column. For base in any column, one vertex is from the first set and the second vertex from the second set such that they have different values.To maximize height, for any column as a base, the third vertex must be chosen such that the vertex should be farthest from the column, on the left or right side of the column having a value different from the other two vertices. Now for each column find the maximum area of the triangle.Below is the implementation of this approach: "
},
{
"code": null,
"e": 1354,
"s": 1350,
"text": "C++"
},
{
"code": null,
"e": 1362,
"s": 1354,
"text": "Python3"
},
{
"code": "// C++ program to find maximum area of triangle// having different vertex color in a matrix.#include<bits/stdc++.h>using namespace std;#define R 4#define C 5 // return the color value so that their corresponding// index can be access.int mapcolor(char c){ if (c == 'r') return 0; else if (c == 'g') return 1; else if (c == 'b') return 2;} // Returns the maximum area of triangle from all// the possible trianglesdouble findarea(char mat[R][C], int r, int c, int top[3][C], int bottom[3][C], int left[3], int right[3]){ double ans = (double)1; // for each column for (int i = 0; i < c; i++) // for each top vertex for (int x = 0; x < 3; x++) // for each bottom vertex for (int y = 0; y < 3; y++) { // finding the third color of // vertex either on right or left. int z = 3 - x - y; // finding area of triangle on left side of column. if (x != y && top[x][i] != INT_MAX && bottom[y][i] != INT_MIN && left[z] != INT_MAX) { ans = max(ans, ((double)1/(double)2) * (bottom[y][i] - top[x][i]) * (i - left[z])); } // finding area of triangle on right side of column. if (x != y && top[x][i] != INT_MAX && bottom[y][i] != INT_MIN && right[z] != INT_MIN) { ans = max(ans, ((double)1/(double)2) * (bottom[y][i] - top[x][i]) * (right[z] - i)); } } return ans;} // Precompute the vertices of top, bottom, left// and right and then computing the maximum area.double maxarea(char mat[R][C], int r, int c){ int left[3], right[3]; int top[3][C], bottom[3][C]; memset(left, INT_MAX, sizeof left); memset(right, INT_MIN, sizeof right); memset(top, INT_MAX, sizeof top); memset(bottom, INT_MIN, sizeof bottom); // finding the r, b, g cells for the left // and right vertices. for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { left[mapcolor(mat[i][j])] = min(left[mapcolor(mat[i][j])], j); right[mapcolor(mat[i][j])] = max(left[mapcolor(mat[i][j])], j); } } // finding set of {r, g, b} of top and // bottom for each column. for (int j = 0; j < c; j++) { for( int i = 0; i < r; i++) { top[mapcolor(mat[i][j])][j] = min(top[mapcolor(mat[i][j])][j], i); bottom[mapcolor(mat[i][j])][j] = max(bottom[mapcolor(mat[i][j])][j], i); } } return findarea(mat, R, C, top, bottom, left, right);} // Driven Programint main(){ char mat[R][C] = { 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'g', 'r', 'r', 'r', 'r', 'r', 'b', 'b', 'b', 'b', 'b', }; cout << maxarea(mat, R, C) << endl; return 0;}",
"e": 4537,
"s": 1362,
"text": null
},
{
"code": "# Python3 program to find the maximum# area of triangle having different# vertex color in a matrix. # Return the color value so that their# corresponding index can be access.def mapcolor(c): if c == 'r': return 0 elif c == 'g': return 1 elif c == 'b': return 2 # Returns the maximum area of triangle# from all the possible trianglesdef findarea(mat, r, c, top, bottom, left, right): ans = 1 # for each column for i in range(0, c): # for each top vertex for x in range(0, 3): # for each bottom vertex for y in range(0, 3): # finding the third color of # vertex either on right or left. z = 3 - x - y # finding area of triangle on # left side of column. if (x != y and top[x][i] != INT_MAX and bottom[y][i] != INT_MIN and left[z] != INT_MAX): ans = max(ans, 0.5 * (bottom[y][i] - top[x][i]) * (i - left[z])) # finding area of triangle on right side of column. if (x != y and top[x][i] != INT_MAX and bottom[y][i] != INT_MIN and right[z] != INT_MIN): ans = max(ans, 0.5 * (bottom[y][i] - top[x][i]) * (right[z] - i)) return ans # Precompute the vertices of top, bottom, left# and right and then computing the maximum area.def maxarea(mat, r, c): left = [-1] * 3 right = [0] * 3 top = [[-1 for i in range(C)] for j in range(3)] bottom = [[0 for i in range(C)] for j in range(3)] # finding the r, b, g cells for # the left and right vertices. for i in range(0, r): for j in range(0, c): left[mapcolor(mat[i][j])] = \\ min(left[mapcolor(mat[i][j])], j) right[mapcolor(mat[i][j])] = \\ max(left[mapcolor(mat[i][j])], j) # finding set of r, g, b of top # and bottom for each column. for j in range(0, c): for i in range(0, r): top[mapcolor(mat[i][j])][j] = \\ min(top[mapcolor(mat[i][j])][j], i) bottom[mapcolor(mat[i][j])][j] = \\ max(bottom[mapcolor(mat[i][j])][j], i) return int(findarea(mat, R, C, top, bottom, left, right)) # Driver Codeif __name__ == \"__main__\": R, C = 4, 5 mat = [['r', 'r', 'r', 'r', 'r'], ['r', 'r', 'r', 'r', 'g'], ['r', 'r', 'r', 'r', 'r'], ['b', 'b', 'b', 'b', 'b']] INT_MAX, INT_MIN = float('inf'), float('-inf') print(maxarea(mat, R, C)) # This code is contributed by Rituraj Jain",
"e": 7580,
"s": 4537,
"text": null
},
{
"code": null,
"e": 7590,
"s": 7580,
"text": "Output: "
},
{
"code": null,
"e": 7593,
"s": 7590,
"text": "10"
},
{
"code": null,
"e": 8191,
"s": 7593,
"text": "Time Complexity : O(R * C)Auxiliary Space: O(R + C) Source: http://stackoverflow.com/questions/40078660/maximum-area-of-triangle-having-all-vertices-of-different-colorThis article is contributed by Anuj Chauhan(anuj0503). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 8204,
"s": 8191,
"text": "rituraj_jain"
},
{
"code": null,
"e": 8220,
"s": 8204,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 8233,
"s": 8220,
"text": "simmytarika5"
},
{
"code": null,
"e": 8254,
"s": 8233,
"text": "area-volume-programs"
},
{
"code": null,
"e": 8262,
"s": 8254,
"text": "Directi"
},
{
"code": null,
"e": 8271,
"s": 8262,
"text": "triangle"
},
{
"code": null,
"e": 8282,
"s": 8271,
"text": "Algorithms"
},
{
"code": null,
"e": 8290,
"s": 8282,
"text": "Directi"
},
{
"code": null,
"e": 8301,
"s": 8290,
"text": "Algorithms"
}
] |
PHP program to add item at the beginning of associative array
|
11 Feb, 2019
In PHP associative array is the type of array where the index need not to be strictly sequential like indexed array. Normally add a new element in an existing associative array it will get appended at the end of that array.
Example:
<?php // Existing array$arr = array('one' => 1, 'two' => 2); // New element$arr['zero'] = 0; // Final arrayprint_r($arr); ?>
Array
(
[one] => 1
[two] => 2
[zero] => 0
)
So, a new element can not be added directly at the beginning of an associative array but the existing array can be appended at the end of a new array where the first element is the new element.It means add the new element in the beginning first the new element need to be put in an empty array as first element and then the array need to be merged with the existing array. In PHP, there are two ways to merge arrays they are array_merge() function and by using array union(+) operator.
In case of array_merge() function if two arrays have a same key then the value corresponding to the key in later array in considered in the resulting array. But in case of indexed array the elements simply get appended and re-indexing is done for all the element in the resulting array.
Syntax:
array array_merge( $arr1, $arr2 )
In case of array union(+) operator if two arrays have same key then the value corresponding to the key in first array in considered in the resulting array, this also applies in the indexed array, if two array have an element of common index then only the element from first array will be considered in the resulting array.
Syntax:
$arr3 = $arr1 + $arr2
Program: PHP program to add a new item at the beginning of an associative array.
<?php // Adding a new element at the beginning of an array // Existing array$arr = array('one' => 1, 'two' => 2, 'three' => 3); // New element to be added at 'zero' => 0 // Create an array using the new element$temp = array('zero' => 0); // Append the $temp in the beginning of $arr // Using array union(+) operator$arr2 = $temp + $arr; echo "Result of array union(+) : ";print_r($arr2); // Using array_merge() function$arr3 = array_merge($temp, $arr); echo "\n" . "Result of array_merge() : ";print_r($arr3); ?>
Result of array union(+) : Array
(
[zero] => 0
[one] => 1
[two] => 2
[three] => 3
)
Result of array_merge() : Array
(
[zero] => 0
[one] => 1
[two] => 2
[three] => 3
)
Picked
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
Split a comma delimited string into an array in PHP
How to get parameters from a URL string in PHP?
Download file from URL using PHP
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
Split a comma delimited string into an array in PHP
How to get parameters from a URL string in PHP?
How to fetch data from localserver database and display on HTML table using PHP ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Feb, 2019"
},
{
"code": null,
"e": 252,
"s": 28,
"text": "In PHP associative array is the type of array where the index need not to be strictly sequential like indexed array. Normally add a new element in an existing associative array it will get appended at the end of that array."
},
{
"code": null,
"e": 261,
"s": 252,
"text": "Example:"
},
{
"code": "<?php // Existing array$arr = array('one' => 1, 'two' => 2); // New element$arr['zero'] = 0; // Final arrayprint_r($arr); ?>",
"e": 398,
"s": 261,
"text": null
},
{
"code": null,
"e": 455,
"s": 398,
"text": "Array\n(\n [one] => 1\n [two] => 2\n [zero] => 0\n)\n"
},
{
"code": null,
"e": 941,
"s": 455,
"text": "So, a new element can not be added directly at the beginning of an associative array but the existing array can be appended at the end of a new array where the first element is the new element.It means add the new element in the beginning first the new element need to be put in an empty array as first element and then the array need to be merged with the existing array. In PHP, there are two ways to merge arrays they are array_merge() function and by using array union(+) operator."
},
{
"code": null,
"e": 1228,
"s": 941,
"text": "In case of array_merge() function if two arrays have a same key then the value corresponding to the key in later array in considered in the resulting array. But in case of indexed array the elements simply get appended and re-indexing is done for all the element in the resulting array."
},
{
"code": null,
"e": 1236,
"s": 1228,
"text": "Syntax:"
},
{
"code": null,
"e": 1270,
"s": 1236,
"text": "array array_merge( $arr1, $arr2 )"
},
{
"code": null,
"e": 1593,
"s": 1270,
"text": "In case of array union(+) operator if two arrays have same key then the value corresponding to the key in first array in considered in the resulting array, this also applies in the indexed array, if two array have an element of common index then only the element from first array will be considered in the resulting array."
},
{
"code": null,
"e": 1601,
"s": 1593,
"text": "Syntax:"
},
{
"code": null,
"e": 1623,
"s": 1601,
"text": "$arr3 = $arr1 + $arr2"
},
{
"code": null,
"e": 1704,
"s": 1623,
"text": "Program: PHP program to add a new item at the beginning of an associative array."
},
{
"code": "<?php // Adding a new element at the beginning of an array // Existing array$arr = array('one' => 1, 'two' => 2, 'three' => 3); // New element to be added at 'zero' => 0 // Create an array using the new element$temp = array('zero' => 0); // Append the $temp in the beginning of $arr // Using array union(+) operator$arr2 = $temp + $arr; echo \"Result of array union(+) : \";print_r($arr2); // Using array_merge() function$arr3 = array_merge($temp, $arr); echo \"\\n\" . \"Result of array_merge() : \";print_r($arr3); ?>",
"e": 2259,
"s": 1704,
"text": null
},
{
"code": null,
"e": 2460,
"s": 2259,
"text": "Result of array union(+) : Array\n(\n [zero] => 0\n [one] => 1\n [two] => 2\n [three] => 3\n)\n\nResult of array_merge() : Array\n(\n [zero] => 0\n [one] => 1\n [two] => 2\n [three] => 3\n)\n"
},
{
"code": null,
"e": 2467,
"s": 2460,
"text": "Picked"
},
{
"code": null,
"e": 2471,
"s": 2467,
"text": "PHP"
},
{
"code": null,
"e": 2484,
"s": 2471,
"text": "PHP Programs"
},
{
"code": null,
"e": 2501,
"s": 2484,
"text": "Web Technologies"
},
{
"code": null,
"e": 2505,
"s": 2501,
"text": "PHP"
},
{
"code": null,
"e": 2603,
"s": 2505,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2643,
"s": 2603,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 2688,
"s": 2643,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 2740,
"s": 2688,
"text": "Split a comma delimited string into an array in PHP"
},
{
"code": null,
"e": 2788,
"s": 2740,
"text": "How to get parameters from a URL string in PHP?"
},
{
"code": null,
"e": 2821,
"s": 2788,
"text": "Download file from URL using PHP"
},
{
"code": null,
"e": 2861,
"s": 2821,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 2913,
"s": 2861,
"text": "How to call PHP function on the click of a Button ?"
},
{
"code": null,
"e": 2965,
"s": 2913,
"text": "Split a comma delimited string into an array in PHP"
},
{
"code": null,
"e": 3013,
"s": 2965,
"text": "How to get parameters from a URL string in PHP?"
}
] |
jQuery | element + next Selector
|
19 Aug, 2021
The (“element + next”) selector selects in jQuery used to select the just “next” element of the specified “element”. This selector only works when the “next” element is placed just after the specified element.
For Example:
If the statement is $(“div + p”) then this will only select the first “p” element which is just next to “div” and the other “p” element are ignored.
But if the statement is $(“div + p”) and a “h1” is placed in between the selected “div” and “p” element then this selector will not work and “p” element will remain noneffective.
Syntax:
$("element + next")
Parameter: Here, parameter are required and this will specifies any valid elements.
Return Value: This will return the selected element with the specified change.
Example-1: Here the paragraph element is just next to the div element.
HTML
<!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> $(document).ready(function() { $("div + p").css("background-color", "lightgreen"); }); </script> <style> body { width: 80%; height: 40%; padding: 10px; border: 2px solid green; font-size: 20px; } div { border: 1px solid green; padding: 10px; } </style></head> <body> <div>Welcome to GfG.!</div> <p>This is first paragraph element.</p> <p>This is second paragraph element.</p> </body> </html>
Output:
Example-2: Here, heading element is in between the paragraph and the div element. So the no change will take place to the “p” element.
HTML
<!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> $(document).ready(function() { $("button").click(function() { $("div + p").css("background-color", "lightgreen"); }); }); </script> <style> body { width: 80%; height: 40%; padding: 10px; border: 2px solid green; font-size: 20px; } div { border: 1px solid green; padding: 10px; } </style></head> <body> <div>Welcome to GfG.!</div> <h1>Heading element ios here.</h1> <p>This is first paragraph element.</p> <p>This is second paragraph element.</p> <button>Submit</button> </body> </html>
Output:
Before Click:
After Click:
sagar0719kumar
jQuery-Selectors
Picked
JQuery
Web Technologies
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 ?
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": 28,
"s": 0,
"text": "\n19 Aug, 2021"
},
{
"code": null,
"e": 239,
"s": 28,
"text": "The (“element + next”) selector selects in jQuery used to select the just “next” element of the specified “element”. This selector only works when the “next” element is placed just after the specified element. "
},
{
"code": null,
"e": 253,
"s": 239,
"text": "For Example: "
},
{
"code": null,
"e": 403,
"s": 253,
"text": "If the statement is $(“div + p”) then this will only select the first “p” element which is just next to “div” and the other “p” element are ignored. "
},
{
"code": null,
"e": 582,
"s": 403,
"text": "But if the statement is $(“div + p”) and a “h1” is placed in between the selected “div” and “p” element then this selector will not work and “p” element will remain noneffective."
},
{
"code": null,
"e": 592,
"s": 582,
"text": "Syntax: "
},
{
"code": null,
"e": 612,
"s": 592,
"text": "$(\"element + next\")"
},
{
"code": null,
"e": 696,
"s": 612,
"text": "Parameter: Here, parameter are required and this will specifies any valid elements."
},
{
"code": null,
"e": 775,
"s": 696,
"text": "Return Value: This will return the selected element with the specified change."
},
{
"code": null,
"e": 848,
"s": 775,
"text": "Example-1: Here the paragraph element is just next to the div element. "
},
{
"code": null,
"e": 853,
"s": 848,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script> $(document).ready(function() { $(\"div + p\").css(\"background-color\", \"lightgreen\"); }); </script> <style> body { width: 80%; height: 40%; padding: 10px; border: 2px solid green; font-size: 20px; } div { border: 1px solid green; padding: 10px; } </style></head> <body> <div>Welcome to GfG.!</div> <p>This is first paragraph element.</p> <p>This is second paragraph element.</p> </body> </html>",
"e": 1572,
"s": 853,
"text": null
},
{
"code": null,
"e": 1581,
"s": 1572,
"text": "Output: "
},
{
"code": null,
"e": 1718,
"s": 1581,
"text": "Example-2: Here, heading element is in between the paragraph and the div element. So the no change will take place to the “p” element. "
},
{
"code": null,
"e": 1723,
"s": 1718,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script> $(document).ready(function() { $(\"button\").click(function() { $(\"div + p\").css(\"background-color\", \"lightgreen\"); }); }); </script> <style> body { width: 80%; height: 40%; padding: 10px; border: 2px solid green; font-size: 20px; } div { border: 1px solid green; padding: 10px; } </style></head> <body> <div>Welcome to GfG.!</div> <h1>Heading element ios here.</h1> <p>This is first paragraph element.</p> <p>This is second paragraph element.</p> <button>Submit</button> </body> </html>",
"e": 2574,
"s": 1723,
"text": null
},
{
"code": null,
"e": 2583,
"s": 2574,
"text": "Output: "
},
{
"code": null,
"e": 2598,
"s": 2583,
"text": "Before Click: "
},
{
"code": null,
"e": 2612,
"s": 2598,
"text": "After Click: "
},
{
"code": null,
"e": 2629,
"s": 2614,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 2646,
"s": 2629,
"text": "jQuery-Selectors"
},
{
"code": null,
"e": 2653,
"s": 2646,
"text": "Picked"
},
{
"code": null,
"e": 2660,
"s": 2653,
"text": "JQuery"
},
{
"code": null,
"e": 2677,
"s": 2660,
"text": "Web Technologies"
},
{
"code": null,
"e": 2775,
"s": 2677,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2804,
"s": 2775,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 2838,
"s": 2804,
"text": "jQuery | children() with Examples"
},
{
"code": null,
"e": 2892,
"s": 2838,
"text": "Scroll to the top of the page using JavaScript/jQuery"
},
{
"code": null,
"e": 2948,
"s": 2892,
"text": "How to Dynamically Add/Remove Table Rows using jQuery ?"
},
{
"code": null,
"e": 3005,
"s": 2948,
"text": "How to get the value in an input text box using jQuery ?"
},
{
"code": null,
"e": 3067,
"s": 3005,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3128,
"s": 3067,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3178,
"s": 3128,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 3221,
"s": 3178,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Workflow of OAuth 2.0
|
22 Sep, 2021
OAuth2.0 is an Open industry-standard authorization protocol that allows a third party to gain limited access to another HTTP service, such as Google, Facebook, and GitHub, on behalf of a user, once the user grants permission to access their credentials.
Most websites require you to complete a registration process before you can access their content. It is likely that you have come across some buttons for logging in with Google, Facebook, or another service.
GeeeksforGeeks Registration Page
Clicking those buttons will get you access to these third-party services without entering any credentials. I’m sure you’re wondering how this happens. OAuth brings this to light.
Let’s have a quick refresher on Authentication and Authorization before we dive into OAuth. Authorization refers to the process by which an administrator grants access to authenticated users, whereas authentication verifies that the user is who they claim to be.
Consider the GeeksforGeeks website as an example.
As a reader, you can read blogs without authenticating, but to add comments, you must register. Once you’ve signed up, you can access the free courses, improve articles and contribute. As a contributor, you have the right to edit your articles.
Let us now discuss OAuth.
OAuth is an open-standard authorization framework that enables third-party applications to gain limited access to user’s data.
Essentially, OAuth is about delegated access.
Delegation is a process in which an owner authorizes a service provider to perform certain tasks on the owner’s behalf. Here the task is to provide limited access to another party.
Let’s take two real-life examples;
House owners often approach real estate agents to sell their house. The house owner authorizes the real estate agent by giving him/her the key. Upon the owner’s consent, the agents show the buyers the property. The buyer is welcome to view the property, but they are not permitted to occupy it. In this scenario, the buyer has limited access, and the access is limited by the real estate agent who is acting on the owner’s behalf.
A classic example of valet parking is often retold to understand this concept. In this case, the car owner has access to both the car and the valet. To have his car parked for him, the car owner gives the valet key to the attendant. The valet key starts the car and opens the driver’s side door but prevents the valet from accessing valuables in the trunk or glove box.
Thus, the Valet key has delegated the task of limiting the access of the valet.
OAuth allows granular access levels. Rather than entrusting our entire protected data to a third party, we would prefer to share just the necessary data with them. Thus, we need a trusted intermediary that would grant limited access(known as scope) to the editor without revealing the user’s credentials once the user has granted permission.(known as consent).
Here’s an example of an application for editing photos.
You go to a photo editing app to resize an image. They ask you to upload the image you want to edit from your Google Drive account. The third party only needs access to the single photo you need to edit. Oauth will ensure that the photo editor gets just that.
Let’s take another example, you would like to share your edited picture with your friend, but they must have the same editing software. The editing software cannot request your Google account credentials; instead, it redirects you to your account. If you choose to invite your friend through that app, the app will request access to your Google address book to send the invitation.
Read/write only -A third party can only read your data, not modify it. In some instances, it can also request content modifications on your account. For example, you can cross-post a picture from your Instagram account to your Facebook account.
Revoke Access –You can deauthorize Instagram’s access to your Facebook wall so it can no longer post on your wall.
Before we get into how OAuth works, we’ll discuss the central components of OAuth for more clarity.
The elements of OAuth are listed below:
ActorsScopes and ConsentTokensFlows
Actors
Scopes and Consent
Tokens
Flows
OAuth Interactions have the following Actors:
OAuth2.0 Actors
Resources are protected data that require OAuth to access them.
Resource Owner: Owns the data in the resource server. An entity capable of granting access to protected data. For example, a user Google Drive account.
Resource Server: The API which stores the data. For example, Google Photos or Google Drive.
Client: It is a third-party application that wants to access your data, for example, a photo editor application.
There seems to be an interaction between two services for accessing resources, but the issue is who is responsible for the security. The resource server, in this case, Google Drive, is responsible for ensuring the required authentication.
OAuth is coupled with the Resource Server. Google implements OAuth to validate the authorization of whoever accesses the resource.
Authorization Server: OAuth’s main engine that creates access tokens.
The scopes define the specific actions that apps can perform on behalf of the user. They are the bundles of permissions asked for by the client when requesting a token.
For example, we can share our LinkedIn posts on Twitter via LinkedIn itself. Given that it has write-only access, it cannot access other pieces of information, such as our conversations.
On the Consent screen, a user learns who is attempting to access their data and what kind of data they want to access, and the user must express their consent to allow third-party access to the requested data. You grant access to your IDE, such as CodingSandbox, when you link your GitHub account to it or import an existing repository. The Github account you are using will send you an email confirming this.
GitHub confirmation Email
Now let’s talk about access and refresh tokens.
A token is a piece of data containing just enough information to be able to verify a user’s identity or authorize them to perform a certain action.
We can comprehend access tokens and refresh tokens by using the analogy of movie theatres. Suppose you (resource owner) wanted to watch the latest Marvel movie (Shang Chi and the Legends of the Ten Rings), you’d go to the ticket vendor (auth server), choose the movie, and buy the ticket(token) for that movie (scope). Ticket validity now pertains only to a certain time frame and to a specific show. After the security guy checks your ticket, he lets you into the theatre (resource server) and directs you to your assigned seat.
If you give your ticket to a friend, they can use it to watch the movie. An OAuth access token works the same way. Anyone who has the access token can use it to make API requests. Therefore, they’re called “Bearer Tokens”. You will not find your personal information on the ticket. Similarly, OAuth access tokens can be created without actually including information about the user to whom they were issued. Like a movie ticket, an OAuth access token is valid for a certain period and then expires. Security personnel usually ask for ID proof to verify your age, especially for A-rated movies. Bookings made online will be authenticated by the app before tickets are provided to you.
So, Access tokens are credentials used to access protected resources. Each token represents the scope and duration of access granted by the resource owner and enforced by the authorization server. The format, structure, and method of utilizing access tokens can be different depending on the resource server’s security needs.
A decoded access token, that follows a JWT format.
{ "iss": "https://YOUR_DOMAIN/",
"sub": "auth0|123456",
"aud": [ "my-api-identifier", "https://YOUR_DOMAIN/userinfo" ],
"azp": "YOUR_CLIENT_ID", "exp": 1474178924, "iat": 1474173924,
"scope": "openid profile email address phone read:meetings" }
Now that your showtime has expired and you want to watch another movie, you need to buy a new ticket. Upon your last purchase, you received a Gift card that is valid for three months. You can use this card to purchase a new ticket. In this scenario, the gift card is analogous to Refresh Tokens. A Refresh token is a string issued to the client by the authorization server and is used to obtain a new access token when the current access token becomes invalid.
They do not refresh an existing access token, they simply request a new one. The expiration time for refresh tokens tends to be much longer than for access tokens. In our case, the gift card is valid for three months, while the ticket is valid for two hours. Unlike the original access token, it contains less information.
Let us now look at how OAuth works when uploading a picture to a photo editor to understand the workflow.
The resource owner or user wishes to resize the image, so he goes to the editor (client), tells the client that the image is in Google Drive (resource owner), asking the client to bring it for editing.The client sends a request to the authorization server to access the image. The server asks the user to grant permissions for the same.Once the user allows third-party access and logs into the website using Google, the authorization server sends a short-lived authorization code to the client.Clients exchange auth codes for access tokens, which define the scope and duration of user access.The Authorization Server validates the access token, and the editor fetches the image that the user wants to edit from their Google Drive account.
The resource owner or user wishes to resize the image, so he goes to the editor (client), tells the client that the image is in Google Drive (resource owner), asking the client to bring it for editing.
The client sends a request to the authorization server to access the image. The server asks the user to grant permissions for the same.
Once the user allows third-party access and logs into the website using Google, the authorization server sends a short-lived authorization code to the client.
Clients exchange auth codes for access tokens, which define the scope and duration of user access.
The Authorization Server validates the access token, and the editor fetches the image that the user wants to edit from their Google Drive account.
Authorization code flow
The client requests authorization by directing the resource owner to the authorization server.The authorization server authenticates the resource owner and informs the user about the client and the data requested by the client. Clients cannot access user credentials since authentication is performed by the authentication server.Once the user grants permission to access the protected data, the authorization server redirects the user to the client with the temporary authorization code.The client requests an access token in exchange for the authorization code. The authorization server authenticates the client, verifies the code, and will issue an access token to the client.Now the client can access protected resources by presenting the access token to the resource server.If the access token is valid, the resource server returns the requested resources to the client.
The client requests authorization by directing the resource owner to the authorization server.
The authorization server authenticates the resource owner and informs the user about the client and the data requested by the client. Clients cannot access user credentials since authentication is performed by the authentication server.
Once the user grants permission to access the protected data, the authorization server redirects the user to the client with the temporary authorization code.
The client requests an access token in exchange for the authorization code.
The authorization server authenticates the client, verifies the code, and will issue an access token to the client.
Now the client can access protected resources by presenting the access token to the resource server.
If the access token is valid, the resource server returns the requested resources to the client.
Implicit Grant flow is an authorization flow for browser-based apps. Implicit Grant Type was designed for single-page JavaScript applications for getting access tokens without an intermediate code exchange step. Single-page applications are those in which the page does not reload and the required contents are dynamically loaded. Take Facebook or Instagram, for instance. Instagram doesn’t require you to reload your application to see the comments on your post. Updates occur without reloading the page. Implicit grant flow is thus applicable in such applications.
The implicit flow issues an access token directly to the client instead of issuing an authorization code.
The Implicit Grant:
Constructs a link and the redirection of the user’s browser to that URL.
https://example-app.com/redirect #access_token=g0ZGZmPj4nOWIlTTk3Pw1Tk4ZTKyZGI3 &token_type=Bearer &expires_in=400 &state=xcoVv98y3kd55vuzwwe3kcq
If the user accepts the request, the authorization server will return the browser to the redirect URL supplied by the Client Application with a token and state appended to the fragment part of the URL. (A state is a string of unique and non-predictable characters.)
To prevent cross-site forging attacks, the application should test the incoming state value against the value that was originally set, once a redirect is initiated. (We are a target of an attack if we receive a response with a state that does not match).
The redirection URI includes the access token, which is sent to the client. Clients now have access to the resources granted by resource owners.
This flow is deprecated due to the lack of client authentication. A malicious application can pretend to be the client if it obtains the client credentials, which are visible if one inspects the source code of the page, and this leaves the owner vulnerable to phishing attacks.
There is no secure backchannel like an intermediate authorization code – all communication is carried out via browser redirects in implicit grant processing. To mitigate the risk of the access token being exposed to potential attacks, most servers issue short-lived access tokens.
In this flow, the owner’s credentials, such as username and password, are exchanged for an access token. The user gives the app their credentials directly, and the app then utilizes those credentials to get an access token from a service.
Client applications ask the user for credentials.The client sends a request to the authorization server to obtain the access token.The authorization server authenticates the client, determines if it is authorized to make this request, and verifies the user’s credentials. It returns an access token if everything is verified successfully.The OAuth client makes an API call to the resource server using the access token to access the protected data.The resource server grants access.
Client applications ask the user for credentials.
The client sends a request to the authorization server to obtain the access token.
The authorization server authenticates the client, determines if it is authorized to make this request, and verifies the user’s credentials. It returns an access token if everything is verified successfully.
The OAuth client makes an API call to the resource server using the access token to access the protected data.
The resource server grants access.
The Microsoft identity platform, for example, supports the resource owner password credentials flow, which enables applications to sign in users by directly using their credentials.
It is appropriate for resource owners with a trusted relationship with their clients. It is not recommended for third-party applications that are not officially released by the API provider.
Impersonation: Someone may pose as the user to request the resource, so there is no way to verify that the owner made the request.Phishing Attacks – A random client application asks the user for credentials. Instead of redirecting you to your Google account when an application requests your Google username and password.The user’s credentials could be leaked maliciously to an attacker.A client application can request any scope it desires from the authorization server. Despite controlled scopes, a client application may be able to access user resources without the user’s permission.
Impersonation: Someone may pose as the user to request the resource, so there is no way to verify that the owner made the request.
Phishing Attacks – A random client application asks the user for credentials. Instead of redirecting you to your Google account when an application requests your Google username and password.
The user’s credentials could be leaked maliciously to an attacker.
A client application can request any scope it desires from the authorization server. Despite controlled scopes, a client application may be able to access user resources without the user’s permission.
For example, in 2017, a fake Google Docs application was used to fool users into thinking it was the legitimate product offered by Google. The attackers used this app to access users’ email accounts by abusing the OAuth token.
The Client credentials flow permits a client service to use its own credentials, instead of impersonating a user to access the protected data. In this case, authorization scope is limited to client-controlled protected resources.
The client application makes an authorization request to the Authorization Server using its client credentials.If the credentials are accurate, the server responds with an access token.The app uses the access token to make requests to the resource server.The resource server validates the token before responding to the request.
The client application makes an authorization request to the Authorization Server using its client credentials.
If the credentials are accurate, the server responds with an access token.
The app uses the access token to make requests to the resource server.
The resource server validates the token before responding to the request.
The versions of OAuth are not compatible, as OAuth 2.0 is a complete overhaul of OAuth 1.0. Implementing OAuth 2.0 is easier and faster. OAuth 1.0 had complicated cryptographic requirements, supported only three flows, and was not scalable.
Now that you know what happens behind the scenes when you forget your Facebook password, and it verifies you through your Google account and allows you to change it, or whenever any other app redirects you to your Google account, you will have a better understanding of how it works.
Blogathon-2021
Advanced Computer Subject
Blogathon
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Sep, 2021"
},
{
"code": null,
"e": 308,
"s": 52,
"text": "OAuth2.0 is an Open industry-standard authorization protocol that allows a third party to gain limited access to another HTTP service, such as Google, Facebook, and GitHub, on behalf of a user, once the user grants permission to access their credentials. "
},
{
"code": null,
"e": 516,
"s": 308,
"text": "Most websites require you to complete a registration process before you can access their content. It is likely that you have come across some buttons for logging in with Google, Facebook, or another service."
},
{
"code": null,
"e": 550,
"s": 516,
"text": "GeeeksforGeeks Registration Page "
},
{
"code": null,
"e": 729,
"s": 550,
"text": "Clicking those buttons will get you access to these third-party services without entering any credentials. I’m sure you’re wondering how this happens. OAuth brings this to light."
},
{
"code": null,
"e": 992,
"s": 729,
"text": "Let’s have a quick refresher on Authentication and Authorization before we dive into OAuth. Authorization refers to the process by which an administrator grants access to authenticated users, whereas authentication verifies that the user is who they claim to be."
},
{
"code": null,
"e": 1042,
"s": 992,
"text": "Consider the GeeksforGeeks website as an example."
},
{
"code": null,
"e": 1287,
"s": 1042,
"text": "As a reader, you can read blogs without authenticating, but to add comments, you must register. Once you’ve signed up, you can access the free courses, improve articles and contribute. As a contributor, you have the right to edit your articles."
},
{
"code": null,
"e": 1313,
"s": 1287,
"text": "Let us now discuss OAuth."
},
{
"code": null,
"e": 1440,
"s": 1313,
"text": "OAuth is an open-standard authorization framework that enables third-party applications to gain limited access to user’s data."
},
{
"code": null,
"e": 1486,
"s": 1440,
"text": "Essentially, OAuth is about delegated access."
},
{
"code": null,
"e": 1667,
"s": 1486,
"text": "Delegation is a process in which an owner authorizes a service provider to perform certain tasks on the owner’s behalf. Here the task is to provide limited access to another party."
},
{
"code": null,
"e": 1702,
"s": 1667,
"text": "Let’s take two real-life examples;"
},
{
"code": null,
"e": 2133,
"s": 1702,
"text": "House owners often approach real estate agents to sell their house. The house owner authorizes the real estate agent by giving him/her the key. Upon the owner’s consent, the agents show the buyers the property. The buyer is welcome to view the property, but they are not permitted to occupy it. In this scenario, the buyer has limited access, and the access is limited by the real estate agent who is acting on the owner’s behalf."
},
{
"code": null,
"e": 2504,
"s": 2133,
"text": "A classic example of valet parking is often retold to understand this concept. In this case, the car owner has access to both the car and the valet. To have his car parked for him, the car owner gives the valet key to the attendant. The valet key starts the car and opens the driver’s side door but prevents the valet from accessing valuables in the trunk or glove box."
},
{
"code": null,
"e": 2584,
"s": 2504,
"text": "Thus, the Valet key has delegated the task of limiting the access of the valet."
},
{
"code": null,
"e": 2945,
"s": 2584,
"text": "OAuth allows granular access levels. Rather than entrusting our entire protected data to a third party, we would prefer to share just the necessary data with them. Thus, we need a trusted intermediary that would grant limited access(known as scope) to the editor without revealing the user’s credentials once the user has granted permission.(known as consent)."
},
{
"code": null,
"e": 3001,
"s": 2945,
"text": "Here’s an example of an application for editing photos."
},
{
"code": null,
"e": 3261,
"s": 3001,
"text": "You go to a photo editing app to resize an image. They ask you to upload the image you want to edit from your Google Drive account. The third party only needs access to the single photo you need to edit. Oauth will ensure that the photo editor gets just that."
},
{
"code": null,
"e": 3643,
"s": 3261,
"text": "Let’s take another example, you would like to share your edited picture with your friend, but they must have the same editing software. The editing software cannot request your Google account credentials; instead, it redirects you to your account. If you choose to invite your friend through that app, the app will request access to your Google address book to send the invitation."
},
{
"code": null,
"e": 3888,
"s": 3643,
"text": "Read/write only -A third party can only read your data, not modify it. In some instances, it can also request content modifications on your account. For example, you can cross-post a picture from your Instagram account to your Facebook account."
},
{
"code": null,
"e": 4003,
"s": 3888,
"text": "Revoke Access –You can deauthorize Instagram’s access to your Facebook wall so it can no longer post on your wall."
},
{
"code": null,
"e": 4103,
"s": 4003,
"text": "Before we get into how OAuth works, we’ll discuss the central components of OAuth for more clarity."
},
{
"code": null,
"e": 4143,
"s": 4103,
"text": "The elements of OAuth are listed below:"
},
{
"code": null,
"e": 4179,
"s": 4143,
"text": "ActorsScopes and ConsentTokensFlows"
},
{
"code": null,
"e": 4186,
"s": 4179,
"text": "Actors"
},
{
"code": null,
"e": 4205,
"s": 4186,
"text": "Scopes and Consent"
},
{
"code": null,
"e": 4212,
"s": 4205,
"text": "Tokens"
},
{
"code": null,
"e": 4218,
"s": 4212,
"text": "Flows"
},
{
"code": null,
"e": 4265,
"s": 4218,
"text": " OAuth Interactions have the following Actors:"
},
{
"code": null,
"e": 4282,
"s": 4265,
"text": "OAuth2.0 Actors "
},
{
"code": null,
"e": 4346,
"s": 4282,
"text": "Resources are protected data that require OAuth to access them."
},
{
"code": null,
"e": 4498,
"s": 4346,
"text": "Resource Owner: Owns the data in the resource server. An entity capable of granting access to protected data. For example, a user Google Drive account."
},
{
"code": null,
"e": 4590,
"s": 4498,
"text": "Resource Server: The API which stores the data. For example, Google Photos or Google Drive."
},
{
"code": null,
"e": 4703,
"s": 4590,
"text": "Client: It is a third-party application that wants to access your data, for example, a photo editor application."
},
{
"code": null,
"e": 4942,
"s": 4703,
"text": "There seems to be an interaction between two services for accessing resources, but the issue is who is responsible for the security. The resource server, in this case, Google Drive, is responsible for ensuring the required authentication."
},
{
"code": null,
"e": 5073,
"s": 4942,
"text": "OAuth is coupled with the Resource Server. Google implements OAuth to validate the authorization of whoever accesses the resource."
},
{
"code": null,
"e": 5143,
"s": 5073,
"text": "Authorization Server: OAuth’s main engine that creates access tokens."
},
{
"code": null,
"e": 5312,
"s": 5143,
"text": "The scopes define the specific actions that apps can perform on behalf of the user. They are the bundles of permissions asked for by the client when requesting a token."
},
{
"code": null,
"e": 5499,
"s": 5312,
"text": "For example, we can share our LinkedIn posts on Twitter via LinkedIn itself. Given that it has write-only access, it cannot access other pieces of information, such as our conversations."
},
{
"code": null,
"e": 5909,
"s": 5499,
"text": "On the Consent screen, a user learns who is attempting to access their data and what kind of data they want to access, and the user must express their consent to allow third-party access to the requested data. You grant access to your IDE, such as CodingSandbox, when you link your GitHub account to it or import an existing repository. The Github account you are using will send you an email confirming this."
},
{
"code": null,
"e": 5935,
"s": 5909,
"text": "GitHub confirmation Email"
},
{
"code": null,
"e": 5984,
"s": 5935,
"text": "Now let’s talk about access and refresh tokens. "
},
{
"code": null,
"e": 6132,
"s": 5984,
"text": "A token is a piece of data containing just enough information to be able to verify a user’s identity or authorize them to perform a certain action."
},
{
"code": null,
"e": 6662,
"s": 6132,
"text": "We can comprehend access tokens and refresh tokens by using the analogy of movie theatres. Suppose you (resource owner) wanted to watch the latest Marvel movie (Shang Chi and the Legends of the Ten Rings), you’d go to the ticket vendor (auth server), choose the movie, and buy the ticket(token) for that movie (scope). Ticket validity now pertains only to a certain time frame and to a specific show. After the security guy checks your ticket, he lets you into the theatre (resource server) and directs you to your assigned seat."
},
{
"code": null,
"e": 7346,
"s": 6662,
"text": "If you give your ticket to a friend, they can use it to watch the movie. An OAuth access token works the same way. Anyone who has the access token can use it to make API requests. Therefore, they’re called “Bearer Tokens”. You will not find your personal information on the ticket. Similarly, OAuth access tokens can be created without actually including information about the user to whom they were issued. Like a movie ticket, an OAuth access token is valid for a certain period and then expires. Security personnel usually ask for ID proof to verify your age, especially for A-rated movies. Bookings made online will be authenticated by the app before tickets are provided to you."
},
{
"code": null,
"e": 7672,
"s": 7346,
"text": "So, Access tokens are credentials used to access protected resources. Each token represents the scope and duration of access granted by the resource owner and enforced by the authorization server. The format, structure, and method of utilizing access tokens can be different depending on the resource server’s security needs."
},
{
"code": null,
"e": 7724,
"s": 7672,
"text": "A decoded access token, that follows a JWT format. "
},
{
"code": null,
"e": 7984,
"s": 7724,
"text": "{ \"iss\": \"https://YOUR_DOMAIN/\",\n \"sub\": \"auth0|123456\",\n \"aud\": [ \"my-api-identifier\", \"https://YOUR_DOMAIN/userinfo\" ],\n \"azp\": \"YOUR_CLIENT_ID\", \"exp\": 1474178924, \"iat\": 1474173924,\n \"scope\": \"openid profile email address phone read:meetings\" } "
},
{
"code": null,
"e": 8446,
"s": 7984,
"text": " Now that your showtime has expired and you want to watch another movie, you need to buy a new ticket. Upon your last purchase, you received a Gift card that is valid for three months. You can use this card to purchase a new ticket. In this scenario, the gift card is analogous to Refresh Tokens. A Refresh token is a string issued to the client by the authorization server and is used to obtain a new access token when the current access token becomes invalid."
},
{
"code": null,
"e": 8769,
"s": 8446,
"text": "They do not refresh an existing access token, they simply request a new one. The expiration time for refresh tokens tends to be much longer than for access tokens. In our case, the gift card is valid for three months, while the ticket is valid for two hours. Unlike the original access token, it contains less information."
},
{
"code": null,
"e": 8875,
"s": 8769,
"text": "Let us now look at how OAuth works when uploading a picture to a photo editor to understand the workflow."
},
{
"code": null,
"e": 9614,
"s": 8875,
"text": "The resource owner or user wishes to resize the image, so he goes to the editor (client), tells the client that the image is in Google Drive (resource owner), asking the client to bring it for editing.The client sends a request to the authorization server to access the image. The server asks the user to grant permissions for the same.Once the user allows third-party access and logs into the website using Google, the authorization server sends a short-lived authorization code to the client.Clients exchange auth codes for access tokens, which define the scope and duration of user access.The Authorization Server validates the access token, and the editor fetches the image that the user wants to edit from their Google Drive account."
},
{
"code": null,
"e": 9816,
"s": 9614,
"text": "The resource owner or user wishes to resize the image, so he goes to the editor (client), tells the client that the image is in Google Drive (resource owner), asking the client to bring it for editing."
},
{
"code": null,
"e": 9952,
"s": 9816,
"text": "The client sends a request to the authorization server to access the image. The server asks the user to grant permissions for the same."
},
{
"code": null,
"e": 10111,
"s": 9952,
"text": "Once the user allows third-party access and logs into the website using Google, the authorization server sends a short-lived authorization code to the client."
},
{
"code": null,
"e": 10210,
"s": 10111,
"text": "Clients exchange auth codes for access tokens, which define the scope and duration of user access."
},
{
"code": null,
"e": 10357,
"s": 10210,
"text": "The Authorization Server validates the access token, and the editor fetches the image that the user wants to edit from their Google Drive account."
},
{
"code": null,
"e": 10382,
"s": 10357,
"text": "Authorization code flow "
},
{
"code": null,
"e": 11258,
"s": 10382,
"text": "The client requests authorization by directing the resource owner to the authorization server.The authorization server authenticates the resource owner and informs the user about the client and the data requested by the client. Clients cannot access user credentials since authentication is performed by the authentication server.Once the user grants permission to access the protected data, the authorization server redirects the user to the client with the temporary authorization code.The client requests an access token in exchange for the authorization code. The authorization server authenticates the client, verifies the code, and will issue an access token to the client.Now the client can access protected resources by presenting the access token to the resource server.If the access token is valid, the resource server returns the requested resources to the client."
},
{
"code": null,
"e": 11353,
"s": 11258,
"text": "The client requests authorization by directing the resource owner to the authorization server."
},
{
"code": null,
"e": 11590,
"s": 11353,
"text": "The authorization server authenticates the resource owner and informs the user about the client and the data requested by the client. Clients cannot access user credentials since authentication is performed by the authentication server."
},
{
"code": null,
"e": 11749,
"s": 11590,
"text": "Once the user grants permission to access the protected data, the authorization server redirects the user to the client with the temporary authorization code."
},
{
"code": null,
"e": 11825,
"s": 11749,
"text": "The client requests an access token in exchange for the authorization code."
},
{
"code": null,
"e": 11942,
"s": 11825,
"text": " The authorization server authenticates the client, verifies the code, and will issue an access token to the client."
},
{
"code": null,
"e": 12043,
"s": 11942,
"text": "Now the client can access protected resources by presenting the access token to the resource server."
},
{
"code": null,
"e": 12140,
"s": 12043,
"text": "If the access token is valid, the resource server returns the requested resources to the client."
},
{
"code": null,
"e": 12707,
"s": 12140,
"text": "Implicit Grant flow is an authorization flow for browser-based apps. Implicit Grant Type was designed for single-page JavaScript applications for getting access tokens without an intermediate code exchange step. Single-page applications are those in which the page does not reload and the required contents are dynamically loaded. Take Facebook or Instagram, for instance. Instagram doesn’t require you to reload your application to see the comments on your post. Updates occur without reloading the page. Implicit grant flow is thus applicable in such applications."
},
{
"code": null,
"e": 12813,
"s": 12707,
"text": "The implicit flow issues an access token directly to the client instead of issuing an authorization code."
},
{
"code": null,
"e": 12833,
"s": 12813,
"text": "The Implicit Grant:"
},
{
"code": null,
"e": 12906,
"s": 12833,
"text": "Constructs a link and the redirection of the user’s browser to that URL."
},
{
"code": null,
"e": 13060,
"s": 12906,
"text": "https://example-app.com/redirect #access_token=g0ZGZmPj4nOWIlTTk3Pw1Tk4ZTKyZGI3 &token_type=Bearer &expires_in=400 &state=xcoVv98y3kd55vuzwwe3kcq "
},
{
"code": null,
"e": 13326,
"s": 13060,
"text": "If the user accepts the request, the authorization server will return the browser to the redirect URL supplied by the Client Application with a token and state appended to the fragment part of the URL. (A state is a string of unique and non-predictable characters.)"
},
{
"code": null,
"e": 13581,
"s": 13326,
"text": "To prevent cross-site forging attacks, the application should test the incoming state value against the value that was originally set, once a redirect is initiated. (We are a target of an attack if we receive a response with a state that does not match)."
},
{
"code": null,
"e": 13726,
"s": 13581,
"text": "The redirection URI includes the access token, which is sent to the client. Clients now have access to the resources granted by resource owners."
},
{
"code": null,
"e": 14004,
"s": 13726,
"text": "This flow is deprecated due to the lack of client authentication. A malicious application can pretend to be the client if it obtains the client credentials, which are visible if one inspects the source code of the page, and this leaves the owner vulnerable to phishing attacks."
},
{
"code": null,
"e": 14285,
"s": 14004,
"text": "There is no secure backchannel like an intermediate authorization code – all communication is carried out via browser redirects in implicit grant processing. To mitigate the risk of the access token being exposed to potential attacks, most servers issue short-lived access tokens."
},
{
"code": null,
"e": 14524,
"s": 14285,
"text": "In this flow, the owner’s credentials, such as username and password, are exchanged for an access token. The user gives the app their credentials directly, and the app then utilizes those credentials to get an access token from a service."
},
{
"code": null,
"e": 15007,
"s": 14524,
"text": "Client applications ask the user for credentials.The client sends a request to the authorization server to obtain the access token.The authorization server authenticates the client, determines if it is authorized to make this request, and verifies the user’s credentials. It returns an access token if everything is verified successfully.The OAuth client makes an API call to the resource server using the access token to access the protected data.The resource server grants access."
},
{
"code": null,
"e": 15057,
"s": 15007,
"text": "Client applications ask the user for credentials."
},
{
"code": null,
"e": 15140,
"s": 15057,
"text": "The client sends a request to the authorization server to obtain the access token."
},
{
"code": null,
"e": 15348,
"s": 15140,
"text": "The authorization server authenticates the client, determines if it is authorized to make this request, and verifies the user’s credentials. It returns an access token if everything is verified successfully."
},
{
"code": null,
"e": 15459,
"s": 15348,
"text": "The OAuth client makes an API call to the resource server using the access token to access the protected data."
},
{
"code": null,
"e": 15494,
"s": 15459,
"text": "The resource server grants access."
},
{
"code": null,
"e": 15676,
"s": 15494,
"text": "The Microsoft identity platform, for example, supports the resource owner password credentials flow, which enables applications to sign in users by directly using their credentials."
},
{
"code": null,
"e": 15867,
"s": 15676,
"text": "It is appropriate for resource owners with a trusted relationship with their clients. It is not recommended for third-party applications that are not officially released by the API provider."
},
{
"code": null,
"e": 16455,
"s": 15867,
"text": "Impersonation: Someone may pose as the user to request the resource, so there is no way to verify that the owner made the request.Phishing Attacks – A random client application asks the user for credentials. Instead of redirecting you to your Google account when an application requests your Google username and password.The user’s credentials could be leaked maliciously to an attacker.A client application can request any scope it desires from the authorization server. Despite controlled scopes, a client application may be able to access user resources without the user’s permission."
},
{
"code": null,
"e": 16586,
"s": 16455,
"text": "Impersonation: Someone may pose as the user to request the resource, so there is no way to verify that the owner made the request."
},
{
"code": null,
"e": 16778,
"s": 16586,
"text": "Phishing Attacks – A random client application asks the user for credentials. Instead of redirecting you to your Google account when an application requests your Google username and password."
},
{
"code": null,
"e": 16845,
"s": 16778,
"text": "The user’s credentials could be leaked maliciously to an attacker."
},
{
"code": null,
"e": 17046,
"s": 16845,
"text": "A client application can request any scope it desires from the authorization server. Despite controlled scopes, a client application may be able to access user resources without the user’s permission."
},
{
"code": null,
"e": 17273,
"s": 17046,
"text": "For example, in 2017, a fake Google Docs application was used to fool users into thinking it was the legitimate product offered by Google. The attackers used this app to access users’ email accounts by abusing the OAuth token."
},
{
"code": null,
"e": 17503,
"s": 17273,
"text": "The Client credentials flow permits a client service to use its own credentials, instead of impersonating a user to access the protected data. In this case, authorization scope is limited to client-controlled protected resources."
},
{
"code": null,
"e": 17832,
"s": 17503,
"text": "The client application makes an authorization request to the Authorization Server using its client credentials.If the credentials are accurate, the server responds with an access token.The app uses the access token to make requests to the resource server.The resource server validates the token before responding to the request."
},
{
"code": null,
"e": 17944,
"s": 17832,
"text": "The client application makes an authorization request to the Authorization Server using its client credentials."
},
{
"code": null,
"e": 18019,
"s": 17944,
"text": "If the credentials are accurate, the server responds with an access token."
},
{
"code": null,
"e": 18090,
"s": 18019,
"text": "The app uses the access token to make requests to the resource server."
},
{
"code": null,
"e": 18164,
"s": 18090,
"text": "The resource server validates the token before responding to the request."
},
{
"code": null,
"e": 18405,
"s": 18164,
"text": "The versions of OAuth are not compatible, as OAuth 2.0 is a complete overhaul of OAuth 1.0. Implementing OAuth 2.0 is easier and faster. OAuth 1.0 had complicated cryptographic requirements, supported only three flows, and was not scalable."
},
{
"code": null,
"e": 18689,
"s": 18405,
"text": "Now that you know what happens behind the scenes when you forget your Facebook password, and it verifies you through your Google account and allows you to change it, or whenever any other app redirects you to your Google account, you will have a better understanding of how it works."
},
{
"code": null,
"e": 18704,
"s": 18689,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 18730,
"s": 18704,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 18740,
"s": 18730,
"text": "Blogathon"
}
] |
Ternary Search Tree
|
14 Jun, 2022
A ternary search tree is a special trie data structure where the child nodes of a standard trie are ordered as a binary search tree.
Representation of ternary search trees: Unlike trie(standard) data structure where each node contains 26 pointers for its children, each node in a ternary search tree contains only 3 pointers: 1. The left pointer points to the node whose value is less than the value in the current node. 2. The equal pointer points to the node whose value is equal to the value in the current node. 3. The right pointer points to the node whose value is greater than the value in the current node.Apart from above three pointers, each node has a field to indicate data(character in case of dictionary) and another field to mark end of a string. So, more or less it is similar to BST which stores data based on some order. However, data in a ternary search tree is distributed over the nodes. e.g. It needs 4 nodes to store the word “Geek”.
Below figure shows how exactly the words in a ternary search tree are stored?
One of the advantage of using ternary search trees over tries is that ternary search trees are a more space efficient (involve only three pointers per node as compared to 26 in standard tries). Further, ternary search trees can be used any time a hashtable would be used to store strings.Tries are suitable when there is a proper distribution of words over the alphabets so that spaces are utilized most efficiently. Otherwise ternary search trees are better. Ternary search trees are efficient to use(in terms of space) when the strings to be stored share a common prefix.
Applications of ternary search trees: 1. Ternary search trees are efficient for queries like “Given a word, find the next word in dictionary(near-neighbor lookups)” or “Find all telephone numbers starting with 9342 or “typing few starting characters in a web browser displays all website names with this prefix”(Auto complete feature)”.2. Used in spell checks: Ternary search trees can be used as a dictionary to store all the words. Once the word is typed in an editor, the word can be parallelly searched in the ternary search tree to check for correct spelling.
Implementation: Following is C implementation of ternary search tree. The operations implemented are, search, insert, and traversal.
C++
C
// C++ program to demonstrate Ternary Search Tree (TST)// insert, traverse and search operations#include <bits/stdc++.h>using namespace std;#define MAX 50 // A node of ternary search treestruct Node { char data; // True if this character is last character of one of // the words unsigned isEndOfString = 1; Node *left, *eq, *right;}; // A utility function to create a new ternary search tree// nodeNode* newNode(char data){ Node* temp = new Node(); temp->data = data; temp->isEndOfString = 0; temp->left = temp->eq = temp->right = NULL; return temp;} // Function to insert a new word in a Ternary Search Treevoid insert(Node** root, char* word){ // Base Case: Tree is empty if (!(*root)) *root = newNode(*word); // If current character of word is smaller than root's // character, then insert this word in left subtree of // root if ((*word) < (*root)->data) insert(&((*root)->left), word); // If current character of word is greater than root's // character, then insert this word in right subtree of // root else if ((*word) > (*root)->data) insert(&((*root)->right), word); // If current character of word is same as root's // character, else { if (*(word + 1)) insert(&((*root)->eq), word + 1); // the last character of the word else (*root)->isEndOfString = 1; }} // A recursive function to traverse Ternary Search Treevoid traverseTSTUtil(Node* root, char* buffer, int depth){ if (root) { // First traverse the left subtree traverseTSTUtil(root->left, buffer, depth); // Store the character of this node buffer[depth] = root->data; if (root->isEndOfString) { buffer[depth + 1] = '\0'; cout << buffer << endl; } // Traverse the subtree using equal pointer (middle // subtree) traverseTSTUtil(root->eq, buffer, depth + 1); // Finally Traverse the right subtree traverseTSTUtil(root->right, buffer, depth); }} // The main function to traverse a Ternary Search Tree.// It mainly uses traverseTSTUtil()void traverseTST(struct Node* root){ char buffer[MAX]; traverseTSTUtil(root, buffer, 0);} // Function to search a given word in TSTint searchTST(Node* root, char* word){ if (!root) return 0; if (*word < (root)->data) return searchTST(root->left, word); else if (*word > (root)->data) return searchTST(root->right, word); else { if (*(word + 1) == '\0') return root->isEndOfString; return searchTST(root->eq, word + 1); }} // Driver program to test above functionsint main(){ Node* root = NULL; char cat[] = "cat"; char cats[] = "cats"; char up[] = "up"; char bug[] = "bug"; char bu[] = "bu"; insert(&root, cat); insert(&root, cats); insert(&root, up); insert(&root, bug); cout << "Following is traversal of ternary search " "tree\n"; traverseTST(root); cout << "\nFollowing are search results for cats, bu " "and cat respectively\n"; searchTST(root, cats) ? cout << "Found\n" : cout << "Not Found\n"; searchTST(root, bu) ? cout << "Found\n" : cout << "Not Found\n"; searchTST(root, cat) ? cout << "Found\n" : cout << "Not Found\n"; return 0;} // This code is contributed by tapeshdua420.
// C program to demonstrate Ternary Search Tree (TST) insert, traverse// and search operations#include <stdio.h>#include <stdlib.h>#define MAX 50 // A node of ternary search treestruct Node{ char data; // True if this character is last character of one of the words unsigned isEndOfString: 1; struct Node *left, *eq, *right;}; // A utility function to create a new ternary search tree nodestruct Node* newNode(char data){ struct Node* temp = (struct Node*) malloc(sizeof( struct Node )); temp->data = data; temp->isEndOfString = 0; temp->left = temp->eq = temp->right = NULL; return temp;} // Function to insert a new word in a Ternary Search Treevoid insert(struct Node** root, char *word){ // Base Case: Tree is empty if (!(*root)) *root = newNode(*word); // If current character of word is smaller than root's character, // then insert this word in left subtree of root if ((*word) < (*root)->data) insert(&( (*root)->left ), word); // If current character of word is greater than root's character, // then insert this word in right subtree of root else if ((*word) > (*root)->data) insert(&( (*root)->right ), word); // If current character of word is same as root's character, else { if (*(word+1)) insert(&( (*root)->eq ), word+1); // the last character of the word else (*root)->isEndOfString = 1; }} // A recursive function to traverse Ternary Search Treevoid traverseTSTUtil(struct Node* root, char* buffer, int depth){ if (root) { // First traverse the left subtree traverseTSTUtil(root->left, buffer, depth); // Store the character of this node buffer[depth] = root->data; if (root->isEndOfString) { buffer[depth+1] = '\0'; printf( "%s\n", buffer); } // Traverse the subtree using equal pointer (middle subtree) traverseTSTUtil(root->eq, buffer, depth + 1); // Finally Traverse the right subtree traverseTSTUtil(root->right, buffer, depth); }} // The main function to traverse a Ternary Search Tree.// It mainly uses traverseTSTUtil()void traverseTST(struct Node* root){ char buffer[MAX]; traverseTSTUtil(root, buffer, 0);} // Function to search a given word in TSTint searchTST(struct Node *root, char *word){ if (!root) return 0; if (*word < (root)->data) return searchTST(root->left, word); else if (*word > (root)->data) return searchTST(root->right, word); else { if (*(word+1) == '\0') return root->isEndOfString; return searchTST(root->eq, word+1); }} // Driver program to test above functionsint main(){ struct Node *root = NULL; insert(&root, "cat"); insert(&root, "cats"); insert(&root, "up"); insert(&root, "bug"); printf("Following is traversal of ternary search tree\n"); traverseTST(root); printf("\nFollowing are search results for cats, bu and cat respectively\n"); searchTST(root, "cats")? printf("Found\n"): printf("Not Found\n"); searchTST(root, "bu")? printf("Found\n"): printf("Not Found\n"); searchTST(root, "cat")? printf("Found\n"): printf("Not Found\n"); return 0;}
Output:
Following is traversal of ternary search tree
bug
cat
cats
up
Following are search results for cats, bu and cat respectively
Found
Not Found
Found
Time Complexity: The time complexity of the ternary search tree operations is similar to that of binary search tree. i.e. the insertion, deletion, and search operations take time proportional to the height of the ternary search tree. The space is proportional to the length of the string to be stored.
Reference: http://en.wikipedia.org/wiki/Ternary_search_treeThis article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
sweetyty
krishnanand3
sooda367
tapeshdua420
Advanced Data Structure
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 Jun, 2022"
},
{
"code": null,
"e": 186,
"s": 52,
"text": "A ternary search tree is a special trie data structure where the child nodes of a standard trie are ordered as a binary search tree. "
},
{
"code": null,
"e": 1011,
"s": 186,
"text": "Representation of ternary search trees: Unlike trie(standard) data structure where each node contains 26 pointers for its children, each node in a ternary search tree contains only 3 pointers: 1. The left pointer points to the node whose value is less than the value in the current node. 2. The equal pointer points to the node whose value is equal to the value in the current node. 3. The right pointer points to the node whose value is greater than the value in the current node.Apart from above three pointers, each node has a field to indicate data(character in case of dictionary) and another field to mark end of a string. So, more or less it is similar to BST which stores data based on some order. However, data in a ternary search tree is distributed over the nodes. e.g. It needs 4 nodes to store the word “Geek”. "
},
{
"code": null,
"e": 1090,
"s": 1011,
"text": "Below figure shows how exactly the words in a ternary search tree are stored? "
},
{
"code": null,
"e": 1664,
"s": 1090,
"text": "One of the advantage of using ternary search trees over tries is that ternary search trees are a more space efficient (involve only three pointers per node as compared to 26 in standard tries). Further, ternary search trees can be used any time a hashtable would be used to store strings.Tries are suitable when there is a proper distribution of words over the alphabets so that spaces are utilized most efficiently. Otherwise ternary search trees are better. Ternary search trees are efficient to use(in terms of space) when the strings to be stored share a common prefix."
},
{
"code": null,
"e": 2229,
"s": 1664,
"text": "Applications of ternary search trees: 1. Ternary search trees are efficient for queries like “Given a word, find the next word in dictionary(near-neighbor lookups)” or “Find all telephone numbers starting with 9342 or “typing few starting characters in a web browser displays all website names with this prefix”(Auto complete feature)”.2. Used in spell checks: Ternary search trees can be used as a dictionary to store all the words. Once the word is typed in an editor, the word can be parallelly searched in the ternary search tree to check for correct spelling."
},
{
"code": null,
"e": 2362,
"s": 2229,
"text": "Implementation: Following is C implementation of ternary search tree. The operations implemented are, search, insert, and traversal."
},
{
"code": null,
"e": 2366,
"s": 2362,
"text": "C++"
},
{
"code": null,
"e": 2368,
"s": 2366,
"text": "C"
},
{
"code": "// C++ program to demonstrate Ternary Search Tree (TST)// insert, traverse and search operations#include <bits/stdc++.h>using namespace std;#define MAX 50 // A node of ternary search treestruct Node { char data; // True if this character is last character of one of // the words unsigned isEndOfString = 1; Node *left, *eq, *right;}; // A utility function to create a new ternary search tree// nodeNode* newNode(char data){ Node* temp = new Node(); temp->data = data; temp->isEndOfString = 0; temp->left = temp->eq = temp->right = NULL; return temp;} // Function to insert a new word in a Ternary Search Treevoid insert(Node** root, char* word){ // Base Case: Tree is empty if (!(*root)) *root = newNode(*word); // If current character of word is smaller than root's // character, then insert this word in left subtree of // root if ((*word) < (*root)->data) insert(&((*root)->left), word); // If current character of word is greater than root's // character, then insert this word in right subtree of // root else if ((*word) > (*root)->data) insert(&((*root)->right), word); // If current character of word is same as root's // character, else { if (*(word + 1)) insert(&((*root)->eq), word + 1); // the last character of the word else (*root)->isEndOfString = 1; }} // A recursive function to traverse Ternary Search Treevoid traverseTSTUtil(Node* root, char* buffer, int depth){ if (root) { // First traverse the left subtree traverseTSTUtil(root->left, buffer, depth); // Store the character of this node buffer[depth] = root->data; if (root->isEndOfString) { buffer[depth + 1] = '\\0'; cout << buffer << endl; } // Traverse the subtree using equal pointer (middle // subtree) traverseTSTUtil(root->eq, buffer, depth + 1); // Finally Traverse the right subtree traverseTSTUtil(root->right, buffer, depth); }} // The main function to traverse a Ternary Search Tree.// It mainly uses traverseTSTUtil()void traverseTST(struct Node* root){ char buffer[MAX]; traverseTSTUtil(root, buffer, 0);} // Function to search a given word in TSTint searchTST(Node* root, char* word){ if (!root) return 0; if (*word < (root)->data) return searchTST(root->left, word); else if (*word > (root)->data) return searchTST(root->right, word); else { if (*(word + 1) == '\\0') return root->isEndOfString; return searchTST(root->eq, word + 1); }} // Driver program to test above functionsint main(){ Node* root = NULL; char cat[] = \"cat\"; char cats[] = \"cats\"; char up[] = \"up\"; char bug[] = \"bug\"; char bu[] = \"bu\"; insert(&root, cat); insert(&root, cats); insert(&root, up); insert(&root, bug); cout << \"Following is traversal of ternary search \" \"tree\\n\"; traverseTST(root); cout << \"\\nFollowing are search results for cats, bu \" \"and cat respectively\\n\"; searchTST(root, cats) ? cout << \"Found\\n\" : cout << \"Not Found\\n\"; searchTST(root, bu) ? cout << \"Found\\n\" : cout << \"Not Found\\n\"; searchTST(root, cat) ? cout << \"Found\\n\" : cout << \"Not Found\\n\"; return 0;} // This code is contributed by tapeshdua420.",
"e": 5827,
"s": 2368,
"text": null
},
{
"code": "// C program to demonstrate Ternary Search Tree (TST) insert, traverse// and search operations#include <stdio.h>#include <stdlib.h>#define MAX 50 // A node of ternary search treestruct Node{ char data; // True if this character is last character of one of the words unsigned isEndOfString: 1; struct Node *left, *eq, *right;}; // A utility function to create a new ternary search tree nodestruct Node* newNode(char data){ struct Node* temp = (struct Node*) malloc(sizeof( struct Node )); temp->data = data; temp->isEndOfString = 0; temp->left = temp->eq = temp->right = NULL; return temp;} // Function to insert a new word in a Ternary Search Treevoid insert(struct Node** root, char *word){ // Base Case: Tree is empty if (!(*root)) *root = newNode(*word); // If current character of word is smaller than root's character, // then insert this word in left subtree of root if ((*word) < (*root)->data) insert(&( (*root)->left ), word); // If current character of word is greater than root's character, // then insert this word in right subtree of root else if ((*word) > (*root)->data) insert(&( (*root)->right ), word); // If current character of word is same as root's character, else { if (*(word+1)) insert(&( (*root)->eq ), word+1); // the last character of the word else (*root)->isEndOfString = 1; }} // A recursive function to traverse Ternary Search Treevoid traverseTSTUtil(struct Node* root, char* buffer, int depth){ if (root) { // First traverse the left subtree traverseTSTUtil(root->left, buffer, depth); // Store the character of this node buffer[depth] = root->data; if (root->isEndOfString) { buffer[depth+1] = '\\0'; printf( \"%s\\n\", buffer); } // Traverse the subtree using equal pointer (middle subtree) traverseTSTUtil(root->eq, buffer, depth + 1); // Finally Traverse the right subtree traverseTSTUtil(root->right, buffer, depth); }} // The main function to traverse a Ternary Search Tree.// It mainly uses traverseTSTUtil()void traverseTST(struct Node* root){ char buffer[MAX]; traverseTSTUtil(root, buffer, 0);} // Function to search a given word in TSTint searchTST(struct Node *root, char *word){ if (!root) return 0; if (*word < (root)->data) return searchTST(root->left, word); else if (*word > (root)->data) return searchTST(root->right, word); else { if (*(word+1) == '\\0') return root->isEndOfString; return searchTST(root->eq, word+1); }} // Driver program to test above functionsint main(){ struct Node *root = NULL; insert(&root, \"cat\"); insert(&root, \"cats\"); insert(&root, \"up\"); insert(&root, \"bug\"); printf(\"Following is traversal of ternary search tree\\n\"); traverseTST(root); printf(\"\\nFollowing are search results for cats, bu and cat respectively\\n\"); searchTST(root, \"cats\")? printf(\"Found\\n\"): printf(\"Not Found\\n\"); searchTST(root, \"bu\")? printf(\"Found\\n\"): printf(\"Not Found\\n\"); searchTST(root, \"cat\")? printf(\"Found\\n\"): printf(\"Not Found\\n\"); return 0;}",
"e": 9090,
"s": 5827,
"text": null
},
{
"code": null,
"e": 9099,
"s": 9090,
"text": "Output: "
},
{
"code": null,
"e": 9247,
"s": 9099,
"text": "Following is traversal of ternary search tree\nbug\ncat\ncats\nup\n\nFollowing are search results for cats, bu and cat respectively\nFound\nNot Found\nFound"
},
{
"code": null,
"e": 9549,
"s": 9247,
"text": "Time Complexity: The time complexity of the ternary search tree operations is similar to that of binary search tree. i.e. the insertion, deletion, and search operations take time proportional to the height of the ternary search tree. The space is proportional to the length of the string to be stored."
},
{
"code": null,
"e": 9814,
"s": 9549,
"text": "Reference: http://en.wikipedia.org/wiki/Ternary_search_treeThis article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 9823,
"s": 9814,
"text": "sweetyty"
},
{
"code": null,
"e": 9836,
"s": 9823,
"text": "krishnanand3"
},
{
"code": null,
"e": 9845,
"s": 9836,
"text": "sooda367"
},
{
"code": null,
"e": 9858,
"s": 9845,
"text": "tapeshdua420"
},
{
"code": null,
"e": 9882,
"s": 9858,
"text": "Advanced Data Structure"
}
] |
Sum of Bitwise-OR of all subarrays of a given Array | Set 2
|
02 Jun, 2021
Give an array of positive integers. The task is to find the total sum after performing the bitwise OR operation on all the sub-arrays of the given array.Examples:
Input : arr[] = {1, 2, 3, 4, 5}
Output : 71
Input : arr[] = {6, 5, 4, 3, 2}
Output : 84
Explanation:
Simple Approach: A simple approach is to find the bitwise OR of each subarray of the given array using two nested loops, and then find the total sum. Time complexity of this approach will be O(N2).Efficient Approach:
Observe here that if a bit is being set by an element of the array then all subarray having that element will have that bit set. Therefore when we calculate sum of all subarrays having that number, we can directly multiply number of subarrays by the value that bit is making.Now, to do this an easy way will be to calculate the number of subarrays for which a bit is not set and subtract it from the total number of subarrays.
Observe here that if a bit is being set by an element of the array then all subarray having that element will have that bit set. Therefore when we calculate sum of all subarrays having that number, we can directly multiply number of subarrays by the value that bit is making.
Now, to do this an easy way will be to calculate the number of subarrays for which a bit is not set and subtract it from the total number of subarrays.
Let’s see an example: Let the array A = [1, 2, 3, 4, 5]. Now the 1st bit is not set in the elements 2 and 4 and total number of such subarrays for which the Bitwise-OR will not have the 1st bit set will be 2. Therefore, total number of subarrays for which the bitwise-OR will have 1st bit as set will be: 15-2 = 13.Therefore we will add (13 * pow(2, 0)) to sum. Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find sum of bitwise OR// of all subarrays #include <bits/stdc++.h>using namespace std; // Function to find sum of bitwise OR// of all subarraysint givesum(int A[], int n){ // Find max element of the array int max = *max_element(A, A + n); // Find the max bit position set in // the array int maxBit = log2(max) + 1; int totalSubarrays = n * (n + 1) / 2; int s = 0; // Traverse from 1st bit to last bit which // can be set in any element of the array for (int i = 0; i < maxBit; i++) { int c1 = 0; // Vector to store indexes of the array // with i-th bit not set vector<int> vec; int sum = 0; // Traverse the array for (int j = 0; j < n; j++) { // Check if ith bit is not set in A[j] int a = A[j] >> i; if (!(a & 1)) { vec.push_back(j); } } // Variable to store count of subarrays // whose bitwise OR will have i-th bit // not set int cntSubarrNotSet = 0; int cnt = 1; for (int j = 1; j < vec.size(); j++) { if (vec[j] - vec[j - 1] == 1) { cnt++; } else { cntSubarrNotSet += cnt * (cnt + 1) / 2; cnt = 1; } } // For last element of vec cntSubarrNotSet += cnt * (cnt + 1) / 2; // If vec is empty then cntSubarrNotSet // should be 0 and not 1 if (vec.size() == 0) cntSubarrNotSet = 0; // Variable to store count of subarrays // whose bitwise OR will have i-th bit set int cntSubarrIthSet = totalSubarrays - cntSubarrNotSet; s += cntSubarrIthSet * pow(2, i); } return s;} // Driver codeint main(){ int A[] = { 1, 2, 3, 4, 5 }; int n = sizeof(A) / sizeof(A[0]); cout << givesum(A, n); return 0;}
// Java program to find sum of bitwise OR// of all subarraysimport java.util.*; class GFG { // Function to find sum of bitwise OR // of all subarrays static int givesum(int A[], int n) { // Find max element of the array int max = Arrays.stream(A).max().getAsInt(); // Find the max bit position // set in the array int maxBit = (int)Math.ceil(Math.log(max) + 1); int totalSubarrays = n * (n + 1) / 2; int s = 0; // Traverse from 1st bit to last bit which // can be set in any element of the array for (int i = 0; i < maxBit; i++) { int c1 = 0; // Vector to store indexes of the array // with i-th bit not set Vector<Integer> vec = new Vector<>(); int sum = 0; // Traverse the array for (int j = 0; j < n; j++) { // Check if ith bit is not set in A[j] int a = A[j] >> i; if (!(a % 2 == 1)) { vec.add(j); } } // Variable to store count of subarrays // whose bitwise OR will have i-th bit // not set int cntSubarrNotSet = 0; int cnt = 1; for (int j = 1; j < vec.size(); j++) { if (vec.get(j) - vec.get(j - 1) == 1) { cnt++; } else { cntSubarrNotSet += cnt * (cnt + 1) / 2; cnt = 1; } } // For last element of vec cntSubarrNotSet += cnt * (cnt + 1) / 2; // If vec is empty then cntSubarrNotSet // should be 0 and not 1 if (vec.size() == 0) cntSubarrNotSet = 0; // Variable to store count of subarrays // whose bitwise OR will have i-th bit set int cntSubarrIthSet = totalSubarrays - cntSubarrNotSet; s += cntSubarrIthSet * Math.pow(2, i); } return s; } // Driver code public static void main(String[] args) { int A[] = { 1, 2, 3, 4, 5 }; int n = A.length; System.out.println(givesum(A, n)); }} // This code is contributed by 29AjayKumar
# Python 3 program to find sum of# bitwise OR of all subarrays # from math lib. import log2 functionfrom math import log2 # Function to find sum of bitwise OR# of all subarraysdef givesum(A, n) : # Find max element of the array max_element = max(A) # Find the max bit position set in # the array maxBit = int(log2(max_element)) + 1 totalSubarrays = n * (n + 1) // 2 s = 0 # Traverse from 1st bit to last bit which # can be set in any element of the array for i in range(maxBit) : c1 = 0 # List to store indexes of the array # with i-th bit not set vec = [] sum = 0 # Traverse the array for j in range(n) : # Check if ith bit is not set in A[j] a = A[j] >> i if (not(a & 1)) : vec.append(j) # Variable to store count of subarrays # whose bitwise OR will have i-th bit # not set cntSubarrNotSet = 0 cnt = 1 for j in range(1, len(vec)) : if (vec[j] - vec[j - 1] == 1) : cnt += 1 else : cntSubarrNotSet += cnt * (cnt + 1) // 2 cnt = 1 # For last element of vec cntSubarrNotSet += cnt * (cnt + 1) // 2 # If vec is empty then cntSubarrNotSet # should be 0 and not 1 if len(vec) == 0: cntSubarrNotSet = 0 # Variable to store count of subarrays # whose bitwise OR will have i-th bit set cntSubarrIthSet = totalSubarrays - cntSubarrNotSet s += cntSubarrIthSet * pow(2, i) return s # Driver codeif __name__ == "__main__" : A = [ 1, 2, 3, 4, 5 ] n = len(A) print(givesum(A, n)) # This code is contributed by Ryuga
// C# program to find sum of bitwise OR// of all subarraysusing System;using System.Linq;using System.Collections.Generic; class GFG { // Function to find sum of bitwise OR // of all subarrays static int givesum(int[] A, int n) { // Find max element of the array int max = A.Max(); // Find the max bit position // set in the array int maxBit = (int)Math.Ceiling(Math.Log(max) + 1); int totalSubarrays = n * (n + 1) / 2; int s = 0; // Traverse from 1st bit to last bit which // can be set in any element of the array for (int i = 0; i < maxBit; i++) { // Vector to store indexes of the array // with i-th bit not set List<int> vec = new List<int>(); // Traverse the array for (int j = 0; j < n; j++) { // Check if ith bit is not set in A[j] int a = A[j] >> i; if (!(a % 2 == 1)) { vec.Add(j); } } // Variable to store count of subarrays // whose bitwise OR will have i-th bit // not set int cntSubarrNotSet = 0; int cnt = 1; for (int j = 1; j < vec.Count; j++) { if (vec[j] - vec[j - 1] == 1) { cnt++; } else { cntSubarrNotSet += cnt * (cnt + 1) / 2; cnt = 1; } } // For last element of vec cntSubarrNotSet += cnt * (cnt + 1) / 2; // If vec is empty then cntSubarrNotSet // should be 0 and not 1 if (vec.Count() == 0) cntSubarrNotSet = 0; // Variable to store count of subarrays // whose bitwise OR will have i-th bit set int cntSubarrIthSet = totalSubarrays - cntSubarrNotSet; s += (int)(cntSubarrIthSet * Math.Pow(2, i)); } return s; } // Driver code public static void Main() { int[] A = { 1, 2, 3, 4, 5 }; int n = A.Length; Console.WriteLine(givesum(A, n)); }} /* This code contributed by PrinciRaj1992 */
<?php// PHP program to find sum of bitwise OR// of all subarrays // Function to find sum of bitwise OR// of all subarraysfunction givesum($A, $n){ // Find max element of the array $max = max($A); // Find the max bit position set in // the array $maxBit = (int)((log($max) / log10(2)) + 1); $totalSubarrays = (int)($n * ($n + 1) / 2); $s = 0; // Traverse from 1st bit to last bit which // can be set in any element of the array for ($i = 0; $i < $maxBit; $i++) { $c1 = 0; // Vector to store indexes of // the array with i-th bit not set $vec = array(); $sum = 0; // Traverse the array for ($j = 0; $j < $n; $j++) { // Check if ith bit is // not set in A[j] $a = $A[$j] >> $i; if (!($a & 1)) { array_push($vec, $j); } } // Variable to store count of subarrays // whose bitwise OR will have i-th bit // not set $cntSubarrNotSet = 0; $cnt = 1; for ($j = 1; $j < count($vec); $j++) { if ($vec[$j] - $vec[$j - 1] == 1) { $cnt++; } else { $cntSubarrNotSet += (int)($cnt * ($cnt + 1) / 2); $cnt = 1; } } // For last element of vec $cntSubarrNotSet += (int)($cnt * ($cnt + 1) / 2); // If vec is empty then cntSubarrNotSet // should be 0 and not 1 if (count($vec) == 0) $cntSubarrNotSet = 0; // Variable to store count of subarrays // whose bitwise OR will have i-th bit set $cntSubarrIthSet = $totalSubarrays - $cntSubarrNotSet; $s += $cntSubarrIthSet * pow(2, $i); } return $s;} // Driver code$A = array( 1, 2, 3, 4, 5 );$n = count($A); echo givesum($A, $n); // This code is contributed by mits?>
<script> // Javascript program to find sum of bitwise OR of all subarrays // Function to find sum of bitwise OR // of all subarrays function givesum(A, n) { // Find max element of the array let max = Number.MIN_VALUE; for(let i = 0; i < A.length; i++) { max = Math.max(max, A[i]); } // Find the max bit position // set in the array let maxBit = Math.ceil(Math.log(max) + 1); let totalSubarrays = n * (n + 1) / 2; let s = 0; // Traverse from 1st bit to last bit which // can be set in any element of the array for (let i = 0; i < maxBit; i++) { // Vector to store indexes of the array // with i-th bit not set let vec = []; // Traverse the array for (let j = 0; j < n; j++) { // Check if ith bit is not set in A[j] let a = A[j] >> i; if (!(a % 2 == 1)) { vec.push(j); } } // Variable to store count of subarrays // whose bitwise OR will have i-th bit // not set let cntSubarrNotSet = 0; let cnt = 1; for (let j = 1; j < vec.length; j++) { if (vec[j] - vec[j - 1] == 1) { cnt++; } else { cntSubarrNotSet += cnt * (cnt + 1) / 2; cnt = 1; } } // For last element of vec cntSubarrNotSet += cnt * (cnt + 1) / 2; // If vec is empty then cntSubarrNotSet // should be 0 and not 1 if (vec.length == 0) cntSubarrNotSet = 0; // Variable to store count of subarrays // whose bitwise OR will have i-th bit set let cntSubarrIthSet = totalSubarrays - cntSubarrNotSet; s += parseInt(cntSubarrIthSet * Math.pow(2, i), 10); } return s; } let A = [ 1, 2, 3, 4, 5 ]; let n = A.length; document.write(givesum(A, n)); // This code is contributed by suresh07.</script>
71
Time Complexity: O(N*logN)
ankthon
29AjayKumar
princiraj1992
Mithun Kumar
Kuldeep Soni
gp6
suresh07
Bitwise-OR
Technical Scripter 2018
Arrays
Bit Magic
C++
C++ Programs
Competitive Programming
Technical Scripter
Arrays
Bit Magic
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
How to swap two numbers without using a temporary variable?
Program to find whether a given number is power of 2
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n02 Jun, 2021"
},
{
"code": null,
"e": 217,
"s": 52,
"text": "Give an array of positive integers. The task is to find the total sum after performing the bitwise OR operation on all the sub-arrays of the given array.Examples: "
},
{
"code": null,
"e": 306,
"s": 217,
"text": "Input : arr[] = {1, 2, 3, 4, 5}\nOutput : 71\n\nInput : arr[] = {6, 5, 4, 3, 2}\nOutput : 84"
},
{
"code": null,
"e": 321,
"s": 306,
"text": "Explanation: "
},
{
"code": null,
"e": 542,
"s": 323,
"text": "Simple Approach: A simple approach is to find the bitwise OR of each subarray of the given array using two nested loops, and then find the total sum. Time complexity of this approach will be O(N2).Efficient Approach: "
},
{
"code": null,
"e": 969,
"s": 542,
"text": "Observe here that if a bit is being set by an element of the array then all subarray having that element will have that bit set. Therefore when we calculate sum of all subarrays having that number, we can directly multiply number of subarrays by the value that bit is making.Now, to do this an easy way will be to calculate the number of subarrays for which a bit is not set and subtract it from the total number of subarrays."
},
{
"code": null,
"e": 1245,
"s": 969,
"text": "Observe here that if a bit is being set by an element of the array then all subarray having that element will have that bit set. Therefore when we calculate sum of all subarrays having that number, we can directly multiply number of subarrays by the value that bit is making."
},
{
"code": null,
"e": 1397,
"s": 1245,
"text": "Now, to do this an easy way will be to calculate the number of subarrays for which a bit is not set and subtract it from the total number of subarrays."
},
{
"code": null,
"e": 1812,
"s": 1397,
"text": "Let’s see an example: Let the array A = [1, 2, 3, 4, 5]. Now the 1st bit is not set in the elements 2 and 4 and total number of such subarrays for which the Bitwise-OR will not have the 1st bit set will be 2. Therefore, total number of subarrays for which the bitwise-OR will have 1st bit as set will be: 15-2 = 13.Therefore we will add (13 * pow(2, 0)) to sum. Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1816,
"s": 1812,
"text": "C++"
},
{
"code": null,
"e": 1821,
"s": 1816,
"text": "Java"
},
{
"code": null,
"e": 1829,
"s": 1821,
"text": "Python3"
},
{
"code": null,
"e": 1832,
"s": 1829,
"text": "C#"
},
{
"code": null,
"e": 1836,
"s": 1832,
"text": "PHP"
},
{
"code": null,
"e": 1847,
"s": 1836,
"text": "Javascript"
},
{
"code": "// C++ program to find sum of bitwise OR// of all subarrays #include <bits/stdc++.h>using namespace std; // Function to find sum of bitwise OR// of all subarraysint givesum(int A[], int n){ // Find max element of the array int max = *max_element(A, A + n); // Find the max bit position set in // the array int maxBit = log2(max) + 1; int totalSubarrays = n * (n + 1) / 2; int s = 0; // Traverse from 1st bit to last bit which // can be set in any element of the array for (int i = 0; i < maxBit; i++) { int c1 = 0; // Vector to store indexes of the array // with i-th bit not set vector<int> vec; int sum = 0; // Traverse the array for (int j = 0; j < n; j++) { // Check if ith bit is not set in A[j] int a = A[j] >> i; if (!(a & 1)) { vec.push_back(j); } } // Variable to store count of subarrays // whose bitwise OR will have i-th bit // not set int cntSubarrNotSet = 0; int cnt = 1; for (int j = 1; j < vec.size(); j++) { if (vec[j] - vec[j - 1] == 1) { cnt++; } else { cntSubarrNotSet += cnt * (cnt + 1) / 2; cnt = 1; } } // For last element of vec cntSubarrNotSet += cnt * (cnt + 1) / 2; // If vec is empty then cntSubarrNotSet // should be 0 and not 1 if (vec.size() == 0) cntSubarrNotSet = 0; // Variable to store count of subarrays // whose bitwise OR will have i-th bit set int cntSubarrIthSet = totalSubarrays - cntSubarrNotSet; s += cntSubarrIthSet * pow(2, i); } return s;} // Driver codeint main(){ int A[] = { 1, 2, 3, 4, 5 }; int n = sizeof(A) / sizeof(A[0]); cout << givesum(A, n); return 0;}",
"e": 3750,
"s": 1847,
"text": null
},
{
"code": "// Java program to find sum of bitwise OR// of all subarraysimport java.util.*; class GFG { // Function to find sum of bitwise OR // of all subarrays static int givesum(int A[], int n) { // Find max element of the array int max = Arrays.stream(A).max().getAsInt(); // Find the max bit position // set in the array int maxBit = (int)Math.ceil(Math.log(max) + 1); int totalSubarrays = n * (n + 1) / 2; int s = 0; // Traverse from 1st bit to last bit which // can be set in any element of the array for (int i = 0; i < maxBit; i++) { int c1 = 0; // Vector to store indexes of the array // with i-th bit not set Vector<Integer> vec = new Vector<>(); int sum = 0; // Traverse the array for (int j = 0; j < n; j++) { // Check if ith bit is not set in A[j] int a = A[j] >> i; if (!(a % 2 == 1)) { vec.add(j); } } // Variable to store count of subarrays // whose bitwise OR will have i-th bit // not set int cntSubarrNotSet = 0; int cnt = 1; for (int j = 1; j < vec.size(); j++) { if (vec.get(j) - vec.get(j - 1) == 1) { cnt++; } else { cntSubarrNotSet += cnt * (cnt + 1) / 2; cnt = 1; } } // For last element of vec cntSubarrNotSet += cnt * (cnt + 1) / 2; // If vec is empty then cntSubarrNotSet // should be 0 and not 1 if (vec.size() == 0) cntSubarrNotSet = 0; // Variable to store count of subarrays // whose bitwise OR will have i-th bit set int cntSubarrIthSet = totalSubarrays - cntSubarrNotSet; s += cntSubarrIthSet * Math.pow(2, i); } return s; } // Driver code public static void main(String[] args) { int A[] = { 1, 2, 3, 4, 5 }; int n = A.length; System.out.println(givesum(A, n)); }} // This code is contributed by 29AjayKumar",
"e": 6007,
"s": 3750,
"text": null
},
{
"code": "# Python 3 program to find sum of# bitwise OR of all subarrays # from math lib. import log2 functionfrom math import log2 # Function to find sum of bitwise OR# of all subarraysdef givesum(A, n) : # Find max element of the array max_element = max(A) # Find the max bit position set in # the array maxBit = int(log2(max_element)) + 1 totalSubarrays = n * (n + 1) // 2 s = 0 # Traverse from 1st bit to last bit which # can be set in any element of the array for i in range(maxBit) : c1 = 0 # List to store indexes of the array # with i-th bit not set vec = [] sum = 0 # Traverse the array for j in range(n) : # Check if ith bit is not set in A[j] a = A[j] >> i if (not(a & 1)) : vec.append(j) # Variable to store count of subarrays # whose bitwise OR will have i-th bit # not set cntSubarrNotSet = 0 cnt = 1 for j in range(1, len(vec)) : if (vec[j] - vec[j - 1] == 1) : cnt += 1 else : cntSubarrNotSet += cnt * (cnt + 1) // 2 cnt = 1 # For last element of vec cntSubarrNotSet += cnt * (cnt + 1) // 2 # If vec is empty then cntSubarrNotSet # should be 0 and not 1 if len(vec) == 0: cntSubarrNotSet = 0 # Variable to store count of subarrays # whose bitwise OR will have i-th bit set cntSubarrIthSet = totalSubarrays - cntSubarrNotSet s += cntSubarrIthSet * pow(2, i) return s # Driver codeif __name__ == \"__main__\" : A = [ 1, 2, 3, 4, 5 ] n = len(A) print(givesum(A, n)) # This code is contributed by Ryuga",
"e": 7827,
"s": 6007,
"text": null
},
{
"code": "// C# program to find sum of bitwise OR// of all subarraysusing System;using System.Linq;using System.Collections.Generic; class GFG { // Function to find sum of bitwise OR // of all subarrays static int givesum(int[] A, int n) { // Find max element of the array int max = A.Max(); // Find the max bit position // set in the array int maxBit = (int)Math.Ceiling(Math.Log(max) + 1); int totalSubarrays = n * (n + 1) / 2; int s = 0; // Traverse from 1st bit to last bit which // can be set in any element of the array for (int i = 0; i < maxBit; i++) { // Vector to store indexes of the array // with i-th bit not set List<int> vec = new List<int>(); // Traverse the array for (int j = 0; j < n; j++) { // Check if ith bit is not set in A[j] int a = A[j] >> i; if (!(a % 2 == 1)) { vec.Add(j); } } // Variable to store count of subarrays // whose bitwise OR will have i-th bit // not set int cntSubarrNotSet = 0; int cnt = 1; for (int j = 1; j < vec.Count; j++) { if (vec[j] - vec[j - 1] == 1) { cnt++; } else { cntSubarrNotSet += cnt * (cnt + 1) / 2; cnt = 1; } } // For last element of vec cntSubarrNotSet += cnt * (cnt + 1) / 2; // If vec is empty then cntSubarrNotSet // should be 0 and not 1 if (vec.Count() == 0) cntSubarrNotSet = 0; // Variable to store count of subarrays // whose bitwise OR will have i-th bit set int cntSubarrIthSet = totalSubarrays - cntSubarrNotSet; s += (int)(cntSubarrIthSet * Math.Pow(2, i)); } return s; } // Driver code public static void Main() { int[] A = { 1, 2, 3, 4, 5 }; int n = A.Length; Console.WriteLine(givesum(A, n)); }} /* This code contributed by PrinciRaj1992 */",
"e": 10038,
"s": 7827,
"text": null
},
{
"code": "<?php// PHP program to find sum of bitwise OR// of all subarrays // Function to find sum of bitwise OR// of all subarraysfunction givesum($A, $n){ // Find max element of the array $max = max($A); // Find the max bit position set in // the array $maxBit = (int)((log($max) / log10(2)) + 1); $totalSubarrays = (int)($n * ($n + 1) / 2); $s = 0; // Traverse from 1st bit to last bit which // can be set in any element of the array for ($i = 0; $i < $maxBit; $i++) { $c1 = 0; // Vector to store indexes of // the array with i-th bit not set $vec = array(); $sum = 0; // Traverse the array for ($j = 0; $j < $n; $j++) { // Check if ith bit is // not set in A[j] $a = $A[$j] >> $i; if (!($a & 1)) { array_push($vec, $j); } } // Variable to store count of subarrays // whose bitwise OR will have i-th bit // not set $cntSubarrNotSet = 0; $cnt = 1; for ($j = 1; $j < count($vec); $j++) { if ($vec[$j] - $vec[$j - 1] == 1) { $cnt++; } else { $cntSubarrNotSet += (int)($cnt * ($cnt + 1) / 2); $cnt = 1; } } // For last element of vec $cntSubarrNotSet += (int)($cnt * ($cnt + 1) / 2); // If vec is empty then cntSubarrNotSet // should be 0 and not 1 if (count($vec) == 0) $cntSubarrNotSet = 0; // Variable to store count of subarrays // whose bitwise OR will have i-th bit set $cntSubarrIthSet = $totalSubarrays - $cntSubarrNotSet; $s += $cntSubarrIthSet * pow(2, $i); } return $s;} // Driver code$A = array( 1, 2, 3, 4, 5 );$n = count($A); echo givesum($A, $n); // This code is contributed by mits?>",
"e": 12086,
"s": 10038,
"text": null
},
{
"code": "<script> // Javascript program to find sum of bitwise OR of all subarrays // Function to find sum of bitwise OR // of all subarrays function givesum(A, n) { // Find max element of the array let max = Number.MIN_VALUE; for(let i = 0; i < A.length; i++) { max = Math.max(max, A[i]); } // Find the max bit position // set in the array let maxBit = Math.ceil(Math.log(max) + 1); let totalSubarrays = n * (n + 1) / 2; let s = 0; // Traverse from 1st bit to last bit which // can be set in any element of the array for (let i = 0; i < maxBit; i++) { // Vector to store indexes of the array // with i-th bit not set let vec = []; // Traverse the array for (let j = 0; j < n; j++) { // Check if ith bit is not set in A[j] let a = A[j] >> i; if (!(a % 2 == 1)) { vec.push(j); } } // Variable to store count of subarrays // whose bitwise OR will have i-th bit // not set let cntSubarrNotSet = 0; let cnt = 1; for (let j = 1; j < vec.length; j++) { if (vec[j] - vec[j - 1] == 1) { cnt++; } else { cntSubarrNotSet += cnt * (cnt + 1) / 2; cnt = 1; } } // For last element of vec cntSubarrNotSet += cnt * (cnt + 1) / 2; // If vec is empty then cntSubarrNotSet // should be 0 and not 1 if (vec.length == 0) cntSubarrNotSet = 0; // Variable to store count of subarrays // whose bitwise OR will have i-th bit set let cntSubarrIthSet = totalSubarrays - cntSubarrNotSet; s += parseInt(cntSubarrIthSet * Math.pow(2, i), 10); } return s; } let A = [ 1, 2, 3, 4, 5 ]; let n = A.length; document.write(givesum(A, n)); // This code is contributed by suresh07.</script>",
"e": 14299,
"s": 12086,
"text": null
},
{
"code": null,
"e": 14302,
"s": 14299,
"text": "71"
},
{
"code": null,
"e": 14332,
"s": 14304,
"text": "Time Complexity: O(N*logN) "
},
{
"code": null,
"e": 14340,
"s": 14332,
"text": "ankthon"
},
{
"code": null,
"e": 14352,
"s": 14340,
"text": "29AjayKumar"
},
{
"code": null,
"e": 14366,
"s": 14352,
"text": "princiraj1992"
},
{
"code": null,
"e": 14379,
"s": 14366,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 14392,
"s": 14379,
"text": "Kuldeep Soni"
},
{
"code": null,
"e": 14396,
"s": 14392,
"text": "gp6"
},
{
"code": null,
"e": 14405,
"s": 14396,
"text": "suresh07"
},
{
"code": null,
"e": 14416,
"s": 14405,
"text": "Bitwise-OR"
},
{
"code": null,
"e": 14440,
"s": 14416,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 14447,
"s": 14440,
"text": "Arrays"
},
{
"code": null,
"e": 14457,
"s": 14447,
"text": "Bit Magic"
},
{
"code": null,
"e": 14461,
"s": 14457,
"text": "C++"
},
{
"code": null,
"e": 14474,
"s": 14461,
"text": "C++ Programs"
},
{
"code": null,
"e": 14498,
"s": 14474,
"text": "Competitive Programming"
},
{
"code": null,
"e": 14517,
"s": 14498,
"text": "Technical Scripter"
},
{
"code": null,
"e": 14524,
"s": 14517,
"text": "Arrays"
},
{
"code": null,
"e": 14534,
"s": 14524,
"text": "Bit Magic"
},
{
"code": null,
"e": 14538,
"s": 14534,
"text": "CPP"
},
{
"code": null,
"e": 14636,
"s": 14538,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 14704,
"s": 14636,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 14748,
"s": 14704,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 14780,
"s": 14748,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 14828,
"s": 14780,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 14842,
"s": 14828,
"text": "Linear Search"
},
{
"code": null,
"e": 14869,
"s": 14842,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 14915,
"s": 14869,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 14983,
"s": 14915,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 15043,
"s": 14983,
"text": "How to swap two numbers without using a temporary variable?"
}
] |
Find the node with minimum value in a Binary Search Tree
|
20 Jun, 2022
This is quite simple. Just traverse the node from root to left recursively until left is NULL. The node whose left is NULL is the node with minimum value.
For the above tree, we start with 20, then we move left 8, we keep on moving to left until we see NULL. Since left of 4 is NULL, 4 is the node with minimum value.
C++
C
Java
Python3
C#
PHP
Javascript
//C++ program to find minimum value node in binary search Tree.#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left childand a pointer to right child */struct node{ int data; struct node* left; struct node* right;}; /* Helper function that allocates a new nodewith the given data and NULL left and rightpointers. */struct node* newNode(int data){struct node* node = (struct node*) malloc(sizeof(struct node));node->data = data;node->left = NULL;node->right = NULL; return(node);} /* Give a binary search tree and a number,inserts a new node with the given number inthe correct place in the tree. Returns the newroot pointer which the caller should then use(the standard trick to avoid using referenceparameters). */struct node* insert(struct node* node, int data){/* 1. If the tree is empty, return a new, single node */if (node == NULL) return(newNode(data));else{ /* 2. Otherwise, recur down the tree */ if (data <= node->data) node->left = insert(node->left, data); else node->right = insert(node->right, data); /* return the (unchanged) node pointer */ return node;}} /* Given a non-empty binary search tree,return the minimum data value found in thattree. Note that the entire tree does not needto be searched. */int minValue(struct node* node){struct node* current = node; /* loop down to find the leftmost leaf */while (current->left != NULL){ current = current->left;}return(current->data);} /* Driver Code*/int main(){struct node* root = NULL;root = insert(root, 4);insert(root, 2);insert(root, 1);insert(root, 3);insert(root, 6);insert(root, 5); cout << "\n Minimum value in BST is " << minValue(root);getchar();return 0;} // This code is contributed by Mukul Singh.
#include <stdio.h>#include<stdlib.h> /* A binary tree node has data, pointer to left child and a pointer to right child */struct node{ int data; struct node* left; struct node* right;}; /* Helper function that allocates a new nodewith the given data and NULL left and rightpointers. */struct node* newNode(int data){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} /* Give a binary search tree and a number,inserts a new node with the given number inthe correct place in the tree. Returns the newroot pointer which the caller should then use(the standard trick to avoid using referenceparameters). */struct node* insert(struct node* node, int data){ /* 1. If the tree is empty, return a new, single node */ if (node == NULL) return(newNode(data)); else { /* 2. Otherwise, recur down the tree */ if (data <= node->data) node->left = insert(node->left, data); else node->right = insert(node->right, data); /* return the (unchanged) node pointer */ return node; }} /* Given a non-empty binary search tree, return the minimum data value found in thattree. Note that the entire tree does not needto be searched. */int minValue(struct node* node) { struct node* current = node; /* loop down to find the leftmost leaf */ while (current->left != NULL) { current = current->left; } return(current->data);} /* Driver program to test sameTree function*/ int main(){ struct node* root = NULL; root = insert(root, 4); insert(root, 2); insert(root, 1); insert(root, 3); insert(root, 6); insert(root, 5); printf("\n Minimum value in BST is %d", minValue(root)); getchar(); return 0; }
// Java program to find minimum value node in Binary Search Tree // A binary tree nodeclass Node { int data; Node left, right; Node(int d) { data = d; left = right = null; }} class BinaryTree { static Node head; /* Given a binary search tree and a number, inserts a new node with the given number in the correct place in the tree. Returns the new root pointer which the caller should then use (the standard trick to avoid using reference parameters). */ Node insert(Node node, int data) { /* 1. If the tree is empty, return a new, single node */ if (node == null) { return (new Node(data)); } else { /* 2. Otherwise, recur down the tree */ if (data <= node.data) { node.left = insert(node.left, data); } else { node.right = insert(node.right, data); } /* return the (unchanged) node pointer */ return node; } } /* Given a non-empty binary search tree, return the minimum data value found in that tree. Note that the entire tree does not need to be searched. */ int minvalue(Node node) { Node current = node; /* loop down to find the leftmost leaf */ while (current.left != null) { current = current.left; } return (current.data); } // Driver program to test above functions public static void main(String[] args) { BinaryTree tree = new BinaryTree(); Node root = null; root = tree.insert(root, 4); tree.insert(root, 2); tree.insert(root, 1); tree.insert(root, 3); tree.insert(root, 6); tree.insert(root, 5); System.out.println("Minimum value of BST is " + tree.minvalue(root)); }} // This code is contributed by Mayank Jaiswal
# Python program to find the node with minimum value in bst # A binary tree nodeclass Node: # Constructor to create a new node def __init__(self, key): self.data = key self.left = None self.right = None """ Give a binary search tree and a number,inserts a new node with the given number inthe correct place in the tree. Returns the newroot pointer which the caller should then use(the standard trick to avoid using referenceparameters). """def insert(node, data): # 1. If the tree is empty, return a new, # single node if node is None: return (Node(data)) else: # 2. Otherwise, recur down the tree if data <= node.data: node.left = insert(node.left, data) else: node.right = insert(node.right, data) # Return the (unchanged) node pointer return node """ Given a non-empty binary search tree, return the minimum data value found in thattree. Note that the entire tree does not needto be searched. """def minValue(node): current = node # loop down to find the leftmost leaf while(current.left is not None): current = current.left return current.data # Driver programroot = Noneroot = insert(root,4)insert(root,2)insert(root,1)insert(root,3)insert(root,6)insert(root,5) print ("\nMinimum value in BST is %d" %(minValue(root))) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
using System; // C# program to find minimum value node in Binary Search Tree // A binary tree nodepublic class Node{ public int data; public Node left, right; public Node(int d) { data = d; left = right = null; }} public class BinaryTree{ public static Node head; /* Given a binary search tree and a number, inserts a new node with the given number in the correct place in the tree. Returns the new root pointer which the caller should then use (the standard trick to avoid using reference parameters). */ public virtual Node insert(Node node, int data) { /* 1. If the tree is empty, return a new, single node */ if (node == null) { return (new Node(data)); } else { /* 2. Otherwise, recur down the tree */ if (data <= node.data) { node.left = insert(node.left, data); } else { node.right = insert(node.right, data); } /* return the (unchanged) node pointer */ return node; } } /* Given a non-empty binary search tree, return the minimum data value found in that tree. Note that the entire tree does not need to be searched. */ public virtual int minvalue(Node node) { Node current = node; /* loop down to find the leftmost leaf */ while (current.left != null) { current = current.left; } return (current.data); } // Driver program to test above functions public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); Node root = null; root = tree.insert(root, 4); tree.insert(root, 2); tree.insert(root, 1); tree.insert(root, 3); tree.insert(root, 6); tree.insert(root, 5); Console.WriteLine("Minimum value of BST is " + tree.minvalue(root)); }} // This code is contributed by Shrikant13
<?php// PHP program to find the node with// minimum value in bst // create a binary treeclass node{ private $node, $left, $right; function __construct($node) { $this->node = $node; $left = $right = NULL; } // set the left node in tree function set_left($left) { $this->left = $left; } // set the right node in tree function set_right($right) { $this->right = $right; } // get left node function get_left() { return $this->left; } // get right node function get_right() { return $this->right; } // get value of current node function get_node() { return $this->node; } } // Find the node with minimum value// in a Binary Search Treefunction get_minimum_value($node){ /*travel till last left node to get the minimum value*/ while ($node->get_left() != NULL) { $node = $node->get_left(); } return $node->get_node();} // code to creating a tree$node = new node(4);$lnode = new node(2);$lnode->set_left(new node(1));$lnode->set_right(new node(3));$rnode = new node(6);$rnode->set_left(new node(5));$node->set_left($lnode);$node->set_right($rnode); $minimum_value = get_minimum_value($node);echo 'Minimum value of BST is '. $minimum_value; // This code is contributed// by Deepika Pathak?>
<script> // JavaScript program to find minimum // value node in Binary Search Tree class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } let head; /* Given a binary search tree and a number, inserts a new node with the given number in the correct place in the tree. Returns the new root pointer which the caller should then use (the standard trick to avoid using reference parameters). */ function insert(node, data) { /* 1. If the tree is empty, return a new, single node */ if (node == null) { return (new Node(data)); } else { /* 2. Otherwise, recur down the tree */ if (data <= node.data) { node.left = insert(node.left, data); } else { node.right = insert(node.right, data); } /* return the (unchanged) node pointer */ return node; } } /* Given a non-empty binary search tree, return the minimum data value found in that tree. Note that the entire tree does not need to be searched. */ function minvalue(node) { if (node === null) return null; let current = node; /* loop down to find the leftmost leaf */ while (current.left != null) { current = current.left; } return (current.data); } let root = null; root = insert(root, 4); insert(root, 2); insert(root, 1); insert(root, 3); insert(root, 6); insert(root, 5); document.write("Minimum value in BST is " + minvalue(root)); </script>
Output:
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Minimum value in BST is 1
Time Complexity: O(n) Worst case happens for left skewed trees.Similarly we can get the maximum value by recursively traversing the right node of a binary search tree.
Space complexity: O(n) for stack space, since using recursion
Find the node with minimum value in a Binary Search Tree | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersFind the node with minimum value in a Binary Search Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:37•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=GgDwIm1TlvE" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
References: http://cslibrary.stanford.edu/110/BinaryTrees.html
shrikanth13
DeepikaPathak
Code_Mech
rathbhupendra
rameshtravel07
amartyaghoshgfg
simmytarika5
karthikshindee
polymatir3j
Microsoft
Binary Search Tree
Tree
Microsoft
Binary Search Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n20 Jun, 2022"
},
{
"code": null,
"e": 210,
"s": 53,
"text": "This is quite simple. Just traverse the node from root to left recursively until left is NULL. The node whose left is NULL is the node with minimum value. "
},
{
"code": null,
"e": 377,
"s": 212,
"text": "For the above tree, we start with 20, then we move left 8, we keep on moving to left until we see NULL. Since left of 4 is NULL, 4 is the node with minimum value. "
},
{
"code": null,
"e": 381,
"s": 377,
"text": "C++"
},
{
"code": null,
"e": 383,
"s": 381,
"text": "C"
},
{
"code": null,
"e": 388,
"s": 383,
"text": "Java"
},
{
"code": null,
"e": 396,
"s": 388,
"text": "Python3"
},
{
"code": null,
"e": 399,
"s": 396,
"text": "C#"
},
{
"code": null,
"e": 403,
"s": 399,
"text": "PHP"
},
{
"code": null,
"e": 414,
"s": 403,
"text": "Javascript"
},
{
"code": "//C++ program to find minimum value node in binary search Tree.#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left childand a pointer to right child */struct node{ int data; struct node* left; struct node* right;}; /* Helper function that allocates a new nodewith the given data and NULL left and rightpointers. */struct node* newNode(int data){struct node* node = (struct node*) malloc(sizeof(struct node));node->data = data;node->left = NULL;node->right = NULL; return(node);} /* Give a binary search tree and a number,inserts a new node with the given number inthe correct place in the tree. Returns the newroot pointer which the caller should then use(the standard trick to avoid using referenceparameters). */struct node* insert(struct node* node, int data){/* 1. If the tree is empty, return a new, single node */if (node == NULL) return(newNode(data));else{ /* 2. Otherwise, recur down the tree */ if (data <= node->data) node->left = insert(node->left, data); else node->right = insert(node->right, data); /* return the (unchanged) node pointer */ return node;}} /* Given a non-empty binary search tree,return the minimum data value found in thattree. Note that the entire tree does not needto be searched. */int minValue(struct node* node){struct node* current = node; /* loop down to find the leftmost leaf */while (current->left != NULL){ current = current->left;}return(current->data);} /* Driver Code*/int main(){struct node* root = NULL;root = insert(root, 4);insert(root, 2);insert(root, 1);insert(root, 3);insert(root, 6);insert(root, 5); cout << \"\\n Minimum value in BST is \" << minValue(root);getchar();return 0;} // This code is contributed by Mukul Singh.",
"e": 2198,
"s": 414,
"text": null
},
{
"code": "#include <stdio.h>#include<stdlib.h> /* A binary tree node has data, pointer to left child and a pointer to right child */struct node{ int data; struct node* left; struct node* right;}; /* Helper function that allocates a new nodewith the given data and NULL left and rightpointers. */struct node* newNode(int data){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} /* Give a binary search tree and a number,inserts a new node with the given number inthe correct place in the tree. Returns the newroot pointer which the caller should then use(the standard trick to avoid using referenceparameters). */struct node* insert(struct node* node, int data){ /* 1. If the tree is empty, return a new, single node */ if (node == NULL) return(newNode(data)); else { /* 2. Otherwise, recur down the tree */ if (data <= node->data) node->left = insert(node->left, data); else node->right = insert(node->right, data); /* return the (unchanged) node pointer */ return node; }} /* Given a non-empty binary search tree, return the minimum data value found in thattree. Note that the entire tree does not needto be searched. */int minValue(struct node* node) { struct node* current = node; /* loop down to find the leftmost leaf */ while (current->left != NULL) { current = current->left; } return(current->data);} /* Driver program to test sameTree function*/ int main(){ struct node* root = NULL; root = insert(root, 4); insert(root, 2); insert(root, 1); insert(root, 3); insert(root, 6); insert(root, 5); printf(\"\\n Minimum value in BST is %d\", minValue(root)); getchar(); return 0; }",
"e": 3976,
"s": 2198,
"text": null
},
{
"code": "// Java program to find minimum value node in Binary Search Tree // A binary tree nodeclass Node { int data; Node left, right; Node(int d) { data = d; left = right = null; }} class BinaryTree { static Node head; /* Given a binary search tree and a number, inserts a new node with the given number in the correct place in the tree. Returns the new root pointer which the caller should then use (the standard trick to avoid using reference parameters). */ Node insert(Node node, int data) { /* 1. If the tree is empty, return a new, single node */ if (node == null) { return (new Node(data)); } else { /* 2. Otherwise, recur down the tree */ if (data <= node.data) { node.left = insert(node.left, data); } else { node.right = insert(node.right, data); } /* return the (unchanged) node pointer */ return node; } } /* Given a non-empty binary search tree, return the minimum data value found in that tree. Note that the entire tree does not need to be searched. */ int minvalue(Node node) { Node current = node; /* loop down to find the leftmost leaf */ while (current.left != null) { current = current.left; } return (current.data); } // Driver program to test above functions public static void main(String[] args) { BinaryTree tree = new BinaryTree(); Node root = null; root = tree.insert(root, 4); tree.insert(root, 2); tree.insert(root, 1); tree.insert(root, 3); tree.insert(root, 6); tree.insert(root, 5); System.out.println(\"Minimum value of BST is \" + tree.minvalue(root)); }} // This code is contributed by Mayank Jaiswal",
"e": 5887,
"s": 3976,
"text": null
},
{
"code": "# Python program to find the node with minimum value in bst # A binary tree nodeclass Node: # Constructor to create a new node def __init__(self, key): self.data = key self.left = None self.right = None \"\"\" Give a binary search tree and a number,inserts a new node with the given number inthe correct place in the tree. Returns the newroot pointer which the caller should then use(the standard trick to avoid using referenceparameters). \"\"\"def insert(node, data): # 1. If the tree is empty, return a new, # single node if node is None: return (Node(data)) else: # 2. Otherwise, recur down the tree if data <= node.data: node.left = insert(node.left, data) else: node.right = insert(node.right, data) # Return the (unchanged) node pointer return node \"\"\" Given a non-empty binary search tree, return the minimum data value found in thattree. Note that the entire tree does not needto be searched. \"\"\"def minValue(node): current = node # loop down to find the leftmost leaf while(current.left is not None): current = current.left return current.data # Driver programroot = Noneroot = insert(root,4)insert(root,2)insert(root,1)insert(root,3)insert(root,6)insert(root,5) print (\"\\nMinimum value in BST is %d\" %(minValue(root))) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)",
"e": 7303,
"s": 5887,
"text": null
},
{
"code": "using System; // C# program to find minimum value node in Binary Search Tree // A binary tree nodepublic class Node{ public int data; public Node left, right; public Node(int d) { data = d; left = right = null; }} public class BinaryTree{ public static Node head; /* Given a binary search tree and a number, inserts a new node with the given number in the correct place in the tree. Returns the new root pointer which the caller should then use (the standard trick to avoid using reference parameters). */ public virtual Node insert(Node node, int data) { /* 1. If the tree is empty, return a new, single node */ if (node == null) { return (new Node(data)); } else { /* 2. Otherwise, recur down the tree */ if (data <= node.data) { node.left = insert(node.left, data); } else { node.right = insert(node.right, data); } /* return the (unchanged) node pointer */ return node; } } /* Given a non-empty binary search tree, return the minimum data value found in that tree. Note that the entire tree does not need to be searched. */ public virtual int minvalue(Node node) { Node current = node; /* loop down to find the leftmost leaf */ while (current.left != null) { current = current.left; } return (current.data); } // Driver program to test above functions public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); Node root = null; root = tree.insert(root, 4); tree.insert(root, 2); tree.insert(root, 1); tree.insert(root, 3); tree.insert(root, 6); tree.insert(root, 5); Console.WriteLine(\"Minimum value of BST is \" + tree.minvalue(root)); }} // This code is contributed by Shrikant13",
"e": 9347,
"s": 7303,
"text": null
},
{
"code": "<?php// PHP program to find the node with// minimum value in bst // create a binary treeclass node{ private $node, $left, $right; function __construct($node) { $this->node = $node; $left = $right = NULL; } // set the left node in tree function set_left($left) { $this->left = $left; } // set the right node in tree function set_right($right) { $this->right = $right; } // get left node function get_left() { return $this->left; } // get right node function get_right() { return $this->right; } // get value of current node function get_node() { return $this->node; } } // Find the node with minimum value// in a Binary Search Treefunction get_minimum_value($node){ /*travel till last left node to get the minimum value*/ while ($node->get_left() != NULL) { $node = $node->get_left(); } return $node->get_node();} // code to creating a tree$node = new node(4);$lnode = new node(2);$lnode->set_left(new node(1));$lnode->set_right(new node(3));$rnode = new node(6);$rnode->set_left(new node(5));$node->set_left($lnode);$node->set_right($rnode); $minimum_value = get_minimum_value($node);echo 'Minimum value of BST is '. $minimum_value; // This code is contributed// by Deepika Pathak?>",
"e": 10703,
"s": 9347,
"text": null
},
{
"code": "<script> // JavaScript program to find minimum // value node in Binary Search Tree class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } let head; /* Given a binary search tree and a number, inserts a new node with the given number in the correct place in the tree. Returns the new root pointer which the caller should then use (the standard trick to avoid using reference parameters). */ function insert(node, data) { /* 1. If the tree is empty, return a new, single node */ if (node == null) { return (new Node(data)); } else { /* 2. Otherwise, recur down the tree */ if (data <= node.data) { node.left = insert(node.left, data); } else { node.right = insert(node.right, data); } /* return the (unchanged) node pointer */ return node; } } /* Given a non-empty binary search tree, return the minimum data value found in that tree. Note that the entire tree does not need to be searched. */ function minvalue(node) { if (node === null) return null; let current = node; /* loop down to find the leftmost leaf */ while (current.left != null) { current = current.left; } return (current.data); } let root = null; root = insert(root, 4); insert(root, 2); insert(root, 1); insert(root, 3); insert(root, 6); insert(root, 5); document.write(\"Minimum value in BST is \" + minvalue(root)); </script>",
"e": 12427,
"s": 10703,
"text": null
},
{
"code": null,
"e": 12435,
"s": 12427,
"text": "Output:"
},
{
"code": null,
"e": 12444,
"s": 12435,
"text": "Chapters"
},
{
"code": null,
"e": 12471,
"s": 12444,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 12521,
"s": 12471,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 12544,
"s": 12521,
"text": "captions off, selected"
},
{
"code": null,
"e": 12552,
"s": 12544,
"text": "English"
},
{
"code": null,
"e": 12576,
"s": 12552,
"text": "This is a modal window."
},
{
"code": null,
"e": 12645,
"s": 12576,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 12667,
"s": 12645,
"text": "End of dialog window."
},
{
"code": null,
"e": 12693,
"s": 12667,
"text": "Minimum value in BST is 1"
},
{
"code": null,
"e": 12861,
"s": 12693,
"text": "Time Complexity: O(n) Worst case happens for left skewed trees.Similarly we can get the maximum value by recursively traversing the right node of a binary search tree."
},
{
"code": null,
"e": 12924,
"s": 12861,
"text": "Space complexity: O(n) for stack space, since using recursion "
},
{
"code": null,
"e": 13854,
"s": 12924,
"text": "Find the node with minimum value in a Binary Search Tree | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersFind the node with minimum value in a Binary Search Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:37•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=GgDwIm1TlvE\" 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": 13918,
"s": 13854,
"text": "References: http://cslibrary.stanford.edu/110/BinaryTrees.html "
},
{
"code": null,
"e": 13930,
"s": 13918,
"text": "shrikanth13"
},
{
"code": null,
"e": 13944,
"s": 13930,
"text": "DeepikaPathak"
},
{
"code": null,
"e": 13954,
"s": 13944,
"text": "Code_Mech"
},
{
"code": null,
"e": 13968,
"s": 13954,
"text": "rathbhupendra"
},
{
"code": null,
"e": 13983,
"s": 13968,
"text": "rameshtravel07"
},
{
"code": null,
"e": 13999,
"s": 13983,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 14012,
"s": 13999,
"text": "simmytarika5"
},
{
"code": null,
"e": 14027,
"s": 14012,
"text": "karthikshindee"
},
{
"code": null,
"e": 14039,
"s": 14027,
"text": "polymatir3j"
},
{
"code": null,
"e": 14049,
"s": 14039,
"text": "Microsoft"
},
{
"code": null,
"e": 14068,
"s": 14049,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 14073,
"s": 14068,
"text": "Tree"
},
{
"code": null,
"e": 14083,
"s": 14073,
"text": "Microsoft"
},
{
"code": null,
"e": 14102,
"s": 14083,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 14107,
"s": 14102,
"text": "Tree"
}
] |
Java Program to Print Pascal’s Triangle
|
20 Apr, 2022
Pascal’s triangle is a pattern of the triangle which is based on nCr.below is the pictorial representation of Pascal’s triangle.
Example:
Input : N = 5
Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Approach #1:
nCr formula:
n ! / ( n – r ) ! r !
After using nCr formula, the pictorial representation becomes:
0C0
1C0 1C1
2C0 2C1 2C2
3C0 3C1 3C2 3C3
Algorithm:
Take a number of rows to be printed, assume it to be n
Make outer iteration i from 0 to n times to print the rows.
Make inner iteration for j from 0 to (N – 1).
Print single blank space ” “
Close inner loop (j loop) //it’s needed for left spacing
Make inner iteration for j from 0 to i.
Print nCr of i and j.
Close inner loop.
Print newline character (\n) after each inner iteration.
Below is the implementation of the above approach:
Java
// Print Pascal's Triangle in Javaimport java.io.*; class GFG { public int factorial(int i) { if (i == 0) return 1; return i * factorial(i - 1); } public static void main(String[] args) { int n = 4, i, j; GFG g = new GFG(); for (i = 0; i <= n; i++) { for (j = 0; j <= n - i; j++) { // for left spacing System.out.print(" "); } for (j = 0; j <= i; j++) { // nCr formula System.out.print( " " + g.factorial(i) / (g.factorial(i - j) * g.factorial(j))); } // for newline System.out.println(); } }}
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Time Complexity: O(N2)
Approach #2:
i’th entry in a line number line is Binomial Coefficient C(line, i) and all lines start with value 1. The idea is to calculate C(line, i) using C(line, i-1).
C(line, i) = C(line, i-1) * (line - i + 1) / i
Below is the Implementation of given approach:
Java
// Print Pascal's Triangle in Javaimport java.io.*;class GFG { // Pascal function public static void printPascal(int n) { for (int line = 1; line <= n; line++) { for (int j = 0; j <= n - line; j++) { // for left spacing System.out.print(" "); } // used to represent C(line, i) int C = 1; for (int i = 1; i <= line; i++) { // The first value in a line is always 1 System.out.print(C + " "); C = C * (line - i) / i; } System.out.println(); } } // Driver code public static void main(String[] args) { int n = 4; printPascal(n); }}
1
1 1
1 2 1
1 3 3 1
Time Complexity: O(N2)
pradiptamukherjee
kvenketeshdora
Technical Scripter 2020
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n20 Apr, 2022"
},
{
"code": null,
"e": 183,
"s": 54,
"text": "Pascal’s triangle is a pattern of the triangle which is based on nCr.below is the pictorial representation of Pascal’s triangle."
},
{
"code": null,
"e": 192,
"s": 183,
"text": "Example:"
},
{
"code": null,
"e": 294,
"s": 192,
"text": "Input : N = 5\nOutput:\n 1\n 1 1\n 1 2 1\n 1 3 3 1\n 1 4 6 4 1"
},
{
"code": null,
"e": 308,
"s": 294,
"text": "Approach #1: "
},
{
"code": null,
"e": 321,
"s": 308,
"text": "nCr formula:"
},
{
"code": null,
"e": 345,
"s": 321,
"text": " n ! / ( n – r ) ! r ! "
},
{
"code": null,
"e": 408,
"s": 345,
"text": "After using nCr formula, the pictorial representation becomes:"
},
{
"code": null,
"e": 486,
"s": 408,
"text": " 0C0\n 1C0 1C1\n 2C0 2C1 2C2\n 3C0 3C1 3C2 3C3"
},
{
"code": null,
"e": 497,
"s": 486,
"text": "Algorithm:"
},
{
"code": null,
"e": 552,
"s": 497,
"text": "Take a number of rows to be printed, assume it to be n"
},
{
"code": null,
"e": 612,
"s": 552,
"text": "Make outer iteration i from 0 to n times to print the rows."
},
{
"code": null,
"e": 658,
"s": 612,
"text": "Make inner iteration for j from 0 to (N – 1)."
},
{
"code": null,
"e": 687,
"s": 658,
"text": "Print single blank space ” “"
},
{
"code": null,
"e": 744,
"s": 687,
"text": "Close inner loop (j loop) //it’s needed for left spacing"
},
{
"code": null,
"e": 784,
"s": 744,
"text": "Make inner iteration for j from 0 to i."
},
{
"code": null,
"e": 806,
"s": 784,
"text": "Print nCr of i and j."
},
{
"code": null,
"e": 824,
"s": 806,
"text": "Close inner loop."
},
{
"code": null,
"e": 881,
"s": 824,
"text": "Print newline character (\\n) after each inner iteration."
},
{
"code": null,
"e": 932,
"s": 881,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 937,
"s": 932,
"text": "Java"
},
{
"code": "// Print Pascal's Triangle in Javaimport java.io.*; class GFG { public int factorial(int i) { if (i == 0) return 1; return i * factorial(i - 1); } public static void main(String[] args) { int n = 4, i, j; GFG g = new GFG(); for (i = 0; i <= n; i++) { for (j = 0; j <= n - i; j++) { // for left spacing System.out.print(\" \"); } for (j = 0; j <= i; j++) { // nCr formula System.out.print( \" \" + g.factorial(i) / (g.factorial(i - j) * g.factorial(j))); } // for newline System.out.println(); } }}",
"e": 1722,
"s": 937,
"text": null
},
{
"code": null,
"e": 1772,
"s": 1722,
"text": " 1\n 1 1\n 1 2 1\n 1 3 3 1\n 1 4 6 4 1"
},
{
"code": null,
"e": 1795,
"s": 1772,
"text": "Time Complexity: O(N2)"
},
{
"code": null,
"e": 1808,
"s": 1795,
"text": "Approach #2:"
},
{
"code": null,
"e": 1967,
"s": 1808,
"text": "i’th entry in a line number line is Binomial Coefficient C(line, i) and all lines start with value 1. The idea is to calculate C(line, i) using C(line, i-1). "
},
{
"code": null,
"e": 2014,
"s": 1967,
"text": "C(line, i) = C(line, i-1) * (line - i + 1) / i"
},
{
"code": null,
"e": 2061,
"s": 2014,
"text": "Below is the Implementation of given approach:"
},
{
"code": null,
"e": 2066,
"s": 2061,
"text": "Java"
},
{
"code": "// Print Pascal's Triangle in Javaimport java.io.*;class GFG { // Pascal function public static void printPascal(int n) { for (int line = 1; line <= n; line++) { for (int j = 0; j <= n - line; j++) { // for left spacing System.out.print(\" \"); } // used to represent C(line, i) int C = 1; for (int i = 1; i <= line; i++) { // The first value in a line is always 1 System.out.print(C + \" \"); C = C * (line - i) / i; } System.out.println(); } } // Driver code public static void main(String[] args) { int n = 4; printPascal(n); }}",
"e": 2803,
"s": 2066,
"text": null
},
{
"code": null,
"e": 2837,
"s": 2803,
"text": " 1 \n 1 1 \n 1 2 1 \n 1 3 3 1 "
},
{
"code": null,
"e": 2860,
"s": 2837,
"text": "Time Complexity: O(N2)"
},
{
"code": null,
"e": 2878,
"s": 2860,
"text": "pradiptamukherjee"
},
{
"code": null,
"e": 2893,
"s": 2878,
"text": "kvenketeshdora"
},
{
"code": null,
"e": 2917,
"s": 2893,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 2922,
"s": 2917,
"text": "Java"
},
{
"code": null,
"e": 2936,
"s": 2922,
"text": "Java Programs"
},
{
"code": null,
"e": 2941,
"s": 2936,
"text": "Java"
},
{
"code": null,
"e": 3039,
"s": 2941,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3054,
"s": 3039,
"text": "Stream In Java"
},
{
"code": null,
"e": 3075,
"s": 3054,
"text": "Introduction to Java"
},
{
"code": null,
"e": 3096,
"s": 3075,
"text": "Constructors in Java"
},
{
"code": null,
"e": 3115,
"s": 3096,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 3132,
"s": 3115,
"text": "Generics in Java"
},
{
"code": null,
"e": 3158,
"s": 3132,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 3192,
"s": 3158,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 3239,
"s": 3192,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 3277,
"s": 3239,
"text": "Factory method design pattern in Java"
}
] |
Node.js fs.truncate() Method
|
12 Oct, 2021
The fs.truncate() method in node.js is used to change the size of the file i.e either increase or decrease the file size. This method changes the length of the file at the path by len bytes. If len represents a length shorter than the file’s current length, the file is truncated to that length. If it is greater than the file length is padded by appending null bytes (x00) until len is reached.
Syntax:
fs.truncate( path, len, callback )
Parameters: This method accept three parameters as mentioned above and described below:
path: It holds the path of targeted file. It can be either string, buffer or a url.
len: It holds the length of the file after which the file will be truncated. It takes an integer input and it is not the mandatory condition as it is default set to 0.
callback: The callback receives one argument, any exception throws in the call.
Note: In latest version of node.js, callback is no longer optional parameter. If we will not use the callback parameter then it will return “Type Error” on run-time.
Return Value: It changes the length of the desired file to the desired length.
Example 1:
// Node.js program to demonstrate the// fs.truncate() method // Include the fs modulevar fs = require('fs'); // Completely delete the content// of the targeted filefs.truncate('/path/to/file', 0, function() { console.log('File Content Deleted')});
Output:
File Content Deleted
Example 2:
// Node.js program to demonstrate the// fs.truncate() method // Include the fs modulevar fs = require('fs'); console.log("Content of file"); // Opening filefs.open('input.txt', 'r+', function(err, fd) { if (err) { return console.error(err); } // Reading file fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){ if (err){ console.log(err); } // Truncating the file fs.truncate('/path/to/file', 15, function(err, bytes){ if (err){ console.log(err); } // Content after truncating console.log("New content of file"); fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){ if (err) { console.log(err); } // Print only read bytes to avoid junk. if(bytes > 0) { console.log(buf.slice(0, bytes).toString()); } // Close the opened file. fs.close(fd, function(err) { if (err) { console.log(err); } }); }); }); });});
Output:
Content of file
GeeksforGeeks example for truncate in node
New content of file
GeeksforGeeks
Reference: https://nodejs.org/api/fs.html#fs_fs_ftruncate_fd_len_callback
Node.js-fs-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
How to update NPM ?
Difference between promise and async await in Node.js
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": 28,
"s": 0,
"text": "\n12 Oct, 2021"
},
{
"code": null,
"e": 424,
"s": 28,
"text": "The fs.truncate() method in node.js is used to change the size of the file i.e either increase or decrease the file size. This method changes the length of the file at the path by len bytes. If len represents a length shorter than the file’s current length, the file is truncated to that length. If it is greater than the file length is padded by appending null bytes (x00) until len is reached."
},
{
"code": null,
"e": 432,
"s": 424,
"text": "Syntax:"
},
{
"code": null,
"e": 467,
"s": 432,
"text": "fs.truncate( path, len, callback )"
},
{
"code": null,
"e": 555,
"s": 467,
"text": "Parameters: This method accept three parameters as mentioned above and described below:"
},
{
"code": null,
"e": 639,
"s": 555,
"text": "path: It holds the path of targeted file. It can be either string, buffer or a url."
},
{
"code": null,
"e": 807,
"s": 639,
"text": "len: It holds the length of the file after which the file will be truncated. It takes an integer input and it is not the mandatory condition as it is default set to 0."
},
{
"code": null,
"e": 887,
"s": 807,
"text": "callback: The callback receives one argument, any exception throws in the call."
},
{
"code": null,
"e": 1053,
"s": 887,
"text": "Note: In latest version of node.js, callback is no longer optional parameter. If we will not use the callback parameter then it will return “Type Error” on run-time."
},
{
"code": null,
"e": 1132,
"s": 1053,
"text": "Return Value: It changes the length of the desired file to the desired length."
},
{
"code": null,
"e": 1143,
"s": 1132,
"text": "Example 1:"
},
{
"code": "// Node.js program to demonstrate the// fs.truncate() method // Include the fs modulevar fs = require('fs'); // Completely delete the content// of the targeted filefs.truncate('/path/to/file', 0, function() { console.log('File Content Deleted')});",
"e": 1397,
"s": 1143,
"text": null
},
{
"code": null,
"e": 1405,
"s": 1397,
"text": "Output:"
},
{
"code": null,
"e": 1426,
"s": 1405,
"text": "File Content Deleted"
},
{
"code": null,
"e": 1437,
"s": 1426,
"text": "Example 2:"
},
{
"code": "// Node.js program to demonstrate the// fs.truncate() method // Include the fs modulevar fs = require('fs'); console.log(\"Content of file\"); // Opening filefs.open('input.txt', 'r+', function(err, fd) { if (err) { return console.error(err); } // Reading file fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){ if (err){ console.log(err); } // Truncating the file fs.truncate('/path/to/file', 15, function(err, bytes){ if (err){ console.log(err); } // Content after truncating console.log(\"New content of file\"); fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){ if (err) { console.log(err); } // Print only read bytes to avoid junk. if(bytes > 0) { console.log(buf.slice(0, bytes).toString()); } // Close the opened file. fs.close(fd, function(err) { if (err) { console.log(err); } }); }); }); });});",
"e": 2654,
"s": 1437,
"text": null
},
{
"code": null,
"e": 2662,
"s": 2654,
"text": "Output:"
},
{
"code": null,
"e": 2755,
"s": 2662,
"text": "Content of file\nGeeksforGeeks example for truncate in node\nNew content of file\nGeeksforGeeks"
},
{
"code": null,
"e": 2829,
"s": 2755,
"text": "Reference: https://nodejs.org/api/fs.html#fs_fs_ftruncate_fd_len_callback"
},
{
"code": null,
"e": 2847,
"s": 2829,
"text": "Node.js-fs-module"
},
{
"code": null,
"e": 2854,
"s": 2847,
"text": "Picked"
},
{
"code": null,
"e": 2862,
"s": 2854,
"text": "Node.js"
},
{
"code": null,
"e": 2879,
"s": 2862,
"text": "Web Technologies"
},
{
"code": null,
"e": 2977,
"s": 2879,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3025,
"s": 2977,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 3058,
"s": 3025,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 3088,
"s": 3058,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 3108,
"s": 3088,
"text": "How to update NPM ?"
},
{
"code": null,
"e": 3162,
"s": 3108,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 3224,
"s": 3162,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3285,
"s": 3224,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3335,
"s": 3285,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 3378,
"s": 3335,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Program to calculate value of nCr
|
18 Jan, 2022
Following are common definition of Binomial Coefficients.
A binomial coefficient C(n, k) can be defined as the coefficient of X^k in the expansion of (1 + X)^n.A binomial coefficient C(n, k) also gives the number of ways, disregarding order, that k objects can be chosen from among n objects; more formally, the number of k-element subsets (or k-combinations) of an n-element set.
A binomial coefficient C(n, k) can be defined as the coefficient of X^k in the expansion of (1 + X)^n.
A binomial coefficient C(n, k) also gives the number of ways, disregarding order, that k objects can be chosen from among n objects; more formally, the number of k-element subsets (or k-combinations) of an n-element set.
Given two numbers n and r, find value of nCrExamples :
Input : n = 5, r = 2
Output : 10
The value of 5C2 is 10
Input : n = 3, r = 1
Output : 3
The idea is simply based on below formula.
nCr = (n!) / (r! * (n-r)!)
C
C++
Java
Python 3
C#
PHP
Javascript
#include <stdio.h> int factorial(int n) { int factorial = 1; for (int i = 2; i <= n; i++) factorial = factorial * i; return factorial;} int nCr(int n, int r) { return factorial(n) / (factorial(r) * factorial(n - r));} int main() { int n = 5, r = 3; printf("%d", nCr(n, r)); return 0;} // This code was contributed by Omkar Prabhune
// CPP program To calculate The Value Of nCr#include <bits/stdc++.h>using namespace std; int fact(int n); int nCr(int n, int r){ return fact(n) / (fact(r) * fact(n - r));} // Returns factorial of nint fact(int n){ int res = 1; for (int i = 2; i <= n; i++) res = res * i; return res;} // Driver codeint main(){ int n = 5, r = 3; cout << nCr(n, r); return 0;}
// Java program To calculate// The Value Of nCrclass GFG { static int nCr(int n, int r){ return fact(n) / (fact(r) * fact(n - r));} // Returns factorial of nstatic int fact(int n){ int res = 1; for (int i = 2; i <= n; i++) res = res * i; return res;} // Driver codepublic static void main(String[] args){ int n = 5, r = 3; System.out.println(nCr(n, r));}} // This code is Contributed by// Smitha Dinesh Semwal.
# Python 3 program To calculate# The Value Of nCr def nCr(n, r): return (fact(n) / (fact(r) * fact(n - r))) # Returns factorial of ndef fact(n): res = 1 for i in range(2, n+1): res = res * i return res # Driver coden = 5r = 3print(int(nCr(n, r))) # This code is contributed# by Smitha
// C# program To calculate// The Value Of nCrusing System; class GFG { static int nCr(int n, int r){ return fact(n) / (fact(r) * fact(n - r));} // Returns factorial of nstatic int fact(int n){ int res = 1; for (int i = 2; i <= n; i++) res = res * i; return res;} // Driver code public static void Main() { int n = 5, r = 3; Console.Write(nCr(n, r)); }} // This code is Contributed by nitin mittal.
<?php// PHP program To calculate// the Value Of nCr function nCr( $n, $r){ return fact($n) / (fact($r) * fact($n - $r));} // Returns factorial of nfunction fact( $n){ $res = 1; for ( $i = 2; $i <= $n; $i++) $res = $res * $i; return $res;} // Driver code $n = 5; $r = 3; echo nCr($n, $r); // This code is contributed by vt_m.?>
<script> // Javascript program To calculate The Value Of nCr function nCr(n, r){ return fact(n) / (fact(r) * fact(n - r));} // Returns factorial of nfunction fact(n){ var res = 1; for (var i = 2; i <= n; i++) res = res * i; return res;} // Driver codevar n = 5, r = 3;document.write(nCr(n, r)); </script>
10
Time Complexity: O(n)
Auxiliary Space: O(1)
More Efficient Solutions: Dynamic Programming | Set 9 (Binomial Coefficient) Space and time efficient Binomial Coefficient All Articles on Binomial Coefficient
Smitha Dinesh Semwal
nitin mittal
vt_m
naimishrastogi
rutvik_56
opprabhune317
prophet1999
binomial coefficient
factorial
Combinatorial
Mathematical
School Programming
Mathematical
Combinatorial
factorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count of subsets with sum equal to X
Count Derangements (Permutation such that no element appears in its original position)
Stack Permutations (Check if an array is stack permutation of other)
Find the K-th Permutation Sequence of first N natural numbers
Probability of getting K heads in N coin tosses
Set in C++ Standard Template Library (STL)
C++ Data Types
Merge two sorted arrays
Operators in C / C++
Algorithm to solve Rubik's Cube
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n18 Jan, 2022"
},
{
"code": null,
"e": 112,
"s": 52,
"text": "Following are common definition of Binomial Coefficients. "
},
{
"code": null,
"e": 435,
"s": 112,
"text": "A binomial coefficient C(n, k) can be defined as the coefficient of X^k in the expansion of (1 + X)^n.A binomial coefficient C(n, k) also gives the number of ways, disregarding order, that k objects can be chosen from among n objects; more formally, the number of k-element subsets (or k-combinations) of an n-element set."
},
{
"code": null,
"e": 538,
"s": 435,
"text": "A binomial coefficient C(n, k) can be defined as the coefficient of X^k in the expansion of (1 + X)^n."
},
{
"code": null,
"e": 759,
"s": 538,
"text": "A binomial coefficient C(n, k) also gives the number of ways, disregarding order, that k objects can be chosen from among n objects; more formally, the number of k-element subsets (or k-combinations) of an n-element set."
},
{
"code": null,
"e": 816,
"s": 759,
"text": "Given two numbers n and r, find value of nCrExamples : "
},
{
"code": null,
"e": 906,
"s": 816,
"text": "Input : n = 5, r = 2\nOutput : 10\nThe value of 5C2 is 10\n\nInput : n = 3, r = 1\nOutput : 3"
},
{
"code": null,
"e": 952,
"s": 908,
"text": "The idea is simply based on below formula. "
},
{
"code": null,
"e": 979,
"s": 952,
"text": "nCr = (n!) / (r! * (n-r)!)"
},
{
"code": null,
"e": 983,
"s": 981,
"text": "C"
},
{
"code": null,
"e": 987,
"s": 983,
"text": "C++"
},
{
"code": null,
"e": 992,
"s": 987,
"text": "Java"
},
{
"code": null,
"e": 1001,
"s": 992,
"text": "Python 3"
},
{
"code": null,
"e": 1004,
"s": 1001,
"text": "C#"
},
{
"code": null,
"e": 1008,
"s": 1004,
"text": "PHP"
},
{
"code": null,
"e": 1019,
"s": 1008,
"text": "Javascript"
},
{
"code": "#include <stdio.h> int factorial(int n) { int factorial = 1; for (int i = 2; i <= n; i++) factorial = factorial * i; return factorial;} int nCr(int n, int r) { return factorial(n) / (factorial(r) * factorial(n - r));} int main() { int n = 5, r = 3; printf(\"%d\", nCr(n, r)); return 0;} // This code was contributed by Omkar Prabhune",
"e": 1381,
"s": 1019,
"text": null
},
{
"code": "// CPP program To calculate The Value Of nCr#include <bits/stdc++.h>using namespace std; int fact(int n); int nCr(int n, int r){ return fact(n) / (fact(r) * fact(n - r));} // Returns factorial of nint fact(int n){ int res = 1; for (int i = 2; i <= n; i++) res = res * i; return res;} // Driver codeint main(){ int n = 5, r = 3; cout << nCr(n, r); return 0;}",
"e": 1767,
"s": 1381,
"text": null
},
{
"code": "// Java program To calculate// The Value Of nCrclass GFG { static int nCr(int n, int r){ return fact(n) / (fact(r) * fact(n - r));} // Returns factorial of nstatic int fact(int n){ int res = 1; for (int i = 2; i <= n; i++) res = res * i; return res;} // Driver codepublic static void main(String[] args){ int n = 5, r = 3; System.out.println(nCr(n, r));}} // This code is Contributed by// Smitha Dinesh Semwal.",
"e": 2220,
"s": 1767,
"text": null
},
{
"code": "# Python 3 program To calculate# The Value Of nCr def nCr(n, r): return (fact(n) / (fact(r) * fact(n - r))) # Returns factorial of ndef fact(n): res = 1 for i in range(2, n+1): res = res * i return res # Driver coden = 5r = 3print(int(nCr(n, r))) # This code is contributed# by Smitha",
"e": 2555,
"s": 2220,
"text": null
},
{
"code": "// C# program To calculate// The Value Of nCrusing System; class GFG { static int nCr(int n, int r){ return fact(n) / (fact(r) * fact(n - r));} // Returns factorial of nstatic int fact(int n){ int res = 1; for (int i = 2; i <= n; i++) res = res * i; return res;} // Driver code public static void Main() { int n = 5, r = 3; Console.Write(nCr(n, r)); }} // This code is Contributed by nitin mittal.",
"e": 3006,
"s": 2555,
"text": null
},
{
"code": "<?php// PHP program To calculate// the Value Of nCr function nCr( $n, $r){ return fact($n) / (fact($r) * fact($n - $r));} // Returns factorial of nfunction fact( $n){ $res = 1; for ( $i = 2; $i <= $n; $i++) $res = $res * $i; return $res;} // Driver code $n = 5; $r = 3; echo nCr($n, $r); // This code is contributed by vt_m.?>",
"e": 3387,
"s": 3006,
"text": null
},
{
"code": "<script> // Javascript program To calculate The Value Of nCr function nCr(n, r){ return fact(n) / (fact(r) * fact(n - r));} // Returns factorial of nfunction fact(n){ var res = 1; for (var i = 2; i <= n; i++) res = res * i; return res;} // Driver codevar n = 5, r = 3;document.write(nCr(n, r)); </script>",
"e": 3712,
"s": 3387,
"text": null
},
{
"code": null,
"e": 3715,
"s": 3712,
"text": "10"
},
{
"code": null,
"e": 3739,
"s": 3717,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 3761,
"s": 3739,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 3922,
"s": 3761,
"text": "More Efficient Solutions: Dynamic Programming | Set 9 (Binomial Coefficient) Space and time efficient Binomial Coefficient All Articles on Binomial Coefficient "
},
{
"code": null,
"e": 3943,
"s": 3922,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 3956,
"s": 3943,
"text": "nitin mittal"
},
{
"code": null,
"e": 3961,
"s": 3956,
"text": "vt_m"
},
{
"code": null,
"e": 3976,
"s": 3961,
"text": "naimishrastogi"
},
{
"code": null,
"e": 3986,
"s": 3976,
"text": "rutvik_56"
},
{
"code": null,
"e": 4000,
"s": 3986,
"text": "opprabhune317"
},
{
"code": null,
"e": 4012,
"s": 4000,
"text": "prophet1999"
},
{
"code": null,
"e": 4033,
"s": 4012,
"text": "binomial coefficient"
},
{
"code": null,
"e": 4043,
"s": 4033,
"text": "factorial"
},
{
"code": null,
"e": 4057,
"s": 4043,
"text": "Combinatorial"
},
{
"code": null,
"e": 4070,
"s": 4057,
"text": "Mathematical"
},
{
"code": null,
"e": 4089,
"s": 4070,
"text": "School Programming"
},
{
"code": null,
"e": 4102,
"s": 4089,
"text": "Mathematical"
},
{
"code": null,
"e": 4116,
"s": 4102,
"text": "Combinatorial"
},
{
"code": null,
"e": 4126,
"s": 4116,
"text": "factorial"
},
{
"code": null,
"e": 4224,
"s": 4126,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4261,
"s": 4224,
"text": "Count of subsets with sum equal to X"
},
{
"code": null,
"e": 4348,
"s": 4261,
"text": "Count Derangements (Permutation such that no element appears in its original position)"
},
{
"code": null,
"e": 4417,
"s": 4348,
"text": "Stack Permutations (Check if an array is stack permutation of other)"
},
{
"code": null,
"e": 4479,
"s": 4417,
"text": "Find the K-th Permutation Sequence of first N natural numbers"
},
{
"code": null,
"e": 4527,
"s": 4479,
"text": "Probability of getting K heads in N coin tosses"
},
{
"code": null,
"e": 4570,
"s": 4527,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 4585,
"s": 4570,
"text": "C++ Data Types"
},
{
"code": null,
"e": 4609,
"s": 4585,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 4630,
"s": 4609,
"text": "Operators in C / C++"
}
] |
How to Make Grouped Boxplots with ggplot2 in R?
|
03 Dec, 2021
In this article, we will discuss how to make a grouped boxplot in the R Programming Language using the ggplot2 package.
Boxplot helps us to visualize the distribution of quantitative data comparing different continuous or categorical variables. Boxplots consist of a five-number summary which helps in detecting and removing outliers from the dataset. These five summary numbers are Minimum, First Quartile, Median, Third Quartile, and Maximum.
Grouped Boxplots are used to visualize the data having multiple subgroups. Also, we can visualize three variables at a time with grouped boxplots where one variable is numerical and the other two are categorical variables. We can visualize the fourth variable by using the color property of ggplot in R.
First, to make a basic boxplot in R using the ggplot2 package, we use the geom_boxplot() function in the R Language.
Syntax:
ggplot(dataframe, aes( x, y ) ) + geom_boxplot()
Example:
Here, is a basic boxplot made using the geom_boxplot function of the ggplot2 package.
R
# load library ggplotlibrary(ggplot2) # Plot boxplot using ggplot function# diamonds dataset used here is inbuilt in the R Languageplot <- ggplot(diamonds, aes(x=factor(cut), y=carat))+ geom_boxplot()+ theme( legend.position = "none" ) # print boxplotplot
Output:
To convert this basic boxplot to grouped boxplot we use the color property of aes() function of the ggplot2 package. Here, we use a third variable as the value of argument color to convert a basic boxplot to grouped boxplot.
Syntax:
ggplot(dataframe, aes( x, y, color = z ) ) + geom_boxplot()
Parameters:
x is first categorical variable
y is quantitative variable
z is second categorical variable.
Example:
Here, is a boxplot grouped by variable color in ggplot2. The diamonds dataset used in example is pre-built in R Language.
R
# load library ggplotlibrary(ggplot2) # Plot boxplot using ggplot function# diamonds dataset used here is inbuilt in the R Languageplot <- ggplot(diamonds, aes(x=factor(cut), y=carat, color = factor(color)))+ geom_boxplot()+ theme( legend.position = "none" ) # print boxplotplot
Output:
There is one more way to make a grouped boxplot in the R language using the ggplot2 package. It is to use facet in ggplot. The faceting functions in ggplot2 offer a general solution to split up the data by one or more variables and make plots with subsets of data together. To create a grouped boxplot, we can use the facet_wrap() function.
Syntax:
ggplot(dataframe, aes( x, y ) ) + geom_boxplot() + facet_wrap(~z)
Parameters:
x is first categorical variable
y is quantitative variable
z is second categorical variable
Example:
Here, is a boxplot grouped by variable color in ggplot2 using facet_wrap() function. The diamonds dataset used in the example is pre-built in R Language. We have also colored the plot by using the cut variable as a value to color argument in the ggplot() function.
R
# load library ggplotlibrary(ggplot2) # Plot boxplot using ggplot function# diamonds dataset used here is inbuilt in the R Languageplot <- ggplot(diamonds, aes(x=factor(cut), y=carat, color=factor(cut) ))+ geom_boxplot()+ theme( legend.position = "none" )+ facet_wrap(~color, ncol=3) # print boxplotplot
Output:
surindertarika1234
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
Logistic Regression in R Programming
R - if statement
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Dec, 2021"
},
{
"code": null,
"e": 148,
"s": 28,
"text": "In this article, we will discuss how to make a grouped boxplot in the R Programming Language using the ggplot2 package."
},
{
"code": null,
"e": 473,
"s": 148,
"text": "Boxplot helps us to visualize the distribution of quantitative data comparing different continuous or categorical variables. Boxplots consist of a five-number summary which helps in detecting and removing outliers from the dataset. These five summary numbers are Minimum, First Quartile, Median, Third Quartile, and Maximum."
},
{
"code": null,
"e": 777,
"s": 473,
"text": "Grouped Boxplots are used to visualize the data having multiple subgroups. Also, we can visualize three variables at a time with grouped boxplots where one variable is numerical and the other two are categorical variables. We can visualize the fourth variable by using the color property of ggplot in R."
},
{
"code": null,
"e": 894,
"s": 777,
"text": "First, to make a basic boxplot in R using the ggplot2 package, we use the geom_boxplot() function in the R Language."
},
{
"code": null,
"e": 902,
"s": 894,
"text": "Syntax:"
},
{
"code": null,
"e": 952,
"s": 902,
"text": "ggplot(dataframe, aes( x, y ) ) + geom_boxplot()"
},
{
"code": null,
"e": 961,
"s": 952,
"text": "Example:"
},
{
"code": null,
"e": 1047,
"s": 961,
"text": "Here, is a basic boxplot made using the geom_boxplot function of the ggplot2 package."
},
{
"code": null,
"e": 1049,
"s": 1047,
"text": "R"
},
{
"code": "# load library ggplotlibrary(ggplot2) # Plot boxplot using ggplot function# diamonds dataset used here is inbuilt in the R Languageplot <- ggplot(diamonds, aes(x=factor(cut), y=carat))+ geom_boxplot()+ theme( legend.position = \"none\" ) # print boxplotplot",
"e": 1314,
"s": 1049,
"text": null
},
{
"code": null,
"e": 1323,
"s": 1314,
"text": "Output: "
},
{
"code": null,
"e": 1548,
"s": 1323,
"text": "To convert this basic boxplot to grouped boxplot we use the color property of aes() function of the ggplot2 package. Here, we use a third variable as the value of argument color to convert a basic boxplot to grouped boxplot."
},
{
"code": null,
"e": 1556,
"s": 1548,
"text": "Syntax:"
},
{
"code": null,
"e": 1618,
"s": 1556,
"text": "ggplot(dataframe, aes( x, y, color = z ) ) + geom_boxplot() "
},
{
"code": null,
"e": 1630,
"s": 1618,
"text": "Parameters:"
},
{
"code": null,
"e": 1662,
"s": 1630,
"text": "x is first categorical variable"
},
{
"code": null,
"e": 1689,
"s": 1662,
"text": "y is quantitative variable"
},
{
"code": null,
"e": 1723,
"s": 1689,
"text": "z is second categorical variable."
},
{
"code": null,
"e": 1732,
"s": 1723,
"text": "Example:"
},
{
"code": null,
"e": 1854,
"s": 1732,
"text": "Here, is a boxplot grouped by variable color in ggplot2. The diamonds dataset used in example is pre-built in R Language."
},
{
"code": null,
"e": 1856,
"s": 1854,
"text": "R"
},
{
"code": "# load library ggplotlibrary(ggplot2) # Plot boxplot using ggplot function# diamonds dataset used here is inbuilt in the R Languageplot <- ggplot(diamonds, aes(x=factor(cut), y=carat, color = factor(color)))+ geom_boxplot()+ theme( legend.position = \"none\" ) # print boxplotplot",
"e": 2144,
"s": 1856,
"text": null
},
{
"code": null,
"e": 2152,
"s": 2144,
"text": "Output:"
},
{
"code": null,
"e": 2493,
"s": 2152,
"text": "There is one more way to make a grouped boxplot in the R language using the ggplot2 package. It is to use facet in ggplot. The faceting functions in ggplot2 offer a general solution to split up the data by one or more variables and make plots with subsets of data together. To create a grouped boxplot, we can use the facet_wrap() function."
},
{
"code": null,
"e": 2501,
"s": 2493,
"text": "Syntax:"
},
{
"code": null,
"e": 2568,
"s": 2501,
"text": "ggplot(dataframe, aes( x, y ) ) + geom_boxplot() + facet_wrap(~z)"
},
{
"code": null,
"e": 2580,
"s": 2568,
"text": "Parameters:"
},
{
"code": null,
"e": 2612,
"s": 2580,
"text": "x is first categorical variable"
},
{
"code": null,
"e": 2639,
"s": 2612,
"text": "y is quantitative variable"
},
{
"code": null,
"e": 2672,
"s": 2639,
"text": "z is second categorical variable"
},
{
"code": null,
"e": 2681,
"s": 2672,
"text": "Example:"
},
{
"code": null,
"e": 2946,
"s": 2681,
"text": "Here, is a boxplot grouped by variable color in ggplot2 using facet_wrap() function. The diamonds dataset used in the example is pre-built in R Language. We have also colored the plot by using the cut variable as a value to color argument in the ggplot() function."
},
{
"code": null,
"e": 2948,
"s": 2946,
"text": "R"
},
{
"code": "# load library ggplotlibrary(ggplot2) # Plot boxplot using ggplot function# diamonds dataset used here is inbuilt in the R Languageplot <- ggplot(diamonds, aes(x=factor(cut), y=carat, color=factor(cut) ))+ geom_boxplot()+ theme( legend.position = \"none\" )+ facet_wrap(~color, ncol=3) # print boxplotplot",
"e": 3265,
"s": 2948,
"text": null
},
{
"code": null,
"e": 3273,
"s": 3265,
"text": "Output:"
},
{
"code": null,
"e": 3292,
"s": 3273,
"text": "surindertarika1234"
},
{
"code": null,
"e": 3299,
"s": 3292,
"text": "Picked"
},
{
"code": null,
"e": 3308,
"s": 3299,
"text": "R-ggplot"
},
{
"code": null,
"e": 3319,
"s": 3308,
"text": "R Language"
},
{
"code": null,
"e": 3417,
"s": 3319,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3469,
"s": 3417,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 3527,
"s": 3469,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 3562,
"s": 3527,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 3600,
"s": 3562,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 3649,
"s": 3600,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 3686,
"s": 3649,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 3703,
"s": 3686,
"text": "R - if statement"
},
{
"code": null,
"e": 3746,
"s": 3703,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 3783,
"s": 3746,
"text": "How to import an Excel File into R ?"
}
] |
How to import config.php file in a PHP script ?
|
02 Mar, 2020
The include statement in PHP copies the code of text from the file mentioned, into the file that uses the include statement. It directs the preprocessor to insert the content specified into the following program. The name of the file to be included is written in double-quotes. It is a good practice to write the basic database details and user details in a file named “config.php”. You can also include the connection building statements in the config.php file to automatically build the connection to the database for every page that includes the config.php file. Including files allows you to form a template of code that is required by multiple pages of a website.
Syntax:
<?php
include('config.php');
?>
Example 1: This shows the creation and including of config.php file.
Code 1: Create a PHP file and save it with the name ‘config.php’.<?php $host = 'localhost'; $database = 'GeeksForGeeks'; $username = 'admin'; $password = '';?>
<?php $host = 'localhost'; $database = 'GeeksForGeeks'; $username = 'admin'; $password = '';?>
Code 2: Create a PHP file and save it with the name ‘try.php’ in the same folder as ‘config.php’ file. Copy the below code to include the ‘config.php’ file and get a print the name of the database and username.<?php include('config.php'); echo "Host: ".$host." Database: ".$database;?>
<?php include('config.php'); echo "Host: ".$host." Database: ".$database;?>
Output:
Example 2: If you want to save the contents of the config.php file into a variable, then the following code does that work.
Code 1: Simply return the contents of the ‘config.php’ file.<?php return [ 'host' => 'localhost2', 'database' => 'GeeksForGeeks2', 'username' => 'admin', 'password' => '' ];?>
<?php return [ 'host' => 'localhost2', 'database' => 'GeeksForGeeks2', 'username' => 'admin', 'password' => '' ];?>
Code 2: Accept the returning array in a variable.<?php $details = include('config.php'); echo 'Host: ' . $details['host'] . ' Database: ' . $details['database'];?>
<?php $details = include('config.php'); echo 'Host: ' . $details['host'] . ' Database: ' . $details['database'];?>
Output:
PHP-Misc
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
Comparing two dates in PHP
How to get parameters from a URL string in PHP?
Split a comma delimited string into an array in PHP
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
Comparing two dates in PHP
Split a comma delimited string into an array in PHP
How to get parameters from a URL string in PHP?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Mar, 2020"
},
{
"code": null,
"e": 697,
"s": 28,
"text": "The include statement in PHP copies the code of text from the file mentioned, into the file that uses the include statement. It directs the preprocessor to insert the content specified into the following program. The name of the file to be included is written in double-quotes. It is a good practice to write the basic database details and user details in a file named “config.php”. You can also include the connection building statements in the config.php file to automatically build the connection to the database for every page that includes the config.php file. Including files allows you to form a template of code that is required by multiple pages of a website."
},
{
"code": null,
"e": 705,
"s": 697,
"text": "Syntax:"
},
{
"code": null,
"e": 740,
"s": 705,
"text": "<?php\n include('config.php');\n?>"
},
{
"code": null,
"e": 809,
"s": 740,
"text": "Example 1: This shows the creation and including of config.php file."
},
{
"code": null,
"e": 977,
"s": 809,
"text": "Code 1: Create a PHP file and save it with the name ‘config.php’.<?php $host = 'localhost'; $database = 'GeeksForGeeks'; $username = 'admin'; $password = '';?>"
},
{
"code": "<?php $host = 'localhost'; $database = 'GeeksForGeeks'; $username = 'admin'; $password = '';?>",
"e": 1080,
"s": 977,
"text": null
},
{
"code": null,
"e": 1370,
"s": 1080,
"text": "Code 2: Create a PHP file and save it with the name ‘try.php’ in the same folder as ‘config.php’ file. Copy the below code to include the ‘config.php’ file and get a print the name of the database and username.<?php include('config.php'); echo \"Host: \".$host.\" Database: \".$database;?>"
},
{
"code": "<?php include('config.php'); echo \"Host: \".$host.\" Database: \".$database;?>",
"e": 1450,
"s": 1370,
"text": null
},
{
"code": null,
"e": 1458,
"s": 1450,
"text": "Output:"
},
{
"code": null,
"e": 1582,
"s": 1458,
"text": "Example 2: If you want to save the contents of the config.php file into a variable, then the following code does that work."
},
{
"code": null,
"e": 1770,
"s": 1582,
"text": "Code 1: Simply return the contents of the ‘config.php’ file.<?php return [ 'host' => 'localhost2', 'database' => 'GeeksForGeeks2', 'username' => 'admin', 'password' => '' ];?>"
},
{
"code": "<?php return [ 'host' => 'localhost2', 'database' => 'GeeksForGeeks2', 'username' => 'admin', 'password' => '' ];?>",
"e": 1898,
"s": 1770,
"text": null
},
{
"code": null,
"e": 2074,
"s": 1898,
"text": "Code 2: Accept the returning array in a variable.<?php $details = include('config.php'); echo 'Host: ' . $details['host'] . ' Database: ' . $details['database'];?>"
},
{
"code": "<?php $details = include('config.php'); echo 'Host: ' . $details['host'] . ' Database: ' . $details['database'];?>",
"e": 2201,
"s": 2074,
"text": null
},
{
"code": null,
"e": 2209,
"s": 2201,
"text": "Output:"
},
{
"code": null,
"e": 2218,
"s": 2209,
"text": "PHP-Misc"
},
{
"code": null,
"e": 2225,
"s": 2218,
"text": "Picked"
},
{
"code": null,
"e": 2229,
"s": 2225,
"text": "PHP"
},
{
"code": null,
"e": 2242,
"s": 2229,
"text": "PHP Programs"
},
{
"code": null,
"e": 2259,
"s": 2242,
"text": "Web Technologies"
},
{
"code": null,
"e": 2286,
"s": 2259,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2290,
"s": 2286,
"text": "PHP"
},
{
"code": null,
"e": 2388,
"s": 2290,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2428,
"s": 2388,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 2473,
"s": 2428,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 2500,
"s": 2473,
"text": "Comparing two dates in PHP"
},
{
"code": null,
"e": 2548,
"s": 2500,
"text": "How to get parameters from a URL string in PHP?"
},
{
"code": null,
"e": 2600,
"s": 2548,
"text": "Split a comma delimited string into an array in PHP"
},
{
"code": null,
"e": 2640,
"s": 2600,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 2692,
"s": 2640,
"text": "How to call PHP function on the click of a Button ?"
},
{
"code": null,
"e": 2719,
"s": 2692,
"text": "Comparing two dates in PHP"
},
{
"code": null,
"e": 2771,
"s": 2719,
"text": "Split a comma delimited string into an array in PHP"
}
] |
Node.js Date.addDays() API
|
12 Mar, 2021
The date-and-time.Date.addDays() is a minimalist collection of functions for manipulating JS date and time module which is used to add the extra Days to the existing date and time.
Required Module: Install the module by npm or used it locally.
By using npm.
npm install date-and-time --save
By using CDN link.
<script src="/path/to/date-and-time.min.js"></script>
Syntax:
addDays(dateObj, days)
Parameters: This method takes the following arguments as parameters:
dateobject: It is the string object of the date.
days: It is the number of days.
Return Value: This method returns updated date and time.
Example 1:
index.js
// Node.js program to demonstrate the // Date.addDays() method // Importing moduleconst date = require('date-and-time') // Creating object of current date and time // by using Date() const now = new Date(); // Adding Days to the existing date and time// by using date.addDays() methodconst value = date.addDays(now, 24); // Display the resultconsole.log("updated date and time : " + value)
Run the index.js file using the following command:
node index.js
Output:
updated date and time :
Wed Mar 31 2021 20:07:07 GMT+0530 (India Standard Time)
Example 2:
index.js
// Node.js program to demonstrate the // Date.addDays() method // Importing moduleconst date = require('date-and-time') // Creating object of current date and time // by using Date() const now = new Date(); now.setDate(20) // Adding Days to the existing date and time// by using date.addDays() methodconst value = date.addDays(now, 24); // Display the resultconsole.log("updated date and time : " + value)
Run the index.js file using the following command:
node index.js
Output:
updated date and time :
Tue Apr 13 2021 20:09:57 GMT+0530 (India Standard Time)
Reference: https://github.com/knowledgecode/date-and-time#adddaysdateobj-days
NodeJS date-time
NodeJS-API
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Mar, 2021"
},
{
"code": null,
"e": 209,
"s": 28,
"text": "The date-and-time.Date.addDays() is a minimalist collection of functions for manipulating JS date and time module which is used to add the extra Days to the existing date and time."
},
{
"code": null,
"e": 272,
"s": 209,
"text": "Required Module: Install the module by npm or used it locally."
},
{
"code": null,
"e": 286,
"s": 272,
"text": "By using npm."
},
{
"code": null,
"e": 319,
"s": 286,
"text": "npm install date-and-time --save"
},
{
"code": null,
"e": 338,
"s": 319,
"text": "By using CDN link."
},
{
"code": null,
"e": 392,
"s": 338,
"text": "<script src=\"/path/to/date-and-time.min.js\"></script>"
},
{
"code": null,
"e": 400,
"s": 392,
"text": "Syntax:"
},
{
"code": null,
"e": 423,
"s": 400,
"text": "addDays(dateObj, days)"
},
{
"code": null,
"e": 492,
"s": 423,
"text": "Parameters: This method takes the following arguments as parameters:"
},
{
"code": null,
"e": 541,
"s": 492,
"text": "dateobject: It is the string object of the date."
},
{
"code": null,
"e": 573,
"s": 541,
"text": "days: It is the number of days."
},
{
"code": null,
"e": 630,
"s": 573,
"text": "Return Value: This method returns updated date and time."
},
{
"code": null,
"e": 641,
"s": 630,
"text": "Example 1:"
},
{
"code": null,
"e": 650,
"s": 641,
"text": "index.js"
},
{
"code": "// Node.js program to demonstrate the // Date.addDays() method // Importing moduleconst date = require('date-and-time') // Creating object of current date and time // by using Date() const now = new Date(); // Adding Days to the existing date and time// by using date.addDays() methodconst value = date.addDays(now, 24); // Display the resultconsole.log(\"updated date and time : \" + value)",
"e": 1045,
"s": 650,
"text": null
},
{
"code": null,
"e": 1096,
"s": 1045,
"text": "Run the index.js file using the following command:"
},
{
"code": null,
"e": 1110,
"s": 1096,
"text": "node index.js"
},
{
"code": null,
"e": 1118,
"s": 1110,
"text": "Output:"
},
{
"code": null,
"e": 1198,
"s": 1118,
"text": "updated date and time :\nWed Mar 31 2021 20:07:07 GMT+0530 (India Standard Time)"
},
{
"code": null,
"e": 1209,
"s": 1198,
"text": "Example 2:"
},
{
"code": null,
"e": 1218,
"s": 1209,
"text": "index.js"
},
{
"code": "// Node.js program to demonstrate the // Date.addDays() method // Importing moduleconst date = require('date-and-time') // Creating object of current date and time // by using Date() const now = new Date(); now.setDate(20) // Adding Days to the existing date and time// by using date.addDays() methodconst value = date.addDays(now, 24); // Display the resultconsole.log(\"updated date and time : \" + value)",
"e": 1630,
"s": 1218,
"text": null
},
{
"code": null,
"e": 1681,
"s": 1630,
"text": "Run the index.js file using the following command:"
},
{
"code": null,
"e": 1695,
"s": 1681,
"text": "node index.js"
},
{
"code": null,
"e": 1703,
"s": 1695,
"text": "Output:"
},
{
"code": null,
"e": 1784,
"s": 1703,
"text": "updated date and time : \nTue Apr 13 2021 20:09:57 GMT+0530 (India Standard Time)"
},
{
"code": null,
"e": 1862,
"s": 1784,
"text": "Reference: https://github.com/knowledgecode/date-and-time#adddaysdateobj-days"
},
{
"code": null,
"e": 1879,
"s": 1862,
"text": "NodeJS date-time"
},
{
"code": null,
"e": 1890,
"s": 1879,
"text": "NodeJS-API"
},
{
"code": null,
"e": 1898,
"s": 1890,
"text": "Node.js"
},
{
"code": null,
"e": 1915,
"s": 1898,
"text": "Web Technologies"
}
] |
tgamma() method in C/C++ with Examples
|
04 Oct, 2021
The tgamma() function is defined in header math.h header in C and cmath library in C++. This function is used to compute the gamma function of an argument passed to the function.Syntax:
float tgamma(float x);
double tgamma(double x);
long double tgamma(long double x);
Parameters: This method accepts a parameter x which is the value whose gamma function is to be computed. It can be float, double or long double.Return Value: This function returns the gamma function value of x.
For x = 0: +inf/-inf
For x = -inf: NAN
For x = +inf: +inf
For x = -ve: NAN
For x = NAN: NAN
Errors: There are two types of errors that usually occur with tgamma() method:
Range errors: Overflow range error: This occurs when the magnitude of the parameter x is very large.Underflow range error: This occurs when the magnitude of the parameter x is very small.Domain/Pole errors: If x is zero or a negative integer for which the function is asymptotic, it may cause a domain error or a pole error (or none, depending on implementation).
Range errors: Overflow range error: This occurs when the magnitude of the parameter x is very large.Underflow range error: This occurs when the magnitude of the parameter x is very small.
Overflow range error: This occurs when the magnitude of the parameter x is very large.
Underflow range error: This occurs when the magnitude of the parameter x is very small.
Domain/Pole errors: If x is zero or a negative integer for which the function is asymptotic, it may cause a domain error or a pole error (or none, depending on implementation).
If x is zero or a negative integer for which the function is asymptotic, it may cause a domain error or a pole error (or none, depending on implementation).
Below examples demonstrate the use of tgamma() function in C/C++:
CPP
// C++ program to show the// use of tgamma() method #include <cmath>#include <iostream>using namespace std; // Driver codeint main(){ // Example 1 float x = 0.0; cout << "For x = " << x << ", tgamma(x) = " << tgamma(x) << endl; // Example 2 x = -18.0 / 0.0; cout << "For x = " << x << ", tgamma(x) = " << tgamma(x) << endl; // Example 3 x = 10.0 / 0.0; cout << "For x = " << x << ", tgamma(x) = " << tgamma(x) << endl; // Example 4 x = 0.0 / 0.0; cout << "For x = " << x << ", tgamma(x) = " << tgamma(x); return 0;}
For x = 0, tgamma(x) = inf
For x = -inf, tgamma(x) = nan
For x = inf, tgamma(x) = inf
For x = -nan, tgamma(x) = -nan
Reference: http://www.cplusplus.com/reference/cmath/tgamma/
sagartomar9927
C-Functions
CPP-Functions
cpp-math
math
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
Operators in C / C++
Exception Handling in C++
What is the purpose of a function prototype?
Sorting Vector of Pairs in C++ | Set 1 (Sort by first and second)
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)
Priority Queue in C++ Standard Template Library (STL)
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Oct, 2021"
},
{
"code": null,
"e": 216,
"s": 28,
"text": "The tgamma() function is defined in header math.h header in C and cmath library in C++. This function is used to compute the gamma function of an argument passed to the function.Syntax: "
},
{
"code": null,
"e": 305,
"s": 216,
"text": "float tgamma(float x); \ndouble tgamma(double x); \nlong double tgamma(long double x); "
},
{
"code": null,
"e": 518,
"s": 305,
"text": "Parameters: This method accepts a parameter x which is the value whose gamma function is to be computed. It can be float, double or long double.Return Value: This function returns the gamma function value of x. "
},
{
"code": null,
"e": 539,
"s": 518,
"text": "For x = 0: +inf/-inf"
},
{
"code": null,
"e": 557,
"s": 539,
"text": "For x = -inf: NAN"
},
{
"code": null,
"e": 576,
"s": 557,
"text": "For x = +inf: +inf"
},
{
"code": null,
"e": 593,
"s": 576,
"text": "For x = -ve: NAN"
},
{
"code": null,
"e": 610,
"s": 593,
"text": "For x = NAN: NAN"
},
{
"code": null,
"e": 691,
"s": 610,
"text": "Errors: There are two types of errors that usually occur with tgamma() method: "
},
{
"code": null,
"e": 1055,
"s": 691,
"text": "Range errors: Overflow range error: This occurs when the magnitude of the parameter x is very large.Underflow range error: This occurs when the magnitude of the parameter x is very small.Domain/Pole errors: If x is zero or a negative integer for which the function is asymptotic, it may cause a domain error or a pole error (or none, depending on implementation)."
},
{
"code": null,
"e": 1243,
"s": 1055,
"text": "Range errors: Overflow range error: This occurs when the magnitude of the parameter x is very large.Underflow range error: This occurs when the magnitude of the parameter x is very small."
},
{
"code": null,
"e": 1330,
"s": 1243,
"text": "Overflow range error: This occurs when the magnitude of the parameter x is very large."
},
{
"code": null,
"e": 1418,
"s": 1330,
"text": "Underflow range error: This occurs when the magnitude of the parameter x is very small."
},
{
"code": null,
"e": 1595,
"s": 1418,
"text": "Domain/Pole errors: If x is zero or a negative integer for which the function is asymptotic, it may cause a domain error or a pole error (or none, depending on implementation)."
},
{
"code": null,
"e": 1752,
"s": 1595,
"text": "If x is zero or a negative integer for which the function is asymptotic, it may cause a domain error or a pole error (or none, depending on implementation)."
},
{
"code": null,
"e": 1819,
"s": 1752,
"text": "Below examples demonstrate the use of tgamma() function in C/C++: "
},
{
"code": null,
"e": 1823,
"s": 1819,
"text": "CPP"
},
{
"code": "// C++ program to show the// use of tgamma() method #include <cmath>#include <iostream>using namespace std; // Driver codeint main(){ // Example 1 float x = 0.0; cout << \"For x = \" << x << \", tgamma(x) = \" << tgamma(x) << endl; // Example 2 x = -18.0 / 0.0; cout << \"For x = \" << x << \", tgamma(x) = \" << tgamma(x) << endl; // Example 3 x = 10.0 / 0.0; cout << \"For x = \" << x << \", tgamma(x) = \" << tgamma(x) << endl; // Example 4 x = 0.0 / 0.0; cout << \"For x = \" << x << \", tgamma(x) = \" << tgamma(x); return 0;}",
"e": 2447,
"s": 1823,
"text": null
},
{
"code": null,
"e": 2564,
"s": 2447,
"text": "For x = 0, tgamma(x) = inf\nFor x = -inf, tgamma(x) = nan\nFor x = inf, tgamma(x) = inf\nFor x = -nan, tgamma(x) = -nan"
},
{
"code": null,
"e": 2627,
"s": 2566,
"text": "Reference: http://www.cplusplus.com/reference/cmath/tgamma/ "
},
{
"code": null,
"e": 2642,
"s": 2627,
"text": "sagartomar9927"
},
{
"code": null,
"e": 2654,
"s": 2642,
"text": "C-Functions"
},
{
"code": null,
"e": 2668,
"s": 2654,
"text": "CPP-Functions"
},
{
"code": null,
"e": 2677,
"s": 2668,
"text": "cpp-math"
},
{
"code": null,
"e": 2682,
"s": 2677,
"text": "math"
},
{
"code": null,
"e": 2693,
"s": 2682,
"text": "C Language"
},
{
"code": null,
"e": 2697,
"s": 2693,
"text": "C++"
},
{
"code": null,
"e": 2701,
"s": 2697,
"text": "CPP"
},
{
"code": null,
"e": 2799,
"s": 2701,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2847,
"s": 2799,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 2868,
"s": 2847,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 2894,
"s": 2868,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 2939,
"s": 2894,
"text": "What is the purpose of a function prototype?"
},
{
"code": null,
"e": 3005,
"s": 2939,
"text": "Sorting Vector of Pairs in C++ | Set 1 (Sort by first and second)"
},
{
"code": null,
"e": 3023,
"s": 3005,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 3066,
"s": 3023,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3112,
"s": 3066,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 3155,
"s": 3112,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
How To Rename Columns In Pandas | Towards Data Science
|
Renaming dataframe columns is a common practise especially when we are interested in sharing some insights with other people and teams. This means that we may wish to make column names more meaningful so that it would be easier for readers to relate them to specific contexts.
In this short article, we will look at a few of options we have when it comes down to renaming columns of pandas DataFrames. Specifically, we are going to see how to rename columns:
using the rename() method
by updating the DataFrame.columns attribute
and using set_axis() method
First, let’s create an example DataFrame that will reference throughout this guide in order to showcase the desired pandas functionality.
import pandas as pddf = pd.DataFrame({ 'colA':[1, 2, 3], 'colB': ['a', 'b', 'c'],})print(df)# colA colB# 0 1 a# 1 2 b# 2 3 c
pandas.DataFrame.rename() can be used to alter columns’ or index name.
Alter axes labels.
Function / dict values must be unique (1-to-1). Labels not contained in a dict / Series will be left as-is.
In order to rename columns using rename() method, we need to provide a mapping (i.e. a dictionary) where keys are the old column name(s) and values are the new one(s). Additionally, we must specify axis=1 in order to denote that we wish to rename columns and not the index:
df = df.rename({'colA': 'A', 'colB': 'B'}, axis=1)print(df)# A B# 0 1 a# 1 2 b# 2 3 c
pandas DataFrames come with pandas.DataFrames.columns attribute which is an Index containing the column labels of the DataFrame.
We can rename DataFrame columns by re-assigning this particular attribute as shown below:
df.columns = ['column_A', 'column_B']print(df)# column_A column_B# 0 1 a# 1 2 b# 2 3 c
pandas.DataFrame.set_axis() method can be used to assign a desired index to either the column or index axis. In order to rename the column names, make sure to provide axis=1 as shown below:
df = df.set_axis(['AA', 'BB'], axis=1, inplace=False)print(df)# AA BB# 0 1 a# 1 2 b# 2 3 c
Note that in all of the examples discussed earlier, you can even use axis='columns' instead of axis=1 in order to denote that the operation should be effective on the column level. For example,
df = df.rename({'colA': 'A', 'colB': 'B'}, axis='columns')df = df.set_axis(['AA', 'BB'], axis='columns')
In today’s short guide we discussed how to rename columns of pandas DataFrames in a few different ways.
You may also be interested in understanding how to change the data types of specific columns of pandas DataFrames.
towardsdatascience.com
Additionally, the article below discusses how to perform proper row selection based on specific conditions.
|
[
{
"code": null,
"e": 448,
"s": 171,
"text": "Renaming dataframe columns is a common practise especially when we are interested in sharing some insights with other people and teams. This means that we may wish to make column names more meaningful so that it would be easier for readers to relate them to specific contexts."
},
{
"code": null,
"e": 630,
"s": 448,
"text": "In this short article, we will look at a few of options we have when it comes down to renaming columns of pandas DataFrames. Specifically, we are going to see how to rename columns:"
},
{
"code": null,
"e": 656,
"s": 630,
"text": "using the rename() method"
},
{
"code": null,
"e": 700,
"s": 656,
"text": "by updating the DataFrame.columns attribute"
},
{
"code": null,
"e": 728,
"s": 700,
"text": "and using set_axis() method"
},
{
"code": null,
"e": 866,
"s": 728,
"text": "First, let’s create an example DataFrame that will reference throughout this guide in order to showcase the desired pandas functionality."
},
{
"code": null,
"e": 1022,
"s": 866,
"text": "import pandas as pddf = pd.DataFrame({ 'colA':[1, 2, 3], 'colB': ['a', 'b', 'c'],})print(df)# colA colB# 0 1 a# 1 2 b# 2 3 c"
},
{
"code": null,
"e": 1093,
"s": 1022,
"text": "pandas.DataFrame.rename() can be used to alter columns’ or index name."
},
{
"code": null,
"e": 1112,
"s": 1093,
"text": "Alter axes labels."
},
{
"code": null,
"e": 1220,
"s": 1112,
"text": "Function / dict values must be unique (1-to-1). Labels not contained in a dict / Series will be left as-is."
},
{
"code": null,
"e": 1494,
"s": 1220,
"text": "In order to rename columns using rename() method, we need to provide a mapping (i.e. a dictionary) where keys are the old column name(s) and values are the new one(s). Additionally, we must specify axis=1 in order to denote that we wish to rename columns and not the index:"
},
{
"code": null,
"e": 1590,
"s": 1494,
"text": "df = df.rename({'colA': 'A', 'colB': 'B'}, axis=1)print(df)# A B# 0 1 a# 1 2 b# 2 3 c"
},
{
"code": null,
"e": 1719,
"s": 1590,
"text": "pandas DataFrames come with pandas.DataFrames.columns attribute which is an Index containing the column labels of the DataFrame."
},
{
"code": null,
"e": 1809,
"s": 1719,
"text": "We can rename DataFrame columns by re-assigning this particular attribute as shown below:"
},
{
"code": null,
"e": 1944,
"s": 1809,
"text": "df.columns = ['column_A', 'column_B']print(df)# column_A column_B# 0 1 a# 1 2 b# 2 3 c"
},
{
"code": null,
"e": 2134,
"s": 1944,
"text": "pandas.DataFrame.set_axis() method can be used to assign a desired index to either the column or index axis. In order to rename the column names, make sure to provide axis=1 as shown below:"
},
{
"code": null,
"e": 2237,
"s": 2134,
"text": "df = df.set_axis(['AA', 'BB'], axis=1, inplace=False)print(df)# AA BB# 0 1 a# 1 2 b# 2 3 c"
},
{
"code": null,
"e": 2431,
"s": 2237,
"text": "Note that in all of the examples discussed earlier, you can even use axis='columns' instead of axis=1 in order to denote that the operation should be effective on the column level. For example,"
},
{
"code": null,
"e": 2536,
"s": 2431,
"text": "df = df.rename({'colA': 'A', 'colB': 'B'}, axis='columns')df = df.set_axis(['AA', 'BB'], axis='columns')"
},
{
"code": null,
"e": 2640,
"s": 2536,
"text": "In today’s short guide we discussed how to rename columns of pandas DataFrames in a few different ways."
},
{
"code": null,
"e": 2755,
"s": 2640,
"text": "You may also be interested in understanding how to change the data types of specific columns of pandas DataFrames."
},
{
"code": null,
"e": 2778,
"s": 2755,
"text": "towardsdatascience.com"
}
] |
C# | Check if Caps Lock is on or off through Console - GeeksforGeeks
|
28 Jan, 2019
Given the normal Console in C#, the task is to check if the CAPS LOCK is on or off through Console.
Approach: This can be done using the CAPS LOCK property in the Console class of the System package in C#.
Program 1: When the CAPS LOCK is on
// C# program to illustrate the// Console.CapsLock Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Check if CAPS LOCK is on or off Console.WriteLine("Is CAPS LOCK on: {0}", Console.CapsLock); }}}
Output:
Program 2: When the CAPS LOCK is off
// C# program to illustrate the// Console.CapsLock Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Check if CAPS LOCK is on or off Console.WriteLine("Is CAPS LOCK on: {0}", Console.CapsLock); }}}
Output:
CSharp-Console-Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
C# | Method Overriding
C# | Abstract Classes
Extension Method in C#
Difference between Ref and Out keywords in C#
C# | Replace() Method
C# | Class and Object
C# | Constructors
C# | String.IndexOf( ) Method | Set - 1
|
[
{
"code": null,
"e": 26463,
"s": 26435,
"text": "\n28 Jan, 2019"
},
{
"code": null,
"e": 26563,
"s": 26463,
"text": "Given the normal Console in C#, the task is to check if the CAPS LOCK is on or off through Console."
},
{
"code": null,
"e": 26669,
"s": 26563,
"text": "Approach: This can be done using the CAPS LOCK property in the Console class of the System package in C#."
},
{
"code": null,
"e": 26705,
"s": 26669,
"text": "Program 1: When the CAPS LOCK is on"
},
{
"code": "// C# program to illustrate the// Console.CapsLock Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Check if CAPS LOCK is on or off Console.WriteLine(\"Is CAPS LOCK on: {0}\", Console.CapsLock); }}}",
"e": 27101,
"s": 26705,
"text": null
},
{
"code": null,
"e": 27109,
"s": 27101,
"text": "Output:"
},
{
"code": null,
"e": 27146,
"s": 27109,
"text": "Program 2: When the CAPS LOCK is off"
},
{
"code": "// C# program to illustrate the// Console.CapsLock Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Check if CAPS LOCK is on or off Console.WriteLine(\"Is CAPS LOCK on: {0}\", Console.CapsLock); }}}",
"e": 27542,
"s": 27146,
"text": null
},
{
"code": null,
"e": 27550,
"s": 27542,
"text": "Output:"
},
{
"code": null,
"e": 27571,
"s": 27550,
"text": "CSharp-Console-Class"
},
{
"code": null,
"e": 27574,
"s": 27571,
"text": "C#"
},
{
"code": null,
"e": 27672,
"s": 27574,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27700,
"s": 27672,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 27715,
"s": 27700,
"text": "C# | Delegates"
},
{
"code": null,
"e": 27738,
"s": 27715,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 27760,
"s": 27738,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 27783,
"s": 27760,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27829,
"s": 27783,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 27851,
"s": 27829,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 27873,
"s": 27851,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 27891,
"s": 27873,
"text": "C# | Constructors"
}
] |
Design IIR Lowpass Butterworth Filter using Bilinear Transformation Method in Scipy- Python - GeeksforGeeks
|
16 Dec, 2021
IIR stands for Infinite Impulse Response, It is one of the striking features of many linear-time invariant systems that are distinguished by having an impulse response h(t)/h(n) which does not become zero after some point but instead continues infinitely.
It basically behaves just like an ordinary digital Lowpass Butterworth Filter with an infinite impulse response.
The specifications are as follows:
Sampling rate of 8 kHz
Order of Filter 2
Cutoff-frequency 3400Hz
We will plot the magnitude & phase response of the filter.
Step-by-step Approach:
Step 1: Importing all the necessary libraries.
Python3
# import required library
import numpy as np
import scipy.signal as signal
import matplotlib.pyplot as plt
Step 2: Define variables with the given specifications of the filter.
Python3
# Given specification
N = 2 # Order of the filter
Fs = 8000 # Sampling frequency in Hz
fc = 3400 # Cut-off frequency in Hz
# Compute Design Sampling parameter
Td = 1/Fs
Step 3: Computing the cut-off frequency
Python3
# Compute cut-off frequency in radian/sec
wd = 2*np.pi*fc
print(wd) # Cut-off frequency in radian/sec
Output:
Step 4: Pre-wrapping the analog frequency
Python3
# Prewarp the analog frequency
wc = (2/Td)*np.tan(wd*Td/2)
print('Order of the filter=', N) # Order
# Prewarped analog cut-off frequency
print('Cut-off frequency (in rad/s)=', wc)
Output:
Step 5: Designing the filter using signal.butter() function and then performing bilinear transformation using signal.bilinear() function
Python3
# Design analog Butterworth filter using signal.butter function
b, a = signal.butter(N, wc, 'low', analog='True')
# Perform bilinear Transformation
z, p = signal.bilinear(b, a, fs=Fs)
# Print numerator and denomerator coefficients of the filter
print('Numerator Coefficients:', z)
print('Denominator Coefficients:', p)
Output:
Step 6: Computing the frequency response of the filter using signal.freqz() function and plotting the magnitude and phase response
Python3
# Compute frequency response of the filter using signal.freqz function
wz, hz = signal.freqz(z, p, 512)
# Plot filter magnitude and phase responses using subplot.
# Convert digital frequency wz into analog frequency in Hz
fig = plt.figure(figsize=(12, 10))
# Calculate Magnitude from hz in dB
Mag = 20*np.log10(abs(hz))
# Calculate frequency in Hz from wz
Freq = wz*Fs/(2*np.pi)
# Plot Magnitude response
sub1 = plt.subplot(2, 1, 1)
sub1.plot(Freq, Mag, 'r', linewidth=2)
sub1.axis([1, Fs/2, -60, 5])
sub1.set_title('Magnitude Response', fontsize=15)
sub1.set_xlabel('Frequency [Hz]', fontsize=15)
sub1.set_ylabel('Magnitude [dB]', fontsize=15)
sub1.grid()
# Plot phase angle
sub2 = plt.subplot(2, 1, 2)
# Calculate phase angle in degree from hz
Phase = np.unwrap(np.angle(hz))*180/np.pi
sub2.plot(Freq, Phase, 'g', linewidth=2)
sub2.set_ylabel('Phase (degree)', fontsize=15)
sub2.set_xlabel(r'Frequency (Hz)', fontsize=15)
sub2.set_title(r'Phase response', fontsize=15)
sub2.grid()
plt.subplots_adjust(hspace=0.5)
fig.tight_layout()
plt.show()
Output:
Below is the implementation:
Python3
# import required library
import numpy as np
import scipy.signal as signal
import matplotlib.pyplot as plt
# Given specification
N = 2 # Order of the filter
Fs = 8000 # Sampling frequency in Hz
fc = 3400 # Cut-off frequency in Hz
# Compute Design Sampling parameter
Td = 1/Fs
# Compute cut-off frequency in radian/sec
wd = 2*np.pi*fc
print(wd) # Cut-off frequency in radian/sec
# Prewarp the analog frequency
wc = (2/Td)*np.tan(wd*Td/2)
print('Order of the filter=', N) # Order
# Prewarped analog cut-off frequency
print('Cut-off frequency (in rad/s)=', wc)
# Design analog Butterworth filter using signal.butter function
b, a = signal.butter(N, wc, 'low', analog='True')
# Perform bilinear Transformation
z, p = signal.bilinear(b, a, fs=Fs)
# Print numerator and denomerator coefficients of the filter
print('Numerator Coefficients:', z)
print('Denominator Coefficients:', p)
# Compute frequency response of the filter using signal.freqz function
wz, hz = signal.freqz(z, p, 512)
# Plot filter magnitude and phase responses using subplot.
#Convert digital frequency wz into analog frequency in Hz
fig = plt.figure(figsize=(10, 8))
# Calculate Magnitude from hz in dB
Mag = 20*np.log10(abs(hz))
# Calculate frequency in Hz from wz
Freq = wz*Fs/(2*np.pi)
# Plot Magnitude response
sub1 = plt.subplot(2, 1, 1)
sub1.plot(Freq, Mag, 'r', linewidth=2)
sub1.axis([1, Fs/2, -60, 5])
sub1.set_title('Magnitude Response', fontsize=15)
sub1.set_xlabel('Frequency [Hz]', fontsize=15)
sub1.set_ylabel('Magnitude [dB]', fontsize=15)
sub1.grid()
# Plot phase angle
sub2 = plt.subplot(2, 1, 2)
# Calculate phase angle in degree from hz
Phase = np.unwrap(np.angle(hz))*180/np.pi
sub2.plot(Freq, Phase, 'g', linewidth=2)
sub2.set_ylabel('Phase (degree)', fontsize=15)
sub2.set_xlabel(r'Frequency (Hz)', fontsize=15)
sub2.set_title(r'Phase response', fontsize=15)
sub2.grid()
plt.subplots_adjust(hspace=0.5)
fig.tight_layout()
plt.show()
Output:
gulshankumarar231
Data Visualization
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
|
[
{
"code": null,
"e": 25719,
"s": 25688,
"text": " \n16 Dec, 2021\n"
},
{
"code": null,
"e": 25975,
"s": 25719,
"text": "IIR stands for Infinite Impulse Response, It is one of the striking features of many linear-time invariant systems that are distinguished by having an impulse response h(t)/h(n) which does not become zero after some point but instead continues infinitely."
},
{
"code": null,
"e": 26089,
"s": 25975,
"text": "It basically behaves just like an ordinary digital Lowpass Butterworth Filter with an infinite impulse response. "
},
{
"code": null,
"e": 26126,
"s": 26089,
"text": "The specifications are as follows: "
},
{
"code": null,
"e": 26149,
"s": 26126,
"text": "Sampling rate of 8 kHz"
},
{
"code": null,
"e": 26167,
"s": 26149,
"text": "Order of Filter 2"
},
{
"code": null,
"e": 26191,
"s": 26167,
"text": "Cutoff-frequency 3400Hz"
},
{
"code": null,
"e": 26250,
"s": 26191,
"text": "We will plot the magnitude & phase response of the filter."
},
{
"code": null,
"e": 26273,
"s": 26250,
"text": "Step-by-step Approach:"
},
{
"code": null,
"e": 26320,
"s": 26273,
"text": "Step 1: Importing all the necessary libraries."
},
{
"code": null,
"e": 26328,
"s": 26320,
"text": "Python3"
},
{
"code": "\n\n\n\n\n\n\n# import required library\nimport numpy as np\nimport scipy.signal as signal\nimport matplotlib.pyplot as plt\n\n\n\n\n\n",
"e": 26458,
"s": 26338,
"text": null
},
{
"code": null,
"e": 26528,
"s": 26458,
"text": "Step 2: Define variables with the given specifications of the filter."
},
{
"code": null,
"e": 26536,
"s": 26528,
"text": "Python3"
},
{
"code": "\n\n\n\n\n\n\n# Given specification\nN = 2 # Order of the filter\nFs = 8000 # Sampling frequency in Hz\nfc = 3400 # Cut-off frequency in Hz\n \n# Compute Design Sampling parameter\nTd = 1/Fs\n\n\n\n\n\n",
"e": 26733,
"s": 26546,
"text": null
},
{
"code": null,
"e": 26773,
"s": 26733,
"text": "Step 3: Computing the cut-off frequency"
},
{
"code": null,
"e": 26781,
"s": 26773,
"text": "Python3"
},
{
"code": "\n\n\n\n\n\n\n# Compute cut-off frequency in radian/sec\nwd = 2*np.pi*fc\nprint(wd) # Cut-off frequency in radian/sec\n\n\n\n\n\n",
"e": 26907,
"s": 26791,
"text": null
},
{
"code": null,
"e": 26915,
"s": 26907,
"text": "Output:"
},
{
"code": null,
"e": 26957,
"s": 26915,
"text": "Step 4: Pre-wrapping the analog frequency"
},
{
"code": null,
"e": 26965,
"s": 26957,
"text": "Python3"
},
{
"code": "\n\n\n\n\n\n\n# Prewarp the analog frequency\n \nwc = (2/Td)*np.tan(wd*Td/2)\nprint('Order of the filter=', N) # Order\n \n# Prewarped analog cut-off frequency\nprint('Cut-off frequency (in rad/s)=', wc)\n\n\n\n\n\n",
"e": 27173,
"s": 26975,
"text": null
},
{
"code": null,
"e": 27181,
"s": 27173,
"text": "Output:"
},
{
"code": null,
"e": 27318,
"s": 27181,
"text": "Step 5: Designing the filter using signal.butter() function and then performing bilinear transformation using signal.bilinear() function"
},
{
"code": null,
"e": 27326,
"s": 27318,
"text": "Python3"
},
{
"code": "\n\n\n\n\n\n\n# Design analog Butterworth filter using signal.butter function\n \nb, a = signal.butter(N, wc, 'low', analog='True')\n# Perform bilinear Transformation\n \nz, p = signal.bilinear(b, a, fs=Fs)\n \n# Print numerator and denomerator coefficients of the filter\nprint('Numerator Coefficients:', z)\nprint('Denominator Coefficients:', p)\n\n\n\n\n\n",
"e": 27674,
"s": 27336,
"text": null
},
{
"code": null,
"e": 27682,
"s": 27674,
"text": "Output:"
},
{
"code": null,
"e": 27813,
"s": 27682,
"text": "Step 6: Computing the frequency response of the filter using signal.freqz() function and plotting the magnitude and phase response"
},
{
"code": null,
"e": 27821,
"s": 27813,
"text": "Python3"
},
{
"code": "\n\n\n\n\n\n\n# Compute frequency response of the filter using signal.freqz function\nwz, hz = signal.freqz(z, p, 512)\n \n# Plot filter magnitude and phase responses using subplot.\n# Convert digital frequency wz into analog frequency in Hz\nfig = plt.figure(figsize=(12, 10))\n \n# Calculate Magnitude from hz in dB\nMag = 20*np.log10(abs(hz))\n \n# Calculate frequency in Hz from wz\nFreq = wz*Fs/(2*np.pi)\n \n# Plot Magnitude response\nsub1 = plt.subplot(2, 1, 1)\nsub1.plot(Freq, Mag, 'r', linewidth=2)\nsub1.axis([1, Fs/2, -60, 5])\nsub1.set_title('Magnitude Response', fontsize=15)\nsub1.set_xlabel('Frequency [Hz]', fontsize=15)\nsub1.set_ylabel('Magnitude [dB]', fontsize=15)\nsub1.grid()\n \n \n# Plot phase angle\nsub2 = plt.subplot(2, 1, 2)\n \n# Calculate phase angle in degree from hz\nPhase = np.unwrap(np.angle(hz))*180/np.pi\nsub2.plot(Freq, Phase, 'g', linewidth=2)\nsub2.set_ylabel('Phase (degree)', fontsize=15)\nsub2.set_xlabel(r'Frequency (Hz)', fontsize=15)\nsub2.set_title(r'Phase response', fontsize=15)\nsub2.grid()\n \nplt.subplots_adjust(hspace=0.5)\nfig.tight_layout()\nplt.show()\n\n\n\n\n\n",
"e": 28905,
"s": 27831,
"text": null
},
{
"code": null,
"e": 28913,
"s": 28905,
"text": "Output:"
},
{
"code": null,
"e": 28942,
"s": 28913,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 28950,
"s": 28942,
"text": "Python3"
},
{
"code": "\n\n\n\n\n\n\n# import required library\nimport numpy as np\nimport scipy.signal as signal\nimport matplotlib.pyplot as plt\n \n# Given specification\nN = 2 # Order of the filter\nFs = 8000 # Sampling frequency in Hz\nfc = 3400 # Cut-off frequency in Hz\n \n# Compute Design Sampling parameter\nTd = 1/Fs\n \n# Compute cut-off frequency in radian/sec\nwd = 2*np.pi*fc\nprint(wd) # Cut-off frequency in radian/sec\n \n# Prewarp the analog frequency\nwc = (2/Td)*np.tan(wd*Td/2)\nprint('Order of the filter=', N) # Order\n \n# Prewarped analog cut-off frequency\nprint('Cut-off frequency (in rad/s)=', wc)\n \n# Design analog Butterworth filter using signal.butter function\nb, a = signal.butter(N, wc, 'low', analog='True')\n \n# Perform bilinear Transformation\nz, p = signal.bilinear(b, a, fs=Fs)\n \n# Print numerator and denomerator coefficients of the filter\nprint('Numerator Coefficients:', z)\nprint('Denominator Coefficients:', p)\n \n# Compute frequency response of the filter using signal.freqz function\nwz, hz = signal.freqz(z, p, 512)\n \n# Plot filter magnitude and phase responses using subplot.\n#Convert digital frequency wz into analog frequency in Hz\nfig = plt.figure(figsize=(10, 8))\n \n# Calculate Magnitude from hz in dB\nMag = 20*np.log10(abs(hz))\n \n# Calculate frequency in Hz from wz\nFreq = wz*Fs/(2*np.pi)\n \n# Plot Magnitude response\nsub1 = plt.subplot(2, 1, 1)\nsub1.plot(Freq, Mag, 'r', linewidth=2)\nsub1.axis([1, Fs/2, -60, 5])\nsub1.set_title('Magnitude Response', fontsize=15)\nsub1.set_xlabel('Frequency [Hz]', fontsize=15)\nsub1.set_ylabel('Magnitude [dB]', fontsize=15)\nsub1.grid()\n \n# Plot phase angle\nsub2 = plt.subplot(2, 1, 2)\n \n# Calculate phase angle in degree from hz\nPhase = np.unwrap(np.angle(hz))*180/np.pi\nsub2.plot(Freq, Phase, 'g', linewidth=2)\nsub2.set_ylabel('Phase (degree)', fontsize=15)\nsub2.set_xlabel(r'Frequency (Hz)', fontsize=15)\nsub2.set_title(r'Phase response', fontsize=15)\nsub2.grid()\n \nplt.subplots_adjust(hspace=0.5)\nfig.tight_layout()\nplt.show()\n\n\n\n\n\n",
"e": 30930,
"s": 28960,
"text": null
},
{
"code": null,
"e": 30938,
"s": 30930,
"text": "Output:"
},
{
"code": null,
"e": 30956,
"s": 30938,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 30977,
"s": 30956,
"text": "\nData Visualization\n"
},
{
"code": null,
"e": 30992,
"s": 30977,
"text": "\nPython-scipy\n"
},
{
"code": null,
"e": 31001,
"s": 30992,
"text": "\nPython\n"
},
{
"code": null,
"e": 31206,
"s": 31001,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 31238,
"s": 31206,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 31280,
"s": 31238,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 31322,
"s": 31280,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 31378,
"s": 31322,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 31405,
"s": 31378,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 31436,
"s": 31405,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 31472,
"s": 31436,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 31501,
"s": 31472,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 31523,
"s": 31501,
"text": "Defaultdict in Python"
}
] |
Tryit Editor v3.7
|
Tryit: HTML button as link
|
[] |
Unusual behaviour with character pointers - GeeksforGeeks
|
03 Nov, 2020
In C++, cout shows different printing behaviour with character pointers/arrays unlike pointers/arrays of other data types. So this article will firstly explain how cout behaves differently with character pointers, and then the reason and the working mechanism behind it will be discussed.
Example 1:
C++
// C++ program to illustrate difference// between behaviour of integer pointer// and character pointer#include <iostream>using namespace std; // Driver Codeint main(){ // Integer array int a[] = { 1, 2, 3 }; // Character array char ch[] = "abc"; // Print the value of a and b cout << a << endl; cout << ch << endl; return 0;}
0x7ffc623e56c0
abc
Explanation:From the above code, it is clear that:
When using the integer pointer to an array, cout prints the base address of that integer array.
But when the character pointer is used, cout prints the complete array of characters (till it encounters a null character) instead of printing the base address of the character array.
Example 2:
C++
// C++ program to illustrate behaviour// of character pointer pointing to// character array#include <iostream>using namespace std; // Driver Codeint main(){ // Character array b char b[] = "abc"; // Pointer to character array char* c = &b[0]; // Print the value of c cout << c << endl;}
abc
Explanation:In this example as well, the character type pointer c is storing the base address of the char array b[] and hence when used with cout, it starts printing each and every character from that base address till it encounters a NULL character.
Example 3:
C++
// C++ program to illustrate difference// between behaviour of character and// character pointer#include <iostream>using namespace std; // Drive Codeint main(){ char c = '$'; char* p = &c; cout << c << endl; cout << p << endl;}
abc
a
a
Output:
Explanation:In the above example, c is a simple character variable and it prints the value stored in it as expected. p being a character pointer when used with cout, results in the printing of each and every character till a null character is encountered. Thus, some garbage value is being printed after ‘$’. This simply means that in the memory the null character was placed after the ‘a’ character (since in this case, there is no automatic storing of a null character after the useful piece of data is finished unlike character arrays) and so it stops printing and gives the obtained output.
The reason for this lies in the concept of Operator Overloading. ‘<<‘ operator is overloaded for different types of inputs. In the case of const void* overload, it prints just the address. But for const char* overload, it starts printing each and every character till it encounters a null character (treating the input as C — style string).
Example 4:
C++
// C++ program to illustrate// printing of character array#include <iostream>using namespace std; // Driver Codeint main(){ // Character array char c[] = "abc"; // print value of c, c[0] and *c cout << c << endl; cout << c[0] << endl; cout << *c << endl;}
abc
a
a
Explanation:In the above example:
Only ‘c’ with cout is treated as const char * and << operator overload for such input is called and thus every character is printed until null character.
When using c[0], i.e., *(c + 0), it simply dereferences the particular memory location and prints the value stored at that location only.
Similarly, for *c which is same as *(c + 0).
NOTE: The unusual behaviour can be rectified if the output is type casted into something which will not be treated as C-style string.Example 5:
C++
// C++ program to illustrate behaviour// of typecasted character pointer#include <iostream>using namespace std; // Driver Codeint main(){ char c[] = { "abc" }; char* b = c; cout << (void*)b;}
0x7ffe66f7f420
Explanation:In the above example, the base address of the character array is obtained in the output.
Given a string, print the pattern as shown in the following example:
C++
// C++ program to illustrate the// utilization of unusual behaviour// of character pointer#include <iostream>using namespace std; // Function that prints the patternvoid printPattern(char* ch){ // Base Condition if (*ch == '\0') return; // Recursion function call after // excluding the current character printPattern(ch + 1); // Print the whole string starting // from base address stored in 'ch' cout << ch << endl;} // Driver Codeint main(){ char ch[] = { "abcd" }; // Function Call printPattern(ch); return 0;}
d
cd
bcd
abcd
C Basics
C-Pointer Basics
C-Pointers
Pointers
C++
Pointers
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Operator Overloading in C++
Sorting a vector in C++
Friend class and function in C++
Polymorphism in C++
List in C++ Standard Template Library (STL)
Convert string to char array in C++
Destructors in C++
new and delete operators in C++ for dynamic memory
Pair in C++ Standard Template Library (STL)
Queue in C++ Standard Template Library (STL)
|
[
{
"code": null,
"e": 23733,
"s": 23705,
"text": "\n03 Nov, 2020"
},
{
"code": null,
"e": 24022,
"s": 23733,
"text": "In C++, cout shows different printing behaviour with character pointers/arrays unlike pointers/arrays of other data types. So this article will firstly explain how cout behaves differently with character pointers, and then the reason and the working mechanism behind it will be discussed."
},
{
"code": null,
"e": 24033,
"s": 24022,
"text": "Example 1:"
},
{
"code": null,
"e": 24037,
"s": 24033,
"text": "C++"
},
{
"code": "// C++ program to illustrate difference// between behaviour of integer pointer// and character pointer#include <iostream>using namespace std; // Driver Codeint main(){ // Integer array int a[] = { 1, 2, 3 }; // Character array char ch[] = \"abc\"; // Print the value of a and b cout << a << endl; cout << ch << endl; return 0;}",
"e": 24394,
"s": 24037,
"text": null
},
{
"code": null,
"e": 24414,
"s": 24394,
"text": "0x7ffc623e56c0\nabc\n"
},
{
"code": null,
"e": 24465,
"s": 24414,
"text": "Explanation:From the above code, it is clear that:"
},
{
"code": null,
"e": 24561,
"s": 24465,
"text": "When using the integer pointer to an array, cout prints the base address of that integer array."
},
{
"code": null,
"e": 24745,
"s": 24561,
"text": "But when the character pointer is used, cout prints the complete array of characters (till it encounters a null character) instead of printing the base address of the character array."
},
{
"code": null,
"e": 24756,
"s": 24745,
"text": "Example 2:"
},
{
"code": null,
"e": 24760,
"s": 24756,
"text": "C++"
},
{
"code": "// C++ program to illustrate behaviour// of character pointer pointing to// character array#include <iostream>using namespace std; // Driver Codeint main(){ // Character array b char b[] = \"abc\"; // Pointer to character array char* c = &b[0]; // Print the value of c cout << c << endl;}",
"e": 25070,
"s": 24760,
"text": null
},
{
"code": null,
"e": 25075,
"s": 25070,
"text": "abc\n"
},
{
"code": null,
"e": 25326,
"s": 25075,
"text": "Explanation:In this example as well, the character type pointer c is storing the base address of the char array b[] and hence when used with cout, it starts printing each and every character from that base address till it encounters a NULL character."
},
{
"code": null,
"e": 25337,
"s": 25326,
"text": "Example 3:"
},
{
"code": null,
"e": 25341,
"s": 25337,
"text": "C++"
},
{
"code": "// C++ program to illustrate difference// between behaviour of character and// character pointer#include <iostream>using namespace std; // Drive Codeint main(){ char c = '$'; char* p = &c; cout << c << endl; cout << p << endl;}",
"e": 25584,
"s": 25341,
"text": null
},
{
"code": null,
"e": 25593,
"s": 25584,
"text": "abc\na\na\n"
},
{
"code": null,
"e": 25601,
"s": 25593,
"text": "Output:"
},
{
"code": null,
"e": 26196,
"s": 25601,
"text": "Explanation:In the above example, c is a simple character variable and it prints the value stored in it as expected. p being a character pointer when used with cout, results in the printing of each and every character till a null character is encountered. Thus, some garbage value is being printed after ‘$’. This simply means that in the memory the null character was placed after the ‘a’ character (since in this case, there is no automatic storing of a null character after the useful piece of data is finished unlike character arrays) and so it stops printing and gives the obtained output."
},
{
"code": null,
"e": 26537,
"s": 26196,
"text": "The reason for this lies in the concept of Operator Overloading. ‘<<‘ operator is overloaded for different types of inputs. In the case of const void* overload, it prints just the address. But for const char* overload, it starts printing each and every character till it encounters a null character (treating the input as C — style string)."
},
{
"code": null,
"e": 26549,
"s": 26537,
"text": "Example 4: "
},
{
"code": null,
"e": 26553,
"s": 26549,
"text": "C++"
},
{
"code": "// C++ program to illustrate// printing of character array#include <iostream>using namespace std; // Driver Codeint main(){ // Character array char c[] = \"abc\"; // print value of c, c[0] and *c cout << c << endl; cout << c[0] << endl; cout << *c << endl;}",
"e": 26830,
"s": 26553,
"text": null
},
{
"code": null,
"e": 26839,
"s": 26830,
"text": "abc\na\na\n"
},
{
"code": null,
"e": 26873,
"s": 26839,
"text": "Explanation:In the above example:"
},
{
"code": null,
"e": 27027,
"s": 26873,
"text": "Only ‘c’ with cout is treated as const char * and << operator overload for such input is called and thus every character is printed until null character."
},
{
"code": null,
"e": 27165,
"s": 27027,
"text": "When using c[0], i.e., *(c + 0), it simply dereferences the particular memory location and prints the value stored at that location only."
},
{
"code": null,
"e": 27210,
"s": 27165,
"text": "Similarly, for *c which is same as *(c + 0)."
},
{
"code": null,
"e": 27354,
"s": 27210,
"text": "NOTE: The unusual behaviour can be rectified if the output is type casted into something which will not be treated as C-style string.Example 5:"
},
{
"code": null,
"e": 27358,
"s": 27354,
"text": "C++"
},
{
"code": "// C++ program to illustrate behaviour// of typecasted character pointer#include <iostream>using namespace std; // Driver Codeint main(){ char c[] = { \"abc\" }; char* b = c; cout << (void*)b;}",
"e": 27560,
"s": 27358,
"text": null
},
{
"code": null,
"e": 27576,
"s": 27560,
"text": "0x7ffe66f7f420\n"
},
{
"code": null,
"e": 27677,
"s": 27576,
"text": "Explanation:In the above example, the base address of the character array is obtained in the output."
},
{
"code": null,
"e": 27746,
"s": 27677,
"text": "Given a string, print the pattern as shown in the following example:"
},
{
"code": null,
"e": 27750,
"s": 27746,
"text": "C++"
},
{
"code": "// C++ program to illustrate the// utilization of unusual behaviour// of character pointer#include <iostream>using namespace std; // Function that prints the patternvoid printPattern(char* ch){ // Base Condition if (*ch == '\\0') return; // Recursion function call after // excluding the current character printPattern(ch + 1); // Print the whole string starting // from base address stored in 'ch' cout << ch << endl;} // Driver Codeint main(){ char ch[] = { \"abcd\" }; // Function Call printPattern(ch); return 0;}",
"e": 28318,
"s": 27750,
"text": null
},
{
"code": null,
"e": 28333,
"s": 28318,
"text": "d\ncd\nbcd\nabcd\n"
},
{
"code": null,
"e": 28342,
"s": 28333,
"text": "C Basics"
},
{
"code": null,
"e": 28359,
"s": 28342,
"text": "C-Pointer Basics"
},
{
"code": null,
"e": 28370,
"s": 28359,
"text": "C-Pointers"
},
{
"code": null,
"e": 28379,
"s": 28370,
"text": "Pointers"
},
{
"code": null,
"e": 28383,
"s": 28379,
"text": "C++"
},
{
"code": null,
"e": 28392,
"s": 28383,
"text": "Pointers"
},
{
"code": null,
"e": 28396,
"s": 28392,
"text": "CPP"
},
{
"code": null,
"e": 28494,
"s": 28396,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28503,
"s": 28494,
"text": "Comments"
},
{
"code": null,
"e": 28516,
"s": 28503,
"text": "Old Comments"
},
{
"code": null,
"e": 28544,
"s": 28516,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 28568,
"s": 28544,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 28601,
"s": 28568,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 28621,
"s": 28601,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 28665,
"s": 28621,
"text": "List in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 28701,
"s": 28665,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 28720,
"s": 28701,
"text": "Destructors in C++"
},
{
"code": null,
"e": 28771,
"s": 28720,
"text": "new and delete operators in C++ for dynamic memory"
},
{
"code": null,
"e": 28815,
"s": 28771,
"text": "Pair in C++ Standard Template Library (STL)"
}
] |
How to select multiple options in a dropdown list with JavaScript?
|
To select multiple options in a drop-down list, use the multiple properties. It allows you to select more than one option while pressing CTRL key.
You can try to run the following code to learn how to select more than one options at once in a dropdownlist.
Live Demo
<!DOCTYPE html>
<html>
<body>
<form id="myForm">
<select id="mySelect">
<option>One</option>
<option>Two</option>
<option>Three</option>
</select>
<input type="button" onclick="multipleFunc()" value="Select multiple options">
</form>
<p>Press CTRL and click above button to select multiple options at once.</p>
<script>
function multipleFunc() {
document.getElementById("mySelect").multiple = true;
}
</script>
</body>
</html>
|
[
{
"code": null,
"e": 1209,
"s": 1062,
"text": "To select multiple options in a drop-down list, use the multiple properties. It allows you to select more than one option while pressing CTRL key."
},
{
"code": null,
"e": 1319,
"s": 1209,
"text": "You can try to run the following code to learn how to select more than one options at once in a dropdownlist."
},
{
"code": null,
"e": 1329,
"s": 1319,
"text": "Live Demo"
},
{
"code": null,
"e": 1885,
"s": 1329,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <form id=\"myForm\">\n <select id=\"mySelect\">\n <option>One</option>\n <option>Two</option>\n <option>Three</option>\n </select>\n <input type=\"button\" onclick=\"multipleFunc()\" value=\"Select multiple options\">\n </form>\n <p>Press CTRL and click above button to select multiple options at once.</p>\n <script>\n function multipleFunc() {\n document.getElementById(\"mySelect\").multiple = true;\n }\n </script>\n </body>\n</html>"
}
] |
Better Heatmaps and Correlation Matrix Plots in Python | by Drazen Zaric | Towards Data Science
|
[Update 2020–04–12: The code described below is now available as a pip package — https://pypi.org/project/heatmapz/. There’s also a Google Colab notebook here, you can see a few examples in there and play around with the lib]
You already know that if you have a data set with many columns, a good way to quickly check correlations among columns is by visualizing the correlation matrix as a heatmap.
But is a simple heatmap the best way to do it?
For illustration, I’ll use the Automobile Data Set, containing various characteristics of a number of cars. You can also find a clean version of the data with header columns here.
Let’s start by making a correlation matrix heatmap for the data set.
Great! Green means positive, red means negative. The stronger the color, the larger the correlation magnitude. Now looking at the chart above, think about the following questions:
Where do your eyes jump first when you look at the chart?
What’s the strongest and what’s the weakest correlated pair (except the main diagonal)?
What are the three variables most correlated with price?
If you’re like most people, you’ll find it hard to map the color scale to numbers and vice versa.
Distinguishing positive from negative is easy, as well as 0 from 1. But what about the second question? Finding the highest negative and positive correlations mean finding the strongest red and green. To do that I need to carefully scan the entire grid. Try to answer it again and notice how your eyes are jumping around the plot, and sometimes going to the legend.
Now consider the following plot:
In addition to color, we’ve added size as a parameter to our heatmap. The size of each square corresponds to the magnitude of the correlation it represents, that is
size(c1, c2) ~ abs(corr(c1, c2))
Now try to answer the questions using the latter plot. Notice how weak correlations visually disappear, and your eyes are immediately drawn to areas where there’s high correlation. Also note that it’s now easier to compare magnitudes of negative vs positive values (lighter red vs lighter green), and we can also compare values that are further apart.
If we’re mapping magnitudes, it’s much more natural to link them to the size of the representing object than to its color. That’s exactly why on bar charts you would use height to display measures, and colors to display categories, but not vice versa.
Let’s see how the cars in our data set are distributed according to horsepower and drivetrain layout. That is, we want to visualize the following table
Consider the following two ways to do it
The second version, where we use square size to display counts makes it effortless to determine which group is the largest/smallest. It also gives some intuition about the marginal distributions, all without needing to refer to a color legend.
To make a regular heatmap, we simply used the Seaborn heatmap function, with a bit of additional styling.
For the second kind, there’s no trivial way to make it using Matplotlib or Seaborn. We could use corrplot from biokit, but it helps with correlations only and isn’t very useful for two-dimensional distributions.
Building a robust parametrized function that enables us to make heatmaps with sized markers is a nice exercise in Matplotlib, so I’ll show you how to do it step by step.
We’ll start by using a simple scatter plot with squares as markers. Then we’ll fix some issues with it, add color and size as parameters, make it more general and robust to various types of input, and finally make a wrapper function corrplot that takes a result of DataFrame.corr method and plots a correlation matrix, supplying all the necessary parameters to the more general heatmap function.
If we want to plot elements on a grid made by two categorical axes, we can use a scatter plot.
Looks like we’re onto something. But I said it’s just a scatterplot, and there’s quite a lot happening in the previous code snippet.
Since the scatterplot requires x and y to be numeric arrays, we need to map our column names to numbers. And since we want our axis ticks to show column names instead of those numbers, we need to set custom ticks and ticklabels. Finally there’s code that loads the dataset, selects a subset of columns, calculates all the correlations, melts the data frame (the inverse of creating a pivot table) and feeds its columns to our heatmap function.
You noticed that our squares are placed where our gridlines intersect, instead of being centered in their cells. In order to move the squares to cell centers, we’ll actually move the grid. And to move the grid, we’ll actually turn off major gridlines, and set minor gridlines to go right in between our axis ticks.
That’s better. But now the left and bottom side look cropped. That’s because our axis lower limit are set to 0. We’ll sort this out by setting the lower limit for both axes to — 0.5. Remember, our points are displayed at integer coordinates, so our gridlines are at .5 coordinates.
Now comes the fun part. We need to map the possible range of values for correlation coefficients, [-1, 1], to a color palette. We’ll use a diverging palette, going from red for -1, all the way to green for 1. Looking at Seaborn color palettes, seems that we’ll do just fine with something like
sns.palplot(sns.diverging_palette(220, 20, n=7))
But lets first flip the order of colors and make it smoother by adding more steps between red and green:
palette = sns.diverging_palette(20, 220, n=256)
Seaborn color palettes are just arrays of color components, so in order to map a correlation value to the appropriate color, we need to ultimately map it to an index in the palette array. It’s a simple mapping of one interval to another: [-1, 1] → [0, 1] → (0, 255). More precisely, here’s the sequence of steps this mapping will take:
Just what we wanted. Let’s now add a color bar on the right side of the chart. We’ll use GridSpec to set up a plot grid with 1 row and n columns. Then we’ll use the rightmost column of the plot to display the color bar and the rest to display the heatmap.
There are multiple ways to display a color bar, here we’ll trick our eyes by using a really dense bar chart. We’ll draw n_colors horizontal bars, each colored with its respective color from the palette.
And we have our color bar.
We’re almost done. Now we should just flip the vertical axis so that we get correlation of each variable with itself shown on the main diagonal, make squares a bit larger and make the background a just a tad lighter so that values around 0 are more visible.
But let’s first make the entire code more useful.
It would be great if we made our function able to accept more than just a correlation matrix. To do this we’ll make the following changes:
Be able to pass color_min, color_max and size_min, size_max as parameters so that we can map different ranges than [-1, 1] to color and size. This will enable us to use the heatmap beyond correlations
Use a sequential palette if no palette specified, use a single color if no color vector provided
Use a constant size if no size vector provided. Avoid mapping the lowest value to 0 size.
Make x and y the only necessary parameters, and pass size, color, size_scale, size_range, color_range, palette, marker as kwargs. Provide sensible defaults for each of the parameters
Use list comprehensions instead pandas apply and map methods, so we can pass any kind of arrays as x, y, color, size instead of just pandas.Series
Pass any other kwargs to pyplot.scatterplot function
Make a wrapper function corrplot that accepts a corr() dataframe, melts it, calls heatmap with a red-green diverging color palette, and size/color min-max set to [-1, 1]
That’s quite a lot of boilerplate stuff to cover step by step, so here’s what it looks like when done. You can also check it out in this Kaggle kernel.
Now that we have our corrplot and heatmap functions, in order to create the correlation plot with sized squares, like the one at the beginning of this post, we simply do the following:
And just for fun, let’s make a plot showing how engine power is distributed among car brands in our data set:
That concludes the story on this simple idea for improving heatmap visualizations.
Curious for more?
Have a comment or question? I tweet about data science and building software products at @drazenxyz, so follow me and see you there.
I also summarize lessons from the industry on Blogboard Journal, where you can find articles such as Data Science for Marketing Optimization — Case Studies from Airbnb, Lyft, Doordash:
|
[
{
"code": null,
"e": 398,
"s": 172,
"text": "[Update 2020–04–12: The code described below is now available as a pip package — https://pypi.org/project/heatmapz/. There’s also a Google Colab notebook here, you can see a few examples in there and play around with the lib]"
},
{
"code": null,
"e": 572,
"s": 398,
"text": "You already know that if you have a data set with many columns, a good way to quickly check correlations among columns is by visualizing the correlation matrix as a heatmap."
},
{
"code": null,
"e": 619,
"s": 572,
"text": "But is a simple heatmap the best way to do it?"
},
{
"code": null,
"e": 799,
"s": 619,
"text": "For illustration, I’ll use the Automobile Data Set, containing various characteristics of a number of cars. You can also find a clean version of the data with header columns here."
},
{
"code": null,
"e": 868,
"s": 799,
"text": "Let’s start by making a correlation matrix heatmap for the data set."
},
{
"code": null,
"e": 1048,
"s": 868,
"text": "Great! Green means positive, red means negative. The stronger the color, the larger the correlation magnitude. Now looking at the chart above, think about the following questions:"
},
{
"code": null,
"e": 1106,
"s": 1048,
"text": "Where do your eyes jump first when you look at the chart?"
},
{
"code": null,
"e": 1194,
"s": 1106,
"text": "What’s the strongest and what’s the weakest correlated pair (except the main diagonal)?"
},
{
"code": null,
"e": 1251,
"s": 1194,
"text": "What are the three variables most correlated with price?"
},
{
"code": null,
"e": 1349,
"s": 1251,
"text": "If you’re like most people, you’ll find it hard to map the color scale to numbers and vice versa."
},
{
"code": null,
"e": 1715,
"s": 1349,
"text": "Distinguishing positive from negative is easy, as well as 0 from 1. But what about the second question? Finding the highest negative and positive correlations mean finding the strongest red and green. To do that I need to carefully scan the entire grid. Try to answer it again and notice how your eyes are jumping around the plot, and sometimes going to the legend."
},
{
"code": null,
"e": 1748,
"s": 1715,
"text": "Now consider the following plot:"
},
{
"code": null,
"e": 1913,
"s": 1748,
"text": "In addition to color, we’ve added size as a parameter to our heatmap. The size of each square corresponds to the magnitude of the correlation it represents, that is"
},
{
"code": null,
"e": 1946,
"s": 1913,
"text": "size(c1, c2) ~ abs(corr(c1, c2))"
},
{
"code": null,
"e": 2298,
"s": 1946,
"text": "Now try to answer the questions using the latter plot. Notice how weak correlations visually disappear, and your eyes are immediately drawn to areas where there’s high correlation. Also note that it’s now easier to compare magnitudes of negative vs positive values (lighter red vs lighter green), and we can also compare values that are further apart."
},
{
"code": null,
"e": 2550,
"s": 2298,
"text": "If we’re mapping magnitudes, it’s much more natural to link them to the size of the representing object than to its color. That’s exactly why on bar charts you would use height to display measures, and colors to display categories, but not vice versa."
},
{
"code": null,
"e": 2702,
"s": 2550,
"text": "Let’s see how the cars in our data set are distributed according to horsepower and drivetrain layout. That is, we want to visualize the following table"
},
{
"code": null,
"e": 2743,
"s": 2702,
"text": "Consider the following two ways to do it"
},
{
"code": null,
"e": 2987,
"s": 2743,
"text": "The second version, where we use square size to display counts makes it effortless to determine which group is the largest/smallest. It also gives some intuition about the marginal distributions, all without needing to refer to a color legend."
},
{
"code": null,
"e": 3093,
"s": 2987,
"text": "To make a regular heatmap, we simply used the Seaborn heatmap function, with a bit of additional styling."
},
{
"code": null,
"e": 3305,
"s": 3093,
"text": "For the second kind, there’s no trivial way to make it using Matplotlib or Seaborn. We could use corrplot from biokit, but it helps with correlations only and isn’t very useful for two-dimensional distributions."
},
{
"code": null,
"e": 3475,
"s": 3305,
"text": "Building a robust parametrized function that enables us to make heatmaps with sized markers is a nice exercise in Matplotlib, so I’ll show you how to do it step by step."
},
{
"code": null,
"e": 3871,
"s": 3475,
"text": "We’ll start by using a simple scatter plot with squares as markers. Then we’ll fix some issues with it, add color and size as parameters, make it more general and robust to various types of input, and finally make a wrapper function corrplot that takes a result of DataFrame.corr method and plots a correlation matrix, supplying all the necessary parameters to the more general heatmap function."
},
{
"code": null,
"e": 3966,
"s": 3871,
"text": "If we want to plot elements on a grid made by two categorical axes, we can use a scatter plot."
},
{
"code": null,
"e": 4099,
"s": 3966,
"text": "Looks like we’re onto something. But I said it’s just a scatterplot, and there’s quite a lot happening in the previous code snippet."
},
{
"code": null,
"e": 4543,
"s": 4099,
"text": "Since the scatterplot requires x and y to be numeric arrays, we need to map our column names to numbers. And since we want our axis ticks to show column names instead of those numbers, we need to set custom ticks and ticklabels. Finally there’s code that loads the dataset, selects a subset of columns, calculates all the correlations, melts the data frame (the inverse of creating a pivot table) and feeds its columns to our heatmap function."
},
{
"code": null,
"e": 4858,
"s": 4543,
"text": "You noticed that our squares are placed where our gridlines intersect, instead of being centered in their cells. In order to move the squares to cell centers, we’ll actually move the grid. And to move the grid, we’ll actually turn off major gridlines, and set minor gridlines to go right in between our axis ticks."
},
{
"code": null,
"e": 5140,
"s": 4858,
"text": "That’s better. But now the left and bottom side look cropped. That’s because our axis lower limit are set to 0. We’ll sort this out by setting the lower limit for both axes to — 0.5. Remember, our points are displayed at integer coordinates, so our gridlines are at .5 coordinates."
},
{
"code": null,
"e": 5434,
"s": 5140,
"text": "Now comes the fun part. We need to map the possible range of values for correlation coefficients, [-1, 1], to a color palette. We’ll use a diverging palette, going from red for -1, all the way to green for 1. Looking at Seaborn color palettes, seems that we’ll do just fine with something like"
},
{
"code": null,
"e": 5483,
"s": 5434,
"text": "sns.palplot(sns.diverging_palette(220, 20, n=7))"
},
{
"code": null,
"e": 5588,
"s": 5483,
"text": "But lets first flip the order of colors and make it smoother by adding more steps between red and green:"
},
{
"code": null,
"e": 5636,
"s": 5588,
"text": "palette = sns.diverging_palette(20, 220, n=256)"
},
{
"code": null,
"e": 5972,
"s": 5636,
"text": "Seaborn color palettes are just arrays of color components, so in order to map a correlation value to the appropriate color, we need to ultimately map it to an index in the palette array. It’s a simple mapping of one interval to another: [-1, 1] → [0, 1] → (0, 255). More precisely, here’s the sequence of steps this mapping will take:"
},
{
"code": null,
"e": 6228,
"s": 5972,
"text": "Just what we wanted. Let’s now add a color bar on the right side of the chart. We’ll use GridSpec to set up a plot grid with 1 row and n columns. Then we’ll use the rightmost column of the plot to display the color bar and the rest to display the heatmap."
},
{
"code": null,
"e": 6431,
"s": 6228,
"text": "There are multiple ways to display a color bar, here we’ll trick our eyes by using a really dense bar chart. We’ll draw n_colors horizontal bars, each colored with its respective color from the palette."
},
{
"code": null,
"e": 6458,
"s": 6431,
"text": "And we have our color bar."
},
{
"code": null,
"e": 6716,
"s": 6458,
"text": "We’re almost done. Now we should just flip the vertical axis so that we get correlation of each variable with itself shown on the main diagonal, make squares a bit larger and make the background a just a tad lighter so that values around 0 are more visible."
},
{
"code": null,
"e": 6766,
"s": 6716,
"text": "But let’s first make the entire code more useful."
},
{
"code": null,
"e": 6905,
"s": 6766,
"text": "It would be great if we made our function able to accept more than just a correlation matrix. To do this we’ll make the following changes:"
},
{
"code": null,
"e": 7106,
"s": 6905,
"text": "Be able to pass color_min, color_max and size_min, size_max as parameters so that we can map different ranges than [-1, 1] to color and size. This will enable us to use the heatmap beyond correlations"
},
{
"code": null,
"e": 7203,
"s": 7106,
"text": "Use a sequential palette if no palette specified, use a single color if no color vector provided"
},
{
"code": null,
"e": 7293,
"s": 7203,
"text": "Use a constant size if no size vector provided. Avoid mapping the lowest value to 0 size."
},
{
"code": null,
"e": 7476,
"s": 7293,
"text": "Make x and y the only necessary parameters, and pass size, color, size_scale, size_range, color_range, palette, marker as kwargs. Provide sensible defaults for each of the parameters"
},
{
"code": null,
"e": 7623,
"s": 7476,
"text": "Use list comprehensions instead pandas apply and map methods, so we can pass any kind of arrays as x, y, color, size instead of just pandas.Series"
},
{
"code": null,
"e": 7676,
"s": 7623,
"text": "Pass any other kwargs to pyplot.scatterplot function"
},
{
"code": null,
"e": 7846,
"s": 7676,
"text": "Make a wrapper function corrplot that accepts a corr() dataframe, melts it, calls heatmap with a red-green diverging color palette, and size/color min-max set to [-1, 1]"
},
{
"code": null,
"e": 7998,
"s": 7846,
"text": "That’s quite a lot of boilerplate stuff to cover step by step, so here’s what it looks like when done. You can also check it out in this Kaggle kernel."
},
{
"code": null,
"e": 8183,
"s": 7998,
"text": "Now that we have our corrplot and heatmap functions, in order to create the correlation plot with sized squares, like the one at the beginning of this post, we simply do the following:"
},
{
"code": null,
"e": 8293,
"s": 8183,
"text": "And just for fun, let’s make a plot showing how engine power is distributed among car brands in our data set:"
},
{
"code": null,
"e": 8376,
"s": 8293,
"text": "That concludes the story on this simple idea for improving heatmap visualizations."
},
{
"code": null,
"e": 8394,
"s": 8376,
"text": "Curious for more?"
},
{
"code": null,
"e": 8527,
"s": 8394,
"text": "Have a comment or question? I tweet about data science and building software products at @drazenxyz, so follow me and see you there."
}
] |
Usage of Bootstrap navbar-btn class
|
Add buttons using class .navbar-btn to <button> elements not residing in a <form> to vertically center them in the navbar. .navbar-btn can be used on <a> and <input> elements.
You can try to run the following code to implement the navbar-btn class
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
<script src = "/scripts/jquery.min.js"></script>
<script src = "/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<nav class = "navbar navbar-default" role = "navigation" style="background: #85C1E9;">
<div class = "navbar-header">
<a class = "navbar-brand" href = "#">Search below:</a>
</div>
<div>
<form class = "navbar-form navbar-left" role = "search">
<div class = "form-group">
<input type = "text" class = "form-control" placeholder = "Search">
</div>
<button type = "submit" class = "btn btn-default">Submit Button</button>
</form>
<button type = "button" class = "btn btn-default navbar-btn">Navbar Button</button>
</div>
</nav>
</body>
</html>
|
[
{
"code": null,
"e": 1238,
"s": 1062,
"text": "Add buttons using class .navbar-btn to <button> elements not residing in a <form> to vertically center them in the navbar. .navbar-btn can be used on <a> and <input> elements."
},
{
"code": null,
"e": 1310,
"s": 1238,
"text": "You can try to run the following code to implement the navbar-btn class"
},
{
"code": null,
"e": 1320,
"s": 1310,
"text": "Live Demo"
},
{
"code": null,
"e": 2306,
"s": 1320,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <nav class = \"navbar navbar-default\" role = \"navigation\" style=\"background: #85C1E9;\">\n <div class = \"navbar-header\">\n <a class = \"navbar-brand\" href = \"#\">Search below:</a>\n </div>\n <div>\n <form class = \"navbar-form navbar-left\" role = \"search\">\n <div class = \"form-group\">\n <input type = \"text\" class = \"form-control\" placeholder = \"Search\">\n </div>\n <button type = \"submit\" class = \"btn btn-default\">Submit Button</button>\n </form>\n <button type = \"button\" class = \"btn btn-default navbar-btn\">Navbar Button</button>\n </div>\n </nav>\n </body>\n</html>"
}
] |
MongoEngine - Quick Guide
|
NoSQL databases have seen rise in popularity in the last decade. In today’s world of real time web applications, huge amount of data is being generated with mobile and embedded devices. Traditional relational databases (like Oracle, MySQL, etc.) are not suitable for strings. The processing of such data is also difficult as they have fixed and predefined schema, and are not scalable. NOSQL databases have flexible schema and are stored in distributed manner on a large number of community servers.
NOSQL databases are classified on the basis of organization of data. MongoDB is a popular Document Store NOSQL database. Fundamental constituent of a MongoDB database is called a document. A document is a collection of key-value pairs stored in JSON format. More than one documents are stored in a collection. A collection can be considered as analogous to a table in any relational database, and a Document as row in a table. However, it should be noted that since MongoDB is schema less, number of key-value pairs in each document of a Collection need not be the same.
MongoDB is developed by MongoDB Inc. It is a general-purpose, distributed document based database. It is available in enterprise as well as community edition. Latest version of Community version for Windows operating system can be downloaded from https://fastdl.mongodb.org/win32/mongodb-win32-x86_64-2012plus-4.2.6-signed.msi.
Install MongoDB in a folder of your choice and start the server with the following command−
D:\mongodb\bin>mongod
Server is now ready for incoming connection requests at port 27017. MongoDB databases are stored in bin/data directory. This location can be changed by –dbpath option in above command.
In another command terminal, start MongoDB console with the following command −
D:\mongodb\bin>mongo
MongoDB prompt is similar to what we normally see in MySQL or SQLite terminal. All database operations such as creating database, inserting a document, updating and deleting as well as retrieval of documents can be done from within the console.
E:\mongodb\bin>mongo
MongoDB shell version v4.0.6
connecting to: mongodb://127.0.0.1:27017/?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("0d848b11-acf7-4d30-83df-242d1d7fa693") }
MongoDB server version: 4.0.6
---
>
Default database in use is test.
> db
Test
With 'use' command any other database is set as current. If the named database does not exist, new one is created.
> use mydb
switched to db mydb
Please refer to our detailed tutorial on MongoDB at https://www.tutorialspoint.com/mongodb/index.htm.
MongoDB has also developed a GUI tool for handling MongoDB databases. It is called MongoDB Compass. It is a convenient tool for performing all CRUD operations without manually writing queries. It helps in many activities such as indexing, document validation, etc.
Download community edition of MongoDB Compass from https://www.mongodb.com/download-center/compass and start MongoDBCompassCommunity.exe (Ensure that MongoDB server is running before starting Compass). Connect to the local server by giving correct host and port number.
All the databases currently available will be listed as below −
Click on + button (shown at the bottom of left panel) to create new database.
Choose name of database from list and select a Collection as shown below −
You can add document directly or import from CSV or JSON file.
Choose Insert Document from Add data drop down.
Documents added will be displayed in JSON, list or tabular form −
Note that, just as a table in relational database has a primary key, document in MongoDB database has a special key called "_id" that is automatically generated.
MongoDB Inc. provides a Python driver for connection with MongoDB databases. It is called PyMongo whose usage is similar to standard SQL queries.
After installing PyMongo module, we need object of MongoClient class for interacting with MongoDB server.
<<< from pymongo import MongoClient
<<< client=MongoClient()
New database is created with the following statement −
db=client.mydatabase
CRUD operations on this database are performed with methods such as insert_one() (or insert_many()), find(), update() and delete() methods. Detailed discussion of PyMongo library is available at https://www.tutorialspoint.com/python_data_access/python_mongodb_introduction.htm.
However, Python’s user defined objects cannot be stored in database unless it is converted in MongoDB’s data types. This is where we need MongoEngine library.
MongoDB is a document based database. Each document is a JSON like representation of fields and values. A document in MongoDB is roughly equivalent to a row in RDBMS table (MongoDB equivalent of table is Collection). Even though MongoDB does not enforce any predefined schema, the field objects in a document have certain data type. MongoDB data types are very much similar to Python’s primary data types. If one has to store object of Python’s user defined class, its attributes have to be manually parsed to equivalent MongoDB data types.
MongoEngine provides a convenient abstraction layer over PyMongo and maps each object of Document class to a document in MongoDB database. MongoEngine API has been developed by Hary Marr in August 2013. Latest version of MongoEngine is 0.19.1.
MongoEngine is to MongoDB what SQLAlchemy is to RDBMS databases. MongoEngine library provides a Document class that is used as base for defining custom class. Attributes of this class form the fields of MongoDB document. The Document class defines methods to perform CRUD operations. In subsequent topics, we shall learn how to use them.
To use MongoEngine, you need to have already installed MongoDB and MongoDB server should be running as described earlier.
Easiest way to install MongoEngine is by using PIP installer.
pip install mongoengine
If your Python installation does not have Setuptools installed, you will have to download MongoEngine from https://github.com/MongoEngine/mongoengine and run the following command −
python setup.py install
MongoEngine has the following dependencies −
pymongo>=3.4
pymongo>=3.4
six>=1.10.0
six>=1.10.0
dateutil>=2.1.0
dateutil>=2.1.0
pillow>=2.0.0
pillow>=2.0.0
To verify the correct installation, run import command and check version as follows −
>>> import mongoengine
>>> mongoengine.__version__
'0.19.1'
As mentioned earlier, you should first start MongoDB server using mongod command.
MongoEngine provides connect() function to connect to a running instance of mongodb server.
from mongoengine import connect
connect(‘mydata.db’)
By default, MongoDB server is running on localhost and on port 27017. To customize, you should provide the host and port arguments to connect() −
connect('mydata.db', host='192.168.1.1', port=12345)
In case the database requires authentication, its credentials such as username, password and authentication_source arguments should be provided.
connect('mydata.db', username='user1', password='***', authentication_source='admin')
MongoEngine also supports URI style connections instead of IP address.
connect('mydata.db', host='mongodb://localhost/database_name')
The connect() function has another optional parameter called replicaset. MongoDB is a distributed database. Data stored in one server is usually replicated in many server instances in order to ensure high availability. A replica set in MongoDB is a group of mongod processes on which the same data set is maintained. Replica sets are the basis for all production deployments.
connect(host='mongodb://localhost/dbname?replicaSet=rs-name')
Following replica set methods are defined as follows:
MongoEngine also allows connection with multiple databases. You need to provide unique alias name for each database. For example, following code connects Python script to two MongoDB databases.
connect(alias='db1', db='db1.db')
connect(alias='db2', db='db2.db')
MongoEngine is termed as ODM (Object Document Mapper). MongoEngine defines a Document class. This is a base class whose inherited class is used to define structure and properties of collection of documents stored in MongoDB database. Each object of this subclass forms Document in Collection in database.
Attributes in this Document subclass are objects of various Field classes. Following is an example of a typical Document class −
from mongoengine import *
class Student(Document):
studentid = StringField(required=True)
name = StringField(max_length=50)
age = IntField()
def _init__(self, id, name, age):
self.studentid=id,
self.name=name
self.age=age
This appears similar to a model class in SQLAlchemy ORM. By default, name of Collection in database is the name of Python class with its name converted to lowercase. However, a different name of collection can be specified in meta attribute of Document class.
meta={collection': 'student_collection'}
Now declare object of this class and call save() method to store the document in a database.
s1=Student('A001', 'Tara', 20)
s1.save()
One of the advantages of MongoDB database is that it supports dynamic schema. To create a class that supports dynamic schema, subclass it from DynamicDocument base class. Following is the Student class with dynamic schema −
>>> class student(DynamicDocument):
... name=StringField()
The first step is to add first Document as before.
>>> s1=student()
>>> s1.name="Tara"
>>> connect('mydb')
>>> s1.save()
Now add another attribute to second document and save.
>>> s2=student()
>>> setattr(s2,'age',20)
>>> s2.name='Lara'
>>> s2.save()
In the database, student collection will show two documents with dynamic schema.
The meta dictionary of document class can use a Capped Collection by specifying max_documents and max_size.
max_documents − The maximum number of documents that is allowed to be stored in the collection.
max_size − The maximum size of the collection in bytes. max_size is rounded up to the next multiple of 256 by MongoDB internally and mongoengine before.
If max_size is not specified and max_documents is, max_size defaults to 10485760 bytes (10MB).
Other parameters of Document class are listed below −
A MongoEngine document class has one or more attributes. Each attribute is an object of Field class. BaseField is the base class or all field types. The BaseField class constructor has the following arguments −
BaseField(db_field, required, default, unique, primary_key)
The db_field represents name of database field.
The required parameter decides whether value for this field is required, default is false.
The default parameter contains default value of this field
The unique parameter is false by default. Set to true if you want this field to have unique value for each document.
The primary_key parameter defaults to false. True makes this field primary key.
There are a number of Field classes derived from BaseField.
IntField (32bit integer), LongField (64 bit integer), FloatField (floating point number) field constructors have min_value and max_value parameters.
There is also DecimalField class. Value of this field’s object is a float whose precision can be specified. Following arguments are defined for DecimalField class −
DecimalField(min_value, max_value, force_string, precision, rounding)
StringField object can store any Unicode value. You can specify min_length and max_length of the string in the constructor. URLField object is a StringField with capability to validate input as a URL. EmailField validates the string as a valid email representation.
StringField(max-length, min_length)
URLField(url_regex)
EmailField(domain_whiltelist, allow_utf8_user, allow_ip_domain)
The domain_whitelist argument contains list of invalid domains which you would not support. If set to True, allow_utf8_user parameter allows the string to contain UTF8 characters as a part of email. The allow_ip_domain parameter is false by default, but if true, it can be a valid IPV4 or IPV6 address.
Following example uses numeric and string fields −
from mongoengine import *
connect('studentDB')
class Student(Document):
studentid = StringField(required=True)
name = StringField()
age=IntField(min_value=6, max-value=20)
percent=DecimalField(precision=2)
email=EmailField()
s1=Student()
s1.studentid='001'
s1.name='Mohan Lal'
s1.age=20
s1.percent=75
s1.email='mohanlal@gmail.com'
s1.save()
When above code is executed, the student collection shows a document as below −
This type of field wraps any standard field, thus allowing multiple objects to be used as a list object in a database. This field can be used with ReferenceField to implement one to many relationships.
The student document class from above example is modified as below −
from mongoengine import *
connect('studentDB')
class Student(Document):
studentid = StringField(required=True)
name = StringField(max_length=50)
subjects = ListField(StringField())
s1=Student()
s1.studentid='A001'
s1.name='Mohan Lal'
s1.subjects=['phy', 'che', 'maths']
s1.save()
The document added is shown in JSON format as follows −
{
"_id":{"$oid":"5ea6a1f4d8d48409f9640319"},
"studentid":"A001",
"name":"Mohan Lal",
"subjects":["phy","che","maths"]
}
An object of DictField class stores a Python dictionary object. In the corresponding database field as well, this will be stored.
In place of ListField in the above example, we change its type to DictField.
from mongoengine import *
connect('studentDB')
class Student(Document):
studentid = StringField(required=True)
name = StringField(max_length=50)
subjects = DictField()
s1=Student()
s1.studentid='A001'
s1.name='Mohan Lal'
s1.subjects['phy']=60
s1.subjects['che']=70
s1.subjects['maths']=80
s1.save()
Document in the database appears as follows −
{
"_id":{"$oid":"5ea6cfbe1788374c81ccaacb"},
"studentid":"A001",
"name":"Mohan Lal",
"subjects":{"phy":{"$numberInt":"60"},
"che":{"$numberInt":"70"},
"maths":{"$numberInt":"80"}
}
}
A MongoDB document can store reference to another document using this type of field. This way, we can implement join as in RDBMS. A ReferenceField constructor uses name of other document class as parameter.
class doc1(Document):
field1=StringField()
class doc2(Document):
field1=StringField()
field2=ReferenceField(doc1)
In following example, StudentDB database contains two document classes, student and teacher. Document of Student class contains reference to an object of teacher class.
from mongoengine import *
connect('studentDB')
class Teacher (Document):
tid=StringField(required=True)
name=StringField()
class Student(Document):
sid = StringField(required=True)
name = StringField()
tid=ReferenceField(Teacher)
t1=Teacher()
t1.tid='T1'
t1.name='Murthy'
t1.save()
s1=Student()
s1.sid='S1'
s1.name='Mohan'
s1.tid=t1
s1.save()
Run above code and verify result in Compass GUI. Two collections corresponding to two document classes are created in StudentDB database.
The teacher document added is as follows −
{
"_id":{"$oid":"5ead627463976ea5159f3081"},
"tid":"T1",
"name":"Murthy"
}
The student document shows the contents as below −
{
"_id":{"$oid":"5ead627463976ea5159f3082"},
"sid":"S1",
"name":"Mohan",
"tid":{"$oid":"5ead627463976ea5159f3081"}
}
Note that ReferenceField in Student document stores _id of corresponding Teacher document. When accessed, Student object is automatically turned into a reference, and dereferenced when corresponding Teacher object is accessed.
To add reference to document being defined, use ‘self’ instead of other document class as argument to ReferenceField. It may be noted that use of ReferenceField may cause poor performance as far retrieval of documents is concerned.
The ReferenceField constructor also has one optional argument as reverse_delete_rule. Its value determines what to be done if the referred document is deleted.
The possible values are as follows −
DO_NOTHING (0) - don’t do anything (default).
DO_NOTHING (0) - don’t do anything (default).
NULLIFY (1) - Updates the reference to null.
NULLIFY (1) - Updates the reference to null.
CASCADE (2) - Deletes the documents associated with the reference.
CASCADE (2) - Deletes the documents associated with the reference.
DENY (3) - Prevent the deletion of the reference object.
DENY (3) - Prevent the deletion of the reference object.
PULL (4) - Pull the reference from a ListField of references
PULL (4) - Pull the reference from a ListField of references
You can implement one to many relationship using list of references. Assuming that a student document has to be related with one or more teacher documents, the Student class must have a ListField of ReferenceField instances.
from mongoengine import *
connect('studentDB')
class Teacher (Document):
tid=StringField(required=True)
name=StringField()
class Student(Document):
sid = StringField(required=True)
name = StringField()
tid=ListField(ReferenceField(Teacher))
t1=Teacher()
t1.tid='T1'
t1.name='Murthy'
t1.save()
t2=Teacher()
t2.tid='T2'
t2.name='Saxena'
t2.save()
s1=Student()
s1.sid='S1'
s1.name='Mohan'
s1.tid=[t1,t2]
s1.save()
On verifying result of the above code in Compass, you will find the student document having reference of two teacher documents −
Teacher Collection
{
"_id":{"$oid":"5eaebcb61ae527e0db6d15e4"},
"tid":"T1","name":"Murthy"
}
{
"_id":{"$oid":"5eaebcb61ae527e0db6d15e5"},
"tid":"T2","name":"Saxena"
}
Student collection
{
"_id":{"$oid":"5eaebcb61ae527e0db6d15e6"},
"sid":"S1","name":"Mohan",
"tid":[{"$oid":"5eaebcb61ae527e0db6d15e4"},{"$oid":"5eaebcb61ae527e0db6d15e5"}]
}
An instance of DateTimeField class allows data in date format in MongoDB database. MongoEngine looks for Python-DateUtil library for parsing data in appropriate date format. If it is not available in current installation, date is represented using built-in time module’s time.strptime() function. Default value of field of this type is current datetime instance.
Different and varying type of data can be handled by this field. This type of field is internally used by DynamicDocument class.
This type of field corresponds to field in document that can store an image file. Constructor of this class can accept size and thumbnail_size parameters (both in terms of pixel size).
We have already used save() method of Document class to add a document in the collection. The save() method can be further customized with the help of following arguments −
You can set cleaning rules for validation of documents before calling save(). By providing a custom clean() method, you can do any pre validation/data cleaning.
class MyDocument(Document):
...
...
def clean(self):
if <condition>==True:
msg = 'error message.'
raise ValidationError(msg)
Note that Cleaning is only called if validation is turned on and when calling save().
Document class also has insert() method to perform bulk insert. It has following parameters −
If document contains any ReferenceField objects, then by default the save() method will not save any changes to those objects. If you want all references to be saved also, noting each save is a separate query, then passing cascade as True to the save method will cascade any saves.
Deleting a document from its collection is very easy, by calling delete() method. Remember that it will only take effect if the document has been previously saved. The delete() method has following arguments −
To delete entire collection from database use drop_collecction() method. It drops the entire collection associated with this Document type from the database. The method raises OperationError if the document has no collection set (i.g. if it is abstract).
The modify() method in document class performs atomic update of the document in the database and reloads its updated version. It returns True if the document has been updated or False if the document in the database does not match the query. Note that all unsaved changes that have been made to the document are rejected if the method returns True.
The connect() function returns a MongoClient object. Using list_database_names() method available to this object, we can retrieve number of databases on the server.
from mongoengine import *
con=connect('newdb')
dbs=con.list_database_names()
for db in dbs:
print (db)
It is also possible to obtain list of collections in a database, using list_collection_names() method.
collections=con['newdb'].list_collection_names()
for collection in collections:
print (collection)
As mentioned earlier, the Document class has objects attribute that enable access to objects associated with the database.
The newdb database has a products collection corresponding to Document class below. To get all documents, we use objects attribute as follows −
from mongoengine import *
con=connect('newdb')
class products (Document):
ProductID=IntField(required=True)
Name=StringField()
price=IntField()
for product in products.objects:
print ('ID:',product.ProductID, 'Name:',product.Name, 'Price:',product.price)
ID: 1 Name: Laptop Price: 25000
ID: 2 Name: TV Price: 50000
ID: 3 Name: Router Price: 2000
ID: 4 Name: Scanner Price: 5000
ID: 5 Name: Printer Price: 12500
The objects attribute is a QuerySet manager. It creates and returns a QuerySet when accessed. A query can be subjected to filter with the help of field names as keyword arguments. For example, from above products collection, to print details of document with name of product as ‘TV’, we use Name as keyword argument.
for product in products.objects(Name='TV'):
print ('ID:',product.ProductID, 'Name:',product.Name, 'Price:',product.price)
You can use filter method of QuerySet object to apply filter to query. Following code snippet also returns product details with name=’TV’.
qset=products.objects
for product in qset.filter(Name='TV'):
print ('ID:',product.ProductID, 'Name:',product.Name, 'Price:',product.price)
In addition to = operator to check equality, the following logical operators are defined in MongoEngine.
These operators must be attached to field name with double underscore __.
To use greater than (gt) operator, use the following format −
#using greater than operator
for product in products.objects(price__gt=10000):
print ('ID:',product.ProductID, 'Name:',product.Name, 'Price:',product.price)
ID: 1 Name: Laptop Price: 25000
ID: 2 Name: TV Price: 50000
ID: 5 Name: Printer Price: 12500
The in operator is like Python’s in operator. For name of product matching with names in list, the following code is used −
for product in products.objects(Name__in=['TV', 'Printer']):
print ('ID:',product.ProductID, 'Name:',product.Name, 'Price:',product.price)
ID: 2 Name: TV Price: 50000
ID: 5 Name: Printer Price: 12500
You can use following operators as shortcut for regex expressions for applying filter to queries −
For example, the following code prints product details for name containing ‘o’ in name −
for product in products.objects(Name__contains='o'):
print ('ID:',product.ProductID, 'Name:',product.Name, 'Price:',product.price)
ID: 1 Name: Laptop Price: 25000
ID: 3 Name: Router Price: 2000
In another example of string query, the following code displays name ending with ‘er’−
for product in products.objects(Name__endswith='er'):
print ('ID:',product.ProductID, 'Name:',product.Name, 'Price:',product.price)
ID: 3 Name: Router Price: 2000
ID: 4 Name: Scanner Price: 5000
ID: 5 Name: Printer Price: 12500
The QuerySet object possesses following useful methods for querying the database.
First document satisfying the query is returned. Following code will return first document in products collection, that has price < 20000.
qset=products.objects(price__lt=20000)
doc=qset.first()
print ('Name:',doc.Name, 'Price:',doc.price)
Name: Router Price: 2000
This will cause mentioned fields to be excluded from Query Set. Here, to_json() mehod of Document class is used to obtain JSONified version of Document. ProductID field will not appear in the result.
for product in products.objects.exclude('ProductID'):
print (product.to_json())
{"_id": {"$oid": "5c8dec275405c12e3402423c"}, "Name": "Laptop", "price": 25000}
{"_id": {"$oid": "5c8dec275405c12e3402423d"}, "Name": "TV", "price": 50000}
{"_id": {"$oid": "5c8dec275405c12e3402423e"}, "Name": "Router", "price": 2000}
{"_id": {"$oid": "5c8dec275405c12e3402423f"}, "Name": "Scanner", "price": 5000}
{"_id": {"$oid": "5c8dec275405c12e34024240"}, "Name": "Printer", "price": 12500}
Use this method to manipulate which fields to load in the query set. Use field names as keyword arguments and set to 1 to include, 0 to exclude.
for product in products.objects.fields(ProductID=1,price=1):
print (product.to_json())
{"_id": {"$oid": "5c8dec275405c12e3402423c"}, "ProductID": 1, "price": 25000}
{"_id": {"$oid": "5c8dec275405c12e3402423d"}, "ProductID": 2, "price": 50000}
{"_id": {"$oid": "5c8dec275405c12e3402423e"}, "ProductID": 3, "price": 2000}
{"_id": {"$oid": "5c8dec275405c12e3402423f"}, "ProductID": 4, "price": 5000}
{"_id": {"$oid": "5c8dec275405c12e34024240"}, "ProductID": 5, "price": 12500}
Setting field keyword argument to 0 in fields() method works similar to exclude() method.
for product in products.objects.fields(price=0):
print (product.to_json())
{"_id": {"$oid": "5c8dec275405c12e3402423c"}, "ProductID": 1, "Name": "Laptop"}
{"_id": {"$oid": "5c8dec275405c12e3402423d"}, "ProductID": 2, "Name": "TV"}
{"_id": {"$oid": "5c8dec275405c12e3402423e"}, "ProductID": 3, "Name": "Router"}
{"_id": {"$oid": "5c8dec275405c12e3402423f"}, "ProductID": 4, "Name": "Scanner"}
{"_id": {"$oid": "5c8dec275405c12e34024240"}, "ProductID": 5, "Name": "Printer"}
Effect of this method is similar to fields() method. Fields corresponding to keyword arguments only will appear in the query set.
for product in products.objects.only('Name'):
print (product.to_json())
{"_id": {"$oid": "5c8dec275405c12e3402423c"}, "Name": "Laptop"}
{"_id": {"$oid": "5c8dec275405c12e3402423d"}, "Name": "TV"}
{"_id": {"$oid": "5c8dec275405c12e3402423e"}, "Name": "Router"}
{"_id": {"$oid": "5c8dec275405c12e3402423f"}, "Name": "Scanner"}
{"_id": {"$oid": "5c8dec275405c12e34024240"}, "Name": "Printer"}
This method computes sum of given field in the query set.
This method calculates average of given field in the query set.
avg=products.objects.average('price')
ttl=products.objects.sum('price')
print ('sum of price field',ttl)
print ('average of price field',avg)
sum of price field 94500
average of price field 18900.0
QuerySet’s order_by() function is used to obtain the query result in a sorted manner. The usage is as follows −
Qset.order_by(‘fieldname’)
By default, the sort order is ascending. For descending order, attach – sign to name of field. For example, to get price wise list in ascending order −
from mongoengine import *
con=connect('newdb')
class products (Document):
ProductID=IntField(required=True)
company=StringField()
Name=StringField()
price=IntField()
for product in products.objects.order_by('price'):
print ("Name:{} company:{} price:{}".format(product.Name, product.company, product.price))
Name:Router company:Iball price:2000
Name:Scanner company:Cannon price:5000
Name:Printer company:Cannon price:12500
Name:Laptop company:Acer price:25000
Name:TV company:Philips price:31000
Name:Laptop company:Dell price:45000
Name:TV company:Samsung price:50000
Following code will get the list in descending order of name −
for product in products.objects.order_by('-Name'):
print ("Name:{} company:{} price:{}".format(product.Name, product.company, product.price))
Name:TV company:Samsung price:50000
Name:TV company:Philips price:31000
Name:Scanner company:Cannon price:5000
Name:Router company:Iball price:2000
Name:Printer company:Cannon price:12500
Name:Laptop company:Acer price:25000
Name:Laptop company:Dell price:45000
You can also get sorting done on multiple fields. This code will get you companywise, pricelist in ascending order.
for product in products.objects.order_by('company','price'):
print ("Name:{} company:{} price:{}".format(product.Name, product.company, product.price))
Name:Laptop company:Acer price:25000
Name:Scanner company:Cannon price:5000
Name:Printer company:Cannon price:12500
Name:Laptop company:Dell price:45000
Name:Router company:Iball price:2000
Name:TV company:Philips price:31000
Name:TV company:Samsung price:50000
By default, the objects attribute on a document class returns a QuerySet without applying any filter. However, you can define a classmethod on a document that modifies a queryset. Such a method should accept two arguments – doc_cls and queryset and it needs to be decorated with queryset_manager() in order for it to be recognized.
@queryset_manager
def qry_method(docs_cls,queryset):
....
----
In the following example, the document class called products has an expensive_prods() method which is decorated by @queryset_manager. The method itself applies a filter to queryset such that only objects with price >20000 are returned. This method is now the default document query and objects attribute of products class returns filtered documents.
from mongoengine import *
con=connect('newdb')
class products (Document):
ProductID=IntField(required=True)
company=StringField()
Name=StringField()
price=IntField()
@queryset_manager
def expensive_prods(docs_cls,queryset):
return queryset.filter(price__gt=20000)
for product in products.expensive_prods():
print ("Name:{} company:{} price:{}".format(product.Name, product.company, product.price))
Name:Laptop company:Acer price:25000
Name:TV company:Samsung price:50000
Name:TV company:Philips price:31000
Name:Laptop company:Dell price:45000
If you wish to customize methods for filtering documents, first declare a subclass of QuerySet class, and use it as value of queryset_class property in meta dictionary.
The example below uses MyQuerySet class as definition of custom queryset. The myqrymethod() in this class filters the documents whose name field ends with ‘er’. In products class, meta attribute refers to this queryset subclass is used as value of queryset_class property.
from mongoengine import *
con=connect('newdb')
class MyQuerySet(QuerySet):
def myqrymethod(self):
return self.filter(Name__endswith='er')
class products (Document):
meta = {'queryset_class': MyQuerySet}
ProductID=IntField(required=True)
company=StringField()
Name=StringField()
price=IntField()
for product in products.objects.myqrymethod():
print ("Name:{} company:{} price:{}".format(product.Name, product.company, product.price))
Name:Router company:Iball price:2000
Name:Scanner company:Cannon price:5000
Name:Printer company:Cannon price:12500
An indexed collection results in faster processing of queries. By default, every collection is automatically indexed on _id field. In addition, you can create index on one or more fields.
Using Compass, we can build index very easily. Click on CREATE INDEX button on Indexes tab as shown in figure below−
A dialog box appears as shown. Choose name of index, field on which to index, order of index (ascending or descending) and other options.
While using MongoEngine, indexes are created by specifying ‘indexes’ key in meta dictionary of definition of Document class.
Value of indexes property is a list of fields. In the following example, we ask documents in student collection be indexed according to name field.
from mongoengine import *
con=connect('mydata')
class student(Document):
name=StringField(required=True)
course=StringField()
meta = {'indexes':['name']}
s1=student()
s1.name='Avinash'
s1.course='DataScience'
s1.save()
s2=student()
s2.name='Anita'
s2.course='WebDesign'
s2.save()
By default, indexing order is ascending. Order may be specified by prepending ‘+’ for ascending or ‘-‘ for descending order.
To create compound index, use a tuple of field names, optionally having + or – symbol attached to indicate sort order.
In the following example, student document class contains definition of compound index on name and course (note - symbol prefixed to course field which means index is built namewise ascending and coursewise descending order.
from mongoengine import *
con=connect('mydata')
class student(Document):
name=StringField(required=True)
course=StringField()
meta = {'indexes':[('name','-course')]}
s1=student()
s1.name='Avinash'
s1.course='DataScience'
s1.save()
s2=student()
s2.name='Anita'
s2.course='WebDesign'
s2.save()
MongoDB Compass will show indexes as below −
Value of ‘indexes’ may be a dictionary of various options as below −
Following example creates index on name field that expires after 3600 seconds.
from mongoengine import *
con=connect('mydata')
class student(Document):
name=StringField(required=True)
course=StringField()
meta = {'indexes':[{
'fields': ['name'],
'expireAfterSeconds': 3600
}
]
}
To specify text index, prefix field name with ‘$’ sign and for hashed index, use ‘#’ as prefix.
Indexes so specified are created automatically as documents are added in the collection. To disable automatic creation, set ‘auto_create_index’ to False in meta attribute.
We have list_indexes() method with Document class that displays list of available indexes.
print (student.list_indexes())
[[('name', 1)], [('_id', 1)]]
To create index on a field not in the meta dictionary, use create_index() method. The following code will create index on course field −
class student(Document):
name=StringField(required=True)
course=StringField()
meta = {'indexes':[{
'fields': ['name'],
'expireAfterSeconds': 3600
}
]}
student.create_index(['course'])
The term ‘aggregation’ is used for the operation that processes data and returns computed result. Finding sum, count and average on one or more fields of documents in a collection can be called as aggregation functions.
MongoEngine provides aggregate() function that encapsulates PyMongo’s aggregation framework. Aggregation operation uses a collection as input and returns one or more documents as a result.
MongoDB uses concept of data processing pipelines. A pipeline can have multiple stages. Basic stage provides that provide filter and operate like queries. Others provide tools for grouping and/or sorting by one or more fields, string concatenation tasks, array aggregation tools, etc.
Following stages are defined in MongoDB pipeline creation −
Aggregation expressions use field path to access fields in the input documents. To specify a field path, use a string that prefixes with a dollar sign $$$ the field name. Expression can use one or more Boolean operators ($and, $or, $not) and comparison operators ($eq, $gt, $lt, $gte, $lte and $ne).
Following arithmetic expressions are also used for aggregation −
Following string expression can also be used in aggregation −
To demonstrate how aggregate() function works in MongoEngine, let us first define a Document class called orders.
from mongoengine import *
con=connect('mydata')
class orders(Document):
custID = StringField()
amount= IntField()
status = StringField()
We then add following documents in orders collection −
The aggregate() function is to be used to find sum of amount field for each custID only when status equals ‘A’. Accordingly, the pipeline is constructed as follows.
First stage in pipeline uses $match to filter documents with status=’A’. Second stage uses $group identifier to group documents on CustID and performs sum of amount.
pipeline = [
{"$match" : {"status" : "A"}},
{"$group": {"_id": "$custID", "total": {"$sum": "$amount"}}}
]
This pipeline is now used as argument to aggregate() function.
docs = orders.objects().aggregate(pipeline)
We can iterate over the document cursor with a for loop. The complete code is given below −
from mongoengine import *
con=connect('mydata')
class orders(Document):
custID = StringField()
amount= IntField()
status = StringField()
pipeline = [
{"$match" : {"status" : "A"}},
{"$group": {"_id": "$custID", "total": {"$sum": "$amount"}}}
]
docs = orders.objects().aggregate(pipeline)
for doc in docs:
print (x)
For the given data, the following output is generated −
{'_id': 'B212', 'total': 400}
{'_id': 'A123', 'total': 750}
In order to get more efficiency in retrieving a subset of fields in a document, use only() method of Objects attribute. This will significantly improve performance especially for fields with extremely large length such as ListField. Pass the required field to only() function. If other fields are accessed after executing only() query, default value is returned.
from mongoengine import *
con=connect('newdb')
class person (Document):
name=StringField(required=True)
city=StringField(default='Mumbai')
pin=IntField()
p1=person(name='Himanshu', city='Delhi', pin=110012).save()
doc=person.objects.only('name').first()
print ('name:',doc.name)
print ('city:', doc.city)
print ('PIN:', doc.pin)
name: Himanshu
city: Mumbai
PIN: None
Note − The value of city attribute is used as default. As default is not specified for PIN, it prints None.
You may call reload() function if you need missing fields.
When a document class has a ListField or DictField, while iterating through it, any DBREf objects are automatically dereferenced. To increase the efficiency further, especially if the document has ReferenceField, number of queries can be limited by using select_related() function which converts QuerySet in a list and effects dereferencing.
MongoEngine API contains Q class which is useful for constructing advanced queries consisting of number of constraints. Q represents a part of query which can be initialized by keyword argument syntax and binary & and | operators.
person.objects(Q(name__startswith=’H’) &Q(city=’Mumbai’))
It is possible to define an inherited class of any user defined Document class. The inherited class may add extra fields if required. However, since such as a class is not a direct subclass of Document class, it will not create a new collection, instead its objects are stored in a collection used by its parent class. In the parent class, meta attribute ‘allow_inheritance the following example, we first define employee as a document class and set allow_inheritance to true. The salary class is derived from employee, adding two more fields dept and sal. Objects of Employee as well as salary classes are stored in employee collection.
In the following example, we first define employee as a document class and set allow_inheritance to true. The salary class is derived from employee, adding two more fields dept and sal. Objects of Employee as well as salary classes are stored in employee collection.
from mongoengine import *
con=connect('newdb')
class employee (Document):
name=StringField(required=True)
branch=StringField()
meta={'allow_inheritance':True}
class salary(employee):
dept=StringField()
sal=IntField()
e1=employee(name='Bharat', branch='Chennai').save()
s1=salary(name='Deep', branch='Hyderabad', dept='Accounts', sal=25000).save()
We can verify that two documents are stored in employee collection as follows −
{
"_id":{"$oid":"5ebc34f44baa3752530b278a"},
"_cls":"employee",
"name":"Bharat",
"branch":"Chennai"
}
{
"_id":{"$oid":"5ebc34f44baa3752530b278b"},
"_cls":"employee.salary",
"name":"Deep",
"branch":"Hyderabad",
"dept":"Accounts",
"sal":{"$numberInt":"25000"}
}
Note that, in order to identify the respective Document class, MongoEngine adds a “_cls” field and sets its value as "employee" and "employee.salary".
If you want to provide extra functionality to a group of Document classes, but without overhead of inheritance, you can first create an abstract class and then derive one or more classes from the same. To make a class abstract, meta attribute ‘abstract’ is set to True.
from mongoengine import *
con=connect('newdb')
class shape (Document):
meta={'abstract':True}
def area(self):
pass
class rectangle(shape):
width=IntField()
height=IntField()
def area(self):
return self.width*self.height
r1=rectangle(width=20, height=30).save()
Atomicity is one of the ACID transaction properties. A database transaction has to be indivisible and irreducible so that it either occurs completely or doesn’t occur at all. This property is called Atomicity. MongoDB supports Atomicity only on single documents and not on multi-document transactions.
MongoEngine provides the following methods for atomic updates on a queryset.
update_one() − Overwrites or adds first document matched by query.
update() − Performs atomic update on fields matched by query.
modify() − Update a document and return it.
Following modifiers may be used with these methods. (These modifiers come before the field, not after).
The following is an example of atomic update, we first create a Document class called tests and add a document in it.
from mongoengine import *
con=connect('newdb')
class tests (Document):
name=StringField()
attempts=IntField()
scores=ListField(IntField())
t1=tests()
t1.name='XYZ'
t1.attempts=0
t1.scores=[]
t1.save()
Let us use update_one() method to update name field from XYZ to MongoDB.
tests.objects(name='XYZ').update_one(set__name='MongoDB')
The push modifier is used to add data in ListField (scores).
tests.objects(name='MongoDB').update_one(push__scores=50)
To increment attempts field by one, we can use inc modifier.
tests.objects(name='MongoDB').update_one(inc__attempts=1)
The updated document looks as follows −
{
"_id":{"$oid":"5ebcf8d353a48858e01ced04"},
"name":"MongoDB",
"attempts":{"$numberInt":"1"},
"scores":[{"$numberInt":"50"}]
}
QuerySet object of MongoEngine has exec_js() method that allows execution of a Javascript function on MongoDB server. This function processes the following arguments −
exec_js(code, *field_names, **options)
Where,
code − a string containing Javascript code to execute
code − a string containing Javascript code to execute
fields − to be used in your function, which will be passed as arguments
fields − to be used in your function, which will be passed as arguments
options − options that you want available to the function (accessed in Javascript through the options object)
options − options that you want available to the function (accessed in Javascript through the options object)
In addition, some more variables are also made available to the function’s scope as given below −
collection − name of the collection corresponding to the Document class. This should be used to get the Collection object from db in Javascript code.
collection − name of the collection corresponding to the Document class. This should be used to get the Collection object from db in Javascript code.
query − the query that has been generated by the QuerySet object; passed into the find() method on a Collection object in the Javascript function.
query − the query that has been generated by the QuerySet object; passed into the find() method on a Collection object in the Javascript function.
options − an object containing the keyword arguments passed into exec_js().
options − an object containing the keyword arguments passed into exec_js().
Note that attributes in MongoEngine document class may use different names in the database (set using the db_field keyword argument to a Field constructor).
class BlogPost(Document):
title = StringField(db_field='doctitle')
For this purpose, a mechanism exists for replacing MongoEngine field attribute with the database field names in Javascript code.
When accessing a field on a collection object, use square-bracket notation, and prefix the MongoEngine field name with a tilde (~) symbol. The field name that follows the tilde will be translated to the name used in the database.
document': doc[~title];
Note that when Javascript code refers to fields on embedded documents, the name of the EmbeddedDocumentField, followed by a dot, should be used before the name of the field on the embedded document.
In MongoDB, the files with size larger than 16 MB are stored using GridFS specifications. A file is divided into multiple chunks each with a default size of 255KB. Large chunk may be as large as necessary. GridFS uses two collections, one for chunks and other for metadata.
GridFS may be used to store any file if you want to access it without having to load it entirely in the memory.
MongoEngine API supports GridFS through FileField object. Using this object, it is possible to insert and retrieve data. The FileField object’s put() method helps writing the file as a part of Document.
from mongoengine import *
con=connect('newdb')
class lang (Document):
name=StringField()
developer=StringField()
logo=FileField()
l1=lang()
l1.name='Python'
l1.developer='Van Rossum'
f=open('pylogo.png','rb')
l1.logo.put(f,content_type='image/png')
l1.save()
Contents of FileField can be retrieved by read() method of Python’s File object.
logo = l1.logo.read()
There is also delete() method to delete the stored file.
l1 = lang.objects(name='Python').first()
l1.logo.delete()
l1.save()
Note that the FileField stores only the ID of file in a separate GridFS collection. Hence delete() method does not delete the file physically.
The replace() method helps in replacing reference of file with another file.
l1 = lang.objects(name='Python').first()
f=open('newlogo.png','rb')
l1.logo.replace(f,content_type='image/png')
l1.save()
Signals are events dispatched by a sender object, any number of receiver objects can subscribe to such events. A signal receiver can subscribe to a specific sender or may receive signals from many senders.
In MongoEngine, signal handling is supported by blinker library, which means you need to install it using pip utility. The mongoengine.signals module has the definitions of following signals −
An event handler function is then attached to Document class. Note that EmbeddedDocument only supports pre/post_init signals. pre/post_save, etc., should be attached to Document’s class only.
You can also use a decorator to quickly create a number of signals and attach them to your Document or EmbeddedDocument subclasses as class decorators.
In the following example, used as demonstration of signal handlers, we also use Python’s standard library module – logging and set the logging level to debug.
from mongoengine import *
from mongoengine import signals
import logging
logging.basicConfig(level=logging.DEBUG)
We then write a document class so that corresponding collection is created in newdb database. Inside the class, two class mehods pre_save() and post_save() methods are defined which are intended to be invoked before and after a document is saved in Author collection.
class Author(Document):
name = StringField()
def __unicode__(self):
return self.name
@classmethod
def pre_save(cls, sender, document, **kwargs):
logging.debug("Pre Save: %s" % document.name)
@classmethod
def post_save(cls, sender, document, **kwargs):
logging.debug("Post Save: %s" % document.name)
if 'created' in kwargs:
if kwargs['created']:
logging.debug("Created")
else:
logging.debug("Updated")
Both the class methods are defined with arguments for classname, sender object and document with optional list of keyword arguments.
Finally, we register the signal handlers.
signals.pre_save.connect(Author.pre_save, sender=Author)
signals.post_save.connect(Author.post_save, sender=Author)
As we create an instance of Document subclass, the console log will show the pre and post save signals being processed by respective event handlers.
Author(name="Lathkar").save()
Python console reports the log as shown below −
DEBUG:root:Pre Save: Lathkar
DEBUG:root:Post Save: Lathkar
DEBUG:root:Created
MongoDB supports use of query operators that can perform text search on a string content. As described earlier, to set a text index prefix name of index with $ symbol. For a text index, the weight of an indexed field denotes the significance of the field relative to the other indexed fields in terms of the text search score. You can also specify default language in meta dictionary of the class.
List of supported languages can be found at https://docs.mongodb.com/manual/reference/text-search-languages/
MongoEngine API consists of search_text() method for QuerySet object. The string to be searched in indexed fields is given as argument.
In the following example, we first define a Document class called lang with two string fields, name of language and its features. We also create indexes on both fields with respective weights.
from mongoengine import *
con=connect('newdb')
class lang (Document):
name=StringField()
features=StringField()
meta = {'indexes': [
{'fields': ['$name', "$features"],
'default_language': 'english',
'weights': {'name': 2, 'features': 10}
}]
}
l1=lang()
l1.name='C++'
l1.features='Object oriented language for OS development'
l1.save()
l2=lang()
l2.name='Python'
l2.features='dynamically typed and object oriented for data science, AI and ML'
l2.save()
l3=lang()
l3.name='HTML'
l3.features='scripting language for web page development'
l3.save()
In order to perform search for word ‘oriented’, we employ search_text() method as follows −
docs=lang.objects.search_text('oriented')
for doc in docs:
print (doc.name)
Output of the above code will be names of languages in whose description the word ‘oriented’ occurs (‘Python and ‘C++’ in this case).
MongoEngine integrates beautifully with the following libraries −
marshmallow is an ORM/ODM/framework independent serialization/deserialization library for converting complex datatypes, such as objects, to and from native Python datatypes. Using this extension of MongoEngine, we can easily perform serialize/deserialize operations.
First, create a Document class as usual as follows −
import mongoengine as me
class Book(me.Document):
title = me.StringField()
Then generate marshmallow schema with the code below −
from marshmallow_mongoengine import ModelSchema
class BookSchema(ModelSchema):
class Meta:
model = Book
b_s = BookSchema()
Save a document using the code:
book = Book(title='MongoEngine Book').save()
And perform serialization/deserialization using dump(0 and load() using the code below −
data = b_s.dump(book).data
b_s.load(data).data
This is a Flask extension that provides integration with MongoEngine. Connection management of MongoDB database for your app is handled easily by this library. You can also use WTForms as model forms for your models.
After installation of flask-mongoengine package, initialize flask app with the following settings −
from flask import Flask
from flask_mongoengine import MongoEngine
app = Flask(__name__)
app.config['MONGODB_SETTINGS'] = {
'db': 'mydata',
'host': 'localhost',
'port':27017
}
db = MongoEngine(app)
Then define a Document sub class using the below code −
class book(me.Document):
name=me.StringField(required=True)
Declare an object of above class and call save() method when a particular route is visited.
@app.route('/')
def index():
b1=book(name='Introduction to MongoEngine')
b1.save()
return 'success'
This extension contains additional Field Types and any other wizardry.
Eve is an open source Python REST API framework designed for human beings. It allows to effortlessly build and deploy highly customizable, fully featured RESTful Web Services.
Eve is powered by Flask and Cerberus and it offers native support for MongoDB data stores. Eve-MongoEngine provides MongoEngine integration with Eve.
Install and import the extension using the code below −
import mongoengine
from eve import Eve
from eve_mongoengine import EveMongoengine
Configure the settings and initialize the Eve instance.
my_settings = {
'MONGO_HOST': 'localhost',
'MONGO_PORT': 27017,
'MONGO_DBNAME': 'eve_db'
app = Eve(settings=my_settings)
# init extension
ext = EveMongoengine(app)
Define a Document class as shown below −
class Person(mongoengine.Document):
name = mongoengine.StringField()
age = mongoengine.IntField()
Add the model and run the application, finally using the below code −
ext.add_model(Person)
app.run()
This extension aims to integrate MongoEngine with Django API, a very popular Python web development framework. This project is still under development.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2810,
"s": 2310,
"text": "NoSQL databases have seen rise in popularity in the last decade. In today’s world of real time web applications, huge amount of data is being generated with mobile and embedded devices. Traditional relational databases (like Oracle, MySQL, etc.) are not suitable for strings. The processing of such data is also difficult as they have fixed and predefined schema, and are not scalable. NOSQL databases have flexible schema and are stored in distributed manner on a large number of community servers."
},
{
"code": null,
"e": 3381,
"s": 2810,
"text": "NOSQL databases are classified on the basis of organization of data. MongoDB is a popular Document Store NOSQL database. Fundamental constituent of a MongoDB database is called a document. A document is a collection of key-value pairs stored in JSON format. More than one documents are stored in a collection. A collection can be considered as analogous to a table in any relational database, and a Document as row in a table. However, it should be noted that since MongoDB is schema less, number of key-value pairs in each document of a Collection need not be the same."
},
{
"code": null,
"e": 3709,
"s": 3381,
"text": "MongoDB is developed by MongoDB Inc. It is a general-purpose, distributed document based database. It is available in enterprise as well as community edition. Latest version of Community version for Windows operating system can be downloaded from https://fastdl.mongodb.org/win32/mongodb-win32-x86_64-2012plus-4.2.6-signed.msi."
},
{
"code": null,
"e": 3801,
"s": 3709,
"text": "Install MongoDB in a folder of your choice and start the server with the following command−"
},
{
"code": null,
"e": 3824,
"s": 3801,
"text": "D:\\mongodb\\bin>mongod\n"
},
{
"code": null,
"e": 4009,
"s": 3824,
"text": "Server is now ready for incoming connection requests at port 27017. MongoDB databases are stored in bin/data directory. This location can be changed by –dbpath option in above command."
},
{
"code": null,
"e": 4089,
"s": 4009,
"text": "In another command terminal, start MongoDB console with the following command −"
},
{
"code": null,
"e": 4111,
"s": 4089,
"text": "D:\\mongodb\\bin>mongo\n"
},
{
"code": null,
"e": 4356,
"s": 4111,
"text": "MongoDB prompt is similar to what we normally see in MySQL or SQLite terminal. All database operations such as creating database, inserting a document, updating and deleting as well as retrieval of documents can be done from within the console."
},
{
"code": null,
"e": 4592,
"s": 4356,
"text": "E:\\mongodb\\bin>mongo\nMongoDB shell version v4.0.6\nconnecting to: mongodb://127.0.0.1:27017/?gssapiServiceName=mongodb\nImplicit session: session { \"id\" : UUID(\"0d848b11-acf7-4d30-83df-242d1d7fa693\") }\nMongoDB server version: 4.0.6\n---\n>"
},
{
"code": null,
"e": 4625,
"s": 4592,
"text": "Default database in use is test."
},
{
"code": null,
"e": 4636,
"s": 4625,
"text": "> db\nTest\n"
},
{
"code": null,
"e": 4751,
"s": 4636,
"text": "With 'use' command any other database is set as current. If the named database does not exist, new one is created."
},
{
"code": null,
"e": 4783,
"s": 4751,
"text": "> use mydb\nswitched to db mydb\n"
},
{
"code": null,
"e": 4885,
"s": 4783,
"text": "Please refer to our detailed tutorial on MongoDB at https://www.tutorialspoint.com/mongodb/index.htm."
},
{
"code": null,
"e": 5150,
"s": 4885,
"text": "MongoDB has also developed a GUI tool for handling MongoDB databases. It is called MongoDB Compass. It is a convenient tool for performing all CRUD operations without manually writing queries. It helps in many activities such as indexing, document validation, etc."
},
{
"code": null,
"e": 5420,
"s": 5150,
"text": "Download community edition of MongoDB Compass from https://www.mongodb.com/download-center/compass and start MongoDBCompassCommunity.exe (Ensure that MongoDB server is running before starting Compass). Connect to the local server by giving correct host and port number."
},
{
"code": null,
"e": 5484,
"s": 5420,
"text": "All the databases currently available will be listed as below −"
},
{
"code": null,
"e": 5562,
"s": 5484,
"text": "Click on + button (shown at the bottom of left panel) to create new database."
},
{
"code": null,
"e": 5637,
"s": 5562,
"text": "Choose name of database from list and select a Collection as shown below −"
},
{
"code": null,
"e": 5700,
"s": 5637,
"text": "You can add document directly or import from CSV or JSON file."
},
{
"code": null,
"e": 5748,
"s": 5700,
"text": "Choose Insert Document from Add data drop down."
},
{
"code": null,
"e": 5814,
"s": 5748,
"text": "Documents added will be displayed in JSON, list or tabular form −"
},
{
"code": null,
"e": 5976,
"s": 5814,
"text": "Note that, just as a table in relational database has a primary key, document in MongoDB database has a special key called \"_id\" that is automatically generated."
},
{
"code": null,
"e": 6122,
"s": 5976,
"text": "MongoDB Inc. provides a Python driver for connection with MongoDB databases. It is called PyMongo whose usage is similar to standard SQL queries."
},
{
"code": null,
"e": 6228,
"s": 6122,
"text": "After installing PyMongo module, we need object of MongoClient class for interacting with MongoDB server."
},
{
"code": null,
"e": 6291,
"s": 6228,
"text": "<<< from pymongo import MongoClient\n<<< client=MongoClient() \n"
},
{
"code": null,
"e": 6346,
"s": 6291,
"text": "New database is created with the following statement −"
},
{
"code": null,
"e": 6369,
"s": 6346,
"text": "db=client.mydatabase \n"
},
{
"code": null,
"e": 6647,
"s": 6369,
"text": "CRUD operations on this database are performed with methods such as insert_one() (or insert_many()), find(), update() and delete() methods. Detailed discussion of PyMongo library is available at https://www.tutorialspoint.com/python_data_access/python_mongodb_introduction.htm."
},
{
"code": null,
"e": 6806,
"s": 6647,
"text": "However, Python’s user defined objects cannot be stored in database unless it is converted in MongoDB’s data types. This is where we need MongoEngine library."
},
{
"code": null,
"e": 7347,
"s": 6806,
"text": "MongoDB is a document based database. Each document is a JSON like representation of fields and values. A document in MongoDB is roughly equivalent to a row in RDBMS table (MongoDB equivalent of table is Collection). Even though MongoDB does not enforce any predefined schema, the field objects in a document have certain data type. MongoDB data types are very much similar to Python’s primary data types. If one has to store object of Python’s user defined class, its attributes have to be manually parsed to equivalent MongoDB data types."
},
{
"code": null,
"e": 7591,
"s": 7347,
"text": "MongoEngine provides a convenient abstraction layer over PyMongo and maps each object of Document class to a document in MongoDB database. MongoEngine API has been developed by Hary Marr in August 2013. Latest version of MongoEngine is 0.19.1."
},
{
"code": null,
"e": 7929,
"s": 7591,
"text": "MongoEngine is to MongoDB what SQLAlchemy is to RDBMS databases. MongoEngine library provides a Document class that is used as base for defining custom class. Attributes of this class form the fields of MongoDB document. The Document class defines methods to perform CRUD operations. In subsequent topics, we shall learn how to use them."
},
{
"code": null,
"e": 8051,
"s": 7929,
"text": "To use MongoEngine, you need to have already installed MongoDB and MongoDB server should be running as described earlier."
},
{
"code": null,
"e": 8113,
"s": 8051,
"text": "Easiest way to install MongoEngine is by using PIP installer."
},
{
"code": null,
"e": 8138,
"s": 8113,
"text": "pip install mongoengine\n"
},
{
"code": null,
"e": 8320,
"s": 8138,
"text": "If your Python installation does not have Setuptools installed, you will have to download MongoEngine from https://github.com/MongoEngine/mongoengine and run the following command −"
},
{
"code": null,
"e": 8345,
"s": 8320,
"text": "python setup.py install\n"
},
{
"code": null,
"e": 8390,
"s": 8345,
"text": "MongoEngine has the following dependencies −"
},
{
"code": null,
"e": 8403,
"s": 8390,
"text": "pymongo>=3.4"
},
{
"code": null,
"e": 8416,
"s": 8403,
"text": "pymongo>=3.4"
},
{
"code": null,
"e": 8428,
"s": 8416,
"text": "six>=1.10.0"
},
{
"code": null,
"e": 8440,
"s": 8428,
"text": "six>=1.10.0"
},
{
"code": null,
"e": 8456,
"s": 8440,
"text": "dateutil>=2.1.0"
},
{
"code": null,
"e": 8472,
"s": 8456,
"text": "dateutil>=2.1.0"
},
{
"code": null,
"e": 8486,
"s": 8472,
"text": "pillow>=2.0.0"
},
{
"code": null,
"e": 8500,
"s": 8486,
"text": "pillow>=2.0.0"
},
{
"code": null,
"e": 8586,
"s": 8500,
"text": "To verify the correct installation, run import command and check version as follows −"
},
{
"code": null,
"e": 8647,
"s": 8586,
"text": ">>> import mongoengine\n>>> mongoengine.__version__\n'0.19.1'\n"
},
{
"code": null,
"e": 8729,
"s": 8647,
"text": "As mentioned earlier, you should first start MongoDB server using mongod command."
},
{
"code": null,
"e": 8821,
"s": 8729,
"text": "MongoEngine provides connect() function to connect to a running instance of mongodb server."
},
{
"code": null,
"e": 8875,
"s": 8821,
"text": "from mongoengine import connect\nconnect(‘mydata.db’)\n"
},
{
"code": null,
"e": 9021,
"s": 8875,
"text": "By default, MongoDB server is running on localhost and on port 27017. To customize, you should provide the host and port arguments to connect() −"
},
{
"code": null,
"e": 9075,
"s": 9021,
"text": "connect('mydata.db', host='192.168.1.1', port=12345)\n"
},
{
"code": null,
"e": 9220,
"s": 9075,
"text": "In case the database requires authentication, its credentials such as username, password and authentication_source arguments should be provided."
},
{
"code": null,
"e": 9307,
"s": 9220,
"text": "connect('mydata.db', username='user1', password='***', authentication_source='admin')\n"
},
{
"code": null,
"e": 9378,
"s": 9307,
"text": "MongoEngine also supports URI style connections instead of IP address."
},
{
"code": null,
"e": 9442,
"s": 9378,
"text": "connect('mydata.db', host='mongodb://localhost/database_name')\n"
},
{
"code": null,
"e": 9818,
"s": 9442,
"text": "The connect() function has another optional parameter called replicaset. MongoDB is a distributed database. Data stored in one server is usually replicated in many server instances in order to ensure high availability. A replica set in MongoDB is a group of mongod processes on which the same data set is maintained. Replica sets are the basis for all production deployments."
},
{
"code": null,
"e": 9881,
"s": 9818,
"text": "connect(host='mongodb://localhost/dbname?replicaSet=rs-name')\n"
},
{
"code": null,
"e": 9935,
"s": 9881,
"text": "Following replica set methods are defined as follows:"
},
{
"code": null,
"e": 10129,
"s": 9935,
"text": "MongoEngine also allows connection with multiple databases. You need to provide unique alias name for each database. For example, following code connects Python script to two MongoDB databases."
},
{
"code": null,
"e": 10198,
"s": 10129,
"text": "connect(alias='db1', db='db1.db')\nconnect(alias='db2', db='db2.db')\n"
},
{
"code": null,
"e": 10503,
"s": 10198,
"text": "MongoEngine is termed as ODM (Object Document Mapper). MongoEngine defines a Document class. This is a base class whose inherited class is used to define structure and properties of collection of documents stored in MongoDB database. Each object of this subclass forms Document in Collection in database."
},
{
"code": null,
"e": 10632,
"s": 10503,
"text": "Attributes in this Document subclass are objects of various Field classes. Following is an example of a typical Document class −"
},
{
"code": null,
"e": 10884,
"s": 10632,
"text": "from mongoengine import *\nclass Student(Document):\n studentid = StringField(required=True)\n name = StringField(max_length=50)\n age = IntField()\n def _init__(self, id, name, age):\n self.studentid=id,\n self.name=name\n self.age=age"
},
{
"code": null,
"e": 11144,
"s": 10884,
"text": "This appears similar to a model class in SQLAlchemy ORM. By default, name of Collection in database is the name of Python class with its name converted to lowercase. However, a different name of collection can be specified in meta attribute of Document class."
},
{
"code": null,
"e": 11186,
"s": 11144,
"text": "meta={collection': 'student_collection'}\n"
},
{
"code": null,
"e": 11279,
"s": 11186,
"text": "Now declare object of this class and call save() method to store the document in a database."
},
{
"code": null,
"e": 11321,
"s": 11279,
"text": "s1=Student('A001', 'Tara', 20)\ns1.save()\n"
},
{
"code": null,
"e": 11545,
"s": 11321,
"text": "One of the advantages of MongoDB database is that it supports dynamic schema. To create a class that supports dynamic schema, subclass it from DynamicDocument base class. Following is the Student class with dynamic schema −"
},
{
"code": null,
"e": 11605,
"s": 11545,
"text": ">>> class student(DynamicDocument):\n... name=StringField()\n"
},
{
"code": null,
"e": 11656,
"s": 11605,
"text": "The first step is to add first Document as before."
},
{
"code": null,
"e": 11727,
"s": 11656,
"text": ">>> s1=student()\n>>> s1.name=\"Tara\"\n>>> connect('mydb')\n>>> s1.save()\n"
},
{
"code": null,
"e": 11782,
"s": 11727,
"text": "Now add another attribute to second document and save."
},
{
"code": null,
"e": 11858,
"s": 11782,
"text": ">>> s2=student()\n>>> setattr(s2,'age',20)\n>>> s2.name='Lara'\n>>> s2.save()\n"
},
{
"code": null,
"e": 11939,
"s": 11858,
"text": "In the database, student collection will show two documents with dynamic schema."
},
{
"code": null,
"e": 12047,
"s": 11939,
"text": "The meta dictionary of document class can use a Capped Collection by specifying max_documents and max_size."
},
{
"code": null,
"e": 12143,
"s": 12047,
"text": "max_documents − The maximum number of documents that is allowed to be stored in the collection."
},
{
"code": null,
"e": 12296,
"s": 12143,
"text": "max_size − The maximum size of the collection in bytes. max_size is rounded up to the next multiple of 256 by MongoDB internally and mongoengine before."
},
{
"code": null,
"e": 12391,
"s": 12296,
"text": "If max_size is not specified and max_documents is, max_size defaults to 10485760 bytes (10MB)."
},
{
"code": null,
"e": 12445,
"s": 12391,
"text": "Other parameters of Document class are listed below −"
},
{
"code": null,
"e": 12656,
"s": 12445,
"text": "A MongoEngine document class has one or more attributes. Each attribute is an object of Field class. BaseField is the base class or all field types. The BaseField class constructor has the following arguments −"
},
{
"code": null,
"e": 12717,
"s": 12656,
"text": "BaseField(db_field, required, default, unique, primary_key)\n"
},
{
"code": null,
"e": 12765,
"s": 12717,
"text": "The db_field represents name of database field."
},
{
"code": null,
"e": 12856,
"s": 12765,
"text": "The required parameter decides whether value for this field is required, default is false."
},
{
"code": null,
"e": 12915,
"s": 12856,
"text": "The default parameter contains default value of this field"
},
{
"code": null,
"e": 13032,
"s": 12915,
"text": "The unique parameter is false by default. Set to true if you want this field to have unique value for each document."
},
{
"code": null,
"e": 13112,
"s": 13032,
"text": "The primary_key parameter defaults to false. True makes this field primary key."
},
{
"code": null,
"e": 13172,
"s": 13112,
"text": "There are a number of Field classes derived from BaseField."
},
{
"code": null,
"e": 13321,
"s": 13172,
"text": "IntField (32bit integer), LongField (64 bit integer), FloatField (floating point number) field constructors have min_value and max_value parameters."
},
{
"code": null,
"e": 13486,
"s": 13321,
"text": "There is also DecimalField class. Value of this field’s object is a float whose precision can be specified. Following arguments are defined for DecimalField class −"
},
{
"code": null,
"e": 13557,
"s": 13486,
"text": "DecimalField(min_value, max_value, force_string, precision, rounding)\n"
},
{
"code": null,
"e": 13823,
"s": 13557,
"text": "StringField object can store any Unicode value. You can specify min_length and max_length of the string in the constructor. URLField object is a StringField with capability to validate input as a URL. EmailField validates the string as a valid email representation."
},
{
"code": null,
"e": 13944,
"s": 13823,
"text": "StringField(max-length, min_length)\nURLField(url_regex)\nEmailField(domain_whiltelist, allow_utf8_user, allow_ip_domain)\n"
},
{
"code": null,
"e": 14247,
"s": 13944,
"text": "The domain_whitelist argument contains list of invalid domains which you would not support. If set to True, allow_utf8_user parameter allows the string to contain UTF8 characters as a part of email. The allow_ip_domain parameter is false by default, but if true, it can be a valid IPV4 or IPV6 address."
},
{
"code": null,
"e": 14298,
"s": 14247,
"text": "Following example uses numeric and string fields −"
},
{
"code": null,
"e": 14654,
"s": 14298,
"text": "from mongoengine import *\nconnect('studentDB')\nclass Student(Document):\n studentid = StringField(required=True)\n name = StringField()\n age=IntField(min_value=6, max-value=20)\n percent=DecimalField(precision=2)\n email=EmailField()\ns1=Student()\ns1.studentid='001'\ns1.name='Mohan Lal'\ns1.age=20\ns1.percent=75\ns1.email='mohanlal@gmail.com'\ns1.save()"
},
{
"code": null,
"e": 14734,
"s": 14654,
"text": "When above code is executed, the student collection shows a document as below −"
},
{
"code": null,
"e": 14936,
"s": 14734,
"text": "This type of field wraps any standard field, thus allowing multiple objects to be used as a list object in a database. This field can be used with ReferenceField to implement one to many relationships."
},
{
"code": null,
"e": 15005,
"s": 14936,
"text": "The student document class from above example is modified as below −"
},
{
"code": null,
"e": 15294,
"s": 15005,
"text": "from mongoengine import *\nconnect('studentDB')\nclass Student(Document):\n studentid = StringField(required=True)\n name = StringField(max_length=50)\n subjects = ListField(StringField())\ns1=Student()\ns1.studentid='A001'\ns1.name='Mohan Lal'\ns1.subjects=['phy', 'che', 'maths']\ns1.save()"
},
{
"code": null,
"e": 15350,
"s": 15294,
"text": "The document added is shown in JSON format as follows −"
},
{
"code": null,
"e": 15471,
"s": 15350,
"text": "{\n\"_id\":{\"$oid\":\"5ea6a1f4d8d48409f9640319\"},\n\"studentid\":\"A001\",\n\"name\":\"Mohan Lal\",\n\"subjects\":[\"phy\",\"che\",\"maths\"]\n}\n"
},
{
"code": null,
"e": 15601,
"s": 15471,
"text": "An object of DictField class stores a Python dictionary object. In the corresponding database field as well, this will be stored."
},
{
"code": null,
"e": 15678,
"s": 15601,
"text": "In place of ListField in the above example, we change its type to DictField."
},
{
"code": null,
"e": 15986,
"s": 15678,
"text": "from mongoengine import *\nconnect('studentDB')\nclass Student(Document):\n studentid = StringField(required=True)\n name = StringField(max_length=50)\n subjects = DictField()\ns1=Student()\ns1.studentid='A001'\ns1.name='Mohan Lal'\ns1.subjects['phy']=60\ns1.subjects['che']=70\ns1.subjects['maths']=80\ns1.save()"
},
{
"code": null,
"e": 16032,
"s": 15986,
"text": "Document in the database appears as follows −"
},
{
"code": null,
"e": 16251,
"s": 16032,
"text": "{\n\"_id\":{\"$oid\":\"5ea6cfbe1788374c81ccaacb\"},\n\"studentid\":\"A001\",\n\"name\":\"Mohan Lal\",\n\"subjects\":{\"phy\":{\"$numberInt\":\"60\"},\n \"che\":{\"$numberInt\":\"70\"},\n \"maths\":{\"$numberInt\":\"80\"}\n }\n}"
},
{
"code": null,
"e": 16458,
"s": 16251,
"text": "A MongoDB document can store reference to another document using this type of field. This way, we can implement join as in RDBMS. A ReferenceField constructor uses name of other document class as parameter."
},
{
"code": null,
"e": 16582,
"s": 16458,
"text": "class doc1(Document):\n field1=StringField()\nclass doc2(Document):\n field1=StringField()\n field2=ReferenceField(doc1)\n"
},
{
"code": null,
"e": 16751,
"s": 16582,
"text": "In following example, StudentDB database contains two document classes, student and teacher. Document of Student class contains reference to an object of teacher class."
},
{
"code": null,
"e": 17111,
"s": 16751,
"text": "from mongoengine import *\nconnect('studentDB')\nclass Teacher (Document):\n tid=StringField(required=True)\n name=StringField()\nclass Student(Document):\n sid = StringField(required=True)\n name = StringField()\n tid=ReferenceField(Teacher)\n\nt1=Teacher()\nt1.tid='T1'\nt1.name='Murthy'\nt1.save()\n\ns1=Student()\ns1.sid='S1'\ns1.name='Mohan'\ns1.tid=t1\ns1.save()"
},
{
"code": null,
"e": 17249,
"s": 17111,
"text": "Run above code and verify result in Compass GUI. Two collections corresponding to two document classes are created in StudentDB database."
},
{
"code": null,
"e": 17292,
"s": 17249,
"text": "The teacher document added is as follows −"
},
{
"code": null,
"e": 17367,
"s": 17292,
"text": "{\n\"_id\":{\"$oid\":\"5ead627463976ea5159f3081\"},\n\"tid\":\"T1\",\n\"name\":\"Murthy\"\n}"
},
{
"code": null,
"e": 17418,
"s": 17367,
"text": "The student document shows the contents as below −"
},
{
"code": null,
"e": 17535,
"s": 17418,
"text": "{\n\"_id\":{\"$oid\":\"5ead627463976ea5159f3082\"},\n\"sid\":\"S1\",\n\"name\":\"Mohan\",\n\"tid\":{\"$oid\":\"5ead627463976ea5159f3081\"}\n}"
},
{
"code": null,
"e": 17762,
"s": 17535,
"text": "Note that ReferenceField in Student document stores _id of corresponding Teacher document. When accessed, Student object is automatically turned into a reference, and dereferenced when corresponding Teacher object is accessed."
},
{
"code": null,
"e": 17994,
"s": 17762,
"text": "To add reference to document being defined, use ‘self’ instead of other document class as argument to ReferenceField. It may be noted that use of ReferenceField may cause poor performance as far retrieval of documents is concerned."
},
{
"code": null,
"e": 18154,
"s": 17994,
"text": "The ReferenceField constructor also has one optional argument as reverse_delete_rule. Its value determines what to be done if the referred document is deleted."
},
{
"code": null,
"e": 18191,
"s": 18154,
"text": "The possible values are as follows −"
},
{
"code": null,
"e": 18237,
"s": 18191,
"text": "DO_NOTHING (0) - don’t do anything (default)."
},
{
"code": null,
"e": 18283,
"s": 18237,
"text": "DO_NOTHING (0) - don’t do anything (default)."
},
{
"code": null,
"e": 18328,
"s": 18283,
"text": "NULLIFY (1) - Updates the reference to null."
},
{
"code": null,
"e": 18373,
"s": 18328,
"text": "NULLIFY (1) - Updates the reference to null."
},
{
"code": null,
"e": 18440,
"s": 18373,
"text": "CASCADE (2) - Deletes the documents associated with the reference."
},
{
"code": null,
"e": 18507,
"s": 18440,
"text": "CASCADE (2) - Deletes the documents associated with the reference."
},
{
"code": null,
"e": 18564,
"s": 18507,
"text": "DENY (3) - Prevent the deletion of the reference object."
},
{
"code": null,
"e": 18621,
"s": 18564,
"text": "DENY (3) - Prevent the deletion of the reference object."
},
{
"code": null,
"e": 18682,
"s": 18621,
"text": "PULL (4) - Pull the reference from a ListField of references"
},
{
"code": null,
"e": 18743,
"s": 18682,
"text": "PULL (4) - Pull the reference from a ListField of references"
},
{
"code": null,
"e": 18968,
"s": 18743,
"text": "You can implement one to many relationship using list of references. Assuming that a student document has to be related with one or more teacher documents, the Student class must have a ListField of ReferenceField instances."
},
{
"code": null,
"e": 19388,
"s": 18968,
"text": "from mongoengine import *\nconnect('studentDB')\nclass Teacher (Document):\ntid=StringField(required=True)\nname=StringField()\nclass Student(Document):\n sid = StringField(required=True)\n name = StringField()\n tid=ListField(ReferenceField(Teacher))\nt1=Teacher()\nt1.tid='T1'\nt1.name='Murthy'\nt1.save()\nt2=Teacher()\nt2.tid='T2'\nt2.name='Saxena'\nt2.save()\ns1=Student()\ns1.sid='S1'\ns1.name='Mohan'\ns1.tid=[t1,t2]\ns1.save()"
},
{
"code": null,
"e": 19517,
"s": 19388,
"text": "On verifying result of the above code in Compass, you will find the student document having reference of two teacher documents −"
},
{
"code": null,
"e": 19857,
"s": 19517,
"text": "Teacher Collection\n{\n\"_id\":{\"$oid\":\"5eaebcb61ae527e0db6d15e4\"},\n\"tid\":\"T1\",\"name\":\"Murthy\"\n}\n{\n\"_id\":{\"$oid\":\"5eaebcb61ae527e0db6d15e5\"},\n\"tid\":\"T2\",\"name\":\"Saxena\"\n}\nStudent collection\n{\n\"_id\":{\"$oid\":\"5eaebcb61ae527e0db6d15e6\"},\n\"sid\":\"S1\",\"name\":\"Mohan\",\n\"tid\":[{\"$oid\":\"5eaebcb61ae527e0db6d15e4\"},{\"$oid\":\"5eaebcb61ae527e0db6d15e5\"}]\n}"
},
{
"code": null,
"e": 20220,
"s": 19857,
"text": "An instance of DateTimeField class allows data in date format in MongoDB database. MongoEngine looks for Python-DateUtil library for parsing data in appropriate date format. If it is not available in current installation, date is represented using built-in time module’s time.strptime() function. Default value of field of this type is current datetime instance."
},
{
"code": null,
"e": 20349,
"s": 20220,
"text": "Different and varying type of data can be handled by this field. This type of field is internally used by DynamicDocument class."
},
{
"code": null,
"e": 20534,
"s": 20349,
"text": "This type of field corresponds to field in document that can store an image file. Constructor of this class can accept size and thumbnail_size parameters (both in terms of pixel size)."
},
{
"code": null,
"e": 20707,
"s": 20534,
"text": "We have already used save() method of Document class to add a document in the collection. The save() method can be further customized with the help of following arguments −"
},
{
"code": null,
"e": 20868,
"s": 20707,
"text": "You can set cleaning rules for validation of documents before calling save(). By providing a custom clean() method, you can do any pre validation/data cleaning."
},
{
"code": null,
"e": 21031,
"s": 20868,
"text": "class MyDocument(Document):\n ...\n ...\n \n def clean(self):\n if <condition>==True:\n msg = 'error message.'\n raise ValidationError(msg)\n"
},
{
"code": null,
"e": 21117,
"s": 21031,
"text": "Note that Cleaning is only called if validation is turned on and when calling save()."
},
{
"code": null,
"e": 21211,
"s": 21117,
"text": "Document class also has insert() method to perform bulk insert. It has following parameters −"
},
{
"code": null,
"e": 21493,
"s": 21211,
"text": "If document contains any ReferenceField objects, then by default the save() method will not save any changes to those objects. If you want all references to be saved also, noting each save is a separate query, then passing cascade as True to the save method will cascade any saves."
},
{
"code": null,
"e": 21703,
"s": 21493,
"text": "Deleting a document from its collection is very easy, by calling delete() method. Remember that it will only take effect if the document has been previously saved. The delete() method has following arguments −"
},
{
"code": null,
"e": 21958,
"s": 21703,
"text": "To delete entire collection from database use drop_collecction() method. It drops the entire collection associated with this Document type from the database. The method raises OperationError if the document has no collection set (i.g. if it is abstract)."
},
{
"code": null,
"e": 22307,
"s": 21958,
"text": "The modify() method in document class performs atomic update of the document in the database and reloads its updated version. It returns True if the document has been updated or False if the document in the database does not match the query. Note that all unsaved changes that have been made to the document are rejected if the method returns True."
},
{
"code": null,
"e": 22472,
"s": 22307,
"text": "The connect() function returns a MongoClient object. Using list_database_names() method available to this object, we can retrieve number of databases on the server."
},
{
"code": null,
"e": 22576,
"s": 22472,
"text": "from mongoengine import *\ncon=connect('newdb')\ndbs=con.list_database_names()\nfor db in dbs:\nprint (db)\n"
},
{
"code": null,
"e": 22679,
"s": 22576,
"text": "It is also possible to obtain list of collections in a database, using list_collection_names() method."
},
{
"code": null,
"e": 22782,
"s": 22679,
"text": "collections=con['newdb'].list_collection_names()\nfor collection in collections:\n print (collection)\n"
},
{
"code": null,
"e": 22905,
"s": 22782,
"text": "As mentioned earlier, the Document class has objects attribute that enable access to objects associated with the database."
},
{
"code": null,
"e": 23049,
"s": 22905,
"text": "The newdb database has a products collection corresponding to Document class below. To get all documents, we use objects attribute as follows −"
},
{
"code": null,
"e": 23304,
"s": 23049,
"text": "from mongoengine import *\ncon=connect('newdb')\nclass products (Document):\nProductID=IntField(required=True)\nName=StringField()\nprice=IntField()\nfor product in products.objects:\nprint ('ID:',product.ProductID, 'Name:',product.Name, 'Price:',product.price)"
},
{
"code": null,
"e": 23461,
"s": 23304,
"text": "ID: 1 Name: Laptop Price: 25000\nID: 2 Name: TV Price: 50000\nID: 3 Name: Router Price: 2000\nID: 4 Name: Scanner Price: 5000\nID: 5 Name: Printer Price: 12500\n"
},
{
"code": null,
"e": 23778,
"s": 23461,
"text": "The objects attribute is a QuerySet manager. It creates and returns a QuerySet when accessed. A query can be subjected to filter with the help of field names as keyword arguments. For example, from above products collection, to print details of document with name of product as ‘TV’, we use Name as keyword argument."
},
{
"code": null,
"e": 23901,
"s": 23778,
"text": "for product in products.objects(Name='TV'):\nprint ('ID:',product.ProductID, 'Name:',product.Name, 'Price:',product.price)\n"
},
{
"code": null,
"e": 24040,
"s": 23901,
"text": "You can use filter method of QuerySet object to apply filter to query. Following code snippet also returns product details with name=’TV’."
},
{
"code": null,
"e": 24183,
"s": 24040,
"text": "qset=products.objects\nfor product in qset.filter(Name='TV'):\n print ('ID:',product.ProductID, 'Name:',product.Name, 'Price:',product.price)\n"
},
{
"code": null,
"e": 24288,
"s": 24183,
"text": "In addition to = operator to check equality, the following logical operators are defined in MongoEngine."
},
{
"code": null,
"e": 24362,
"s": 24288,
"text": "These operators must be attached to field name with double underscore __."
},
{
"code": null,
"e": 24424,
"s": 24362,
"text": "To use greater than (gt) operator, use the following format −"
},
{
"code": null,
"e": 24585,
"s": 24424,
"text": "#using greater than operator\nfor product in products.objects(price__gt=10000):\n print ('ID:',product.ProductID, 'Name:',product.Name, 'Price:',product.price)\n"
},
{
"code": null,
"e": 24679,
"s": 24585,
"text": "ID: 1 Name: Laptop Price: 25000\nID: 2 Name: TV Price: 50000\nID: 5 Name: Printer Price: 12500\n"
},
{
"code": null,
"e": 24803,
"s": 24679,
"text": "The in operator is like Python’s in operator. For name of product matching with names in list, the following code is used −"
},
{
"code": null,
"e": 24943,
"s": 24803,
"text": "for product in products.objects(Name__in=['TV', 'Printer']):\nprint ('ID:',product.ProductID, 'Name:',product.Name, 'Price:',product.price)\n"
},
{
"code": null,
"e": 25005,
"s": 24943,
"text": "ID: 2 Name: TV Price: 50000\nID: 5 Name: Printer Price: 12500\n"
},
{
"code": null,
"e": 25104,
"s": 25005,
"text": "You can use following operators as shortcut for regex expressions for applying filter to queries −"
},
{
"code": null,
"e": 25193,
"s": 25104,
"text": "For example, the following code prints product details for name containing ‘o’ in name −"
},
{
"code": null,
"e": 25328,
"s": 25193,
"text": "for product in products.objects(Name__contains='o'):\n print ('ID:',product.ProductID, 'Name:',product.Name, 'Price:',product.price)\n"
},
{
"code": null,
"e": 25392,
"s": 25328,
"text": "ID: 1 Name: Laptop Price: 25000\nID: 3 Name: Router Price: 2000\n"
},
{
"code": null,
"e": 25479,
"s": 25392,
"text": "In another example of string query, the following code displays name ending with ‘er’−"
},
{
"code": null,
"e": 25615,
"s": 25479,
"text": "for product in products.objects(Name__endswith='er'):\n print ('ID:',product.ProductID, 'Name:',product.Name, 'Price:',product.price)\n"
},
{
"code": null,
"e": 25712,
"s": 25615,
"text": "ID: 3 Name: Router Price: 2000\nID: 4 Name: Scanner Price: 5000\nID: 5 Name: Printer Price: 12500\n"
},
{
"code": null,
"e": 25794,
"s": 25712,
"text": "The QuerySet object possesses following useful methods for querying the database."
},
{
"code": null,
"e": 25933,
"s": 25794,
"text": "First document satisfying the query is returned. Following code will return first document in products collection, that has price < 20000."
},
{
"code": null,
"e": 26035,
"s": 25933,
"text": "qset=products.objects(price__lt=20000)\ndoc=qset.first()\nprint ('Name:',doc.Name, 'Price:',doc.price)\n"
},
{
"code": null,
"e": 26061,
"s": 26035,
"text": "Name: Router Price: 2000\n"
},
{
"code": null,
"e": 26261,
"s": 26061,
"text": "This will cause mentioned fields to be excluded from Query Set. Here, to_json() mehod of Document class is used to obtain JSONified version of Document. ProductID field will not appear in the result."
},
{
"code": null,
"e": 26345,
"s": 26261,
"text": "for product in products.objects.exclude('ProductID'):\n print (product.to_json())\n"
},
{
"code": null,
"e": 26742,
"s": 26345,
"text": "{\"_id\": {\"$oid\": \"5c8dec275405c12e3402423c\"}, \"Name\": \"Laptop\", \"price\": 25000}\n{\"_id\": {\"$oid\": \"5c8dec275405c12e3402423d\"}, \"Name\": \"TV\", \"price\": 50000}\n{\"_id\": {\"$oid\": \"5c8dec275405c12e3402423e\"}, \"Name\": \"Router\", \"price\": 2000}\n{\"_id\": {\"$oid\": \"5c8dec275405c12e3402423f\"}, \"Name\": \"Scanner\", \"price\": 5000}\n{\"_id\": {\"$oid\": \"5c8dec275405c12e34024240\"}, \"Name\": \"Printer\", \"price\": 12500}\n"
},
{
"code": null,
"e": 26887,
"s": 26742,
"text": "Use this method to manipulate which fields to load in the query set. Use field names as keyword arguments and set to 1 to include, 0 to exclude."
},
{
"code": null,
"e": 26975,
"s": 26887,
"text": "for product in products.objects.fields(ProductID=1,price=1):\nprint (product.to_json())\n"
},
{
"code": null,
"e": 27364,
"s": 26975,
"text": "{\"_id\": {\"$oid\": \"5c8dec275405c12e3402423c\"}, \"ProductID\": 1, \"price\": 25000}\n{\"_id\": {\"$oid\": \"5c8dec275405c12e3402423d\"}, \"ProductID\": 2, \"price\": 50000}\n{\"_id\": {\"$oid\": \"5c8dec275405c12e3402423e\"}, \"ProductID\": 3, \"price\": 2000}\n{\"_id\": {\"$oid\": \"5c8dec275405c12e3402423f\"}, \"ProductID\": 4, \"price\": 5000}\n{\"_id\": {\"$oid\": \"5c8dec275405c12e34024240\"}, \"ProductID\": 5, \"price\": 12500}\n"
},
{
"code": null,
"e": 27454,
"s": 27364,
"text": "Setting field keyword argument to 0 in fields() method works similar to exclude() method."
},
{
"code": null,
"e": 27530,
"s": 27454,
"text": "for product in products.objects.fields(price=0):\nprint (product.to_json())\n"
},
{
"code": null,
"e": 27929,
"s": 27530,
"text": "{\"_id\": {\"$oid\": \"5c8dec275405c12e3402423c\"}, \"ProductID\": 1, \"Name\": \"Laptop\"}\n{\"_id\": {\"$oid\": \"5c8dec275405c12e3402423d\"}, \"ProductID\": 2, \"Name\": \"TV\"}\n{\"_id\": {\"$oid\": \"5c8dec275405c12e3402423e\"}, \"ProductID\": 3, \"Name\": \"Router\"}\n{\"_id\": {\"$oid\": \"5c8dec275405c12e3402423f\"}, \"ProductID\": 4, \"Name\": \"Scanner\"}\n{\"_id\": {\"$oid\": \"5c8dec275405c12e34024240\"}, \"ProductID\": 5, \"Name\": \"Printer\"}\n"
},
{
"code": null,
"e": 28059,
"s": 27929,
"text": "Effect of this method is similar to fields() method. Fields corresponding to keyword arguments only will appear in the query set."
},
{
"code": null,
"e": 28132,
"s": 28059,
"text": "for product in products.objects.only('Name'):\nprint (product.to_json())\n"
},
{
"code": null,
"e": 28451,
"s": 28132,
"text": "{\"_id\": {\"$oid\": \"5c8dec275405c12e3402423c\"}, \"Name\": \"Laptop\"}\n{\"_id\": {\"$oid\": \"5c8dec275405c12e3402423d\"}, \"Name\": \"TV\"}\n{\"_id\": {\"$oid\": \"5c8dec275405c12e3402423e\"}, \"Name\": \"Router\"}\n{\"_id\": {\"$oid\": \"5c8dec275405c12e3402423f\"}, \"Name\": \"Scanner\"}\n{\"_id\": {\"$oid\": \"5c8dec275405c12e34024240\"}, \"Name\": \"Printer\"}\n"
},
{
"code": null,
"e": 28509,
"s": 28451,
"text": "This method computes sum of given field in the query set."
},
{
"code": null,
"e": 28573,
"s": 28509,
"text": "This method calculates average of given field in the query set."
},
{
"code": null,
"e": 28716,
"s": 28573,
"text": "avg=products.objects.average('price')\nttl=products.objects.sum('price')\nprint ('sum of price field',ttl)\nprint ('average of price field',avg)\n"
},
{
"code": null,
"e": 28773,
"s": 28716,
"text": "sum of price field 94500\naverage of price field 18900.0\n"
},
{
"code": null,
"e": 28885,
"s": 28773,
"text": "QuerySet’s order_by() function is used to obtain the query result in a sorted manner. The usage is as follows −"
},
{
"code": null,
"e": 28913,
"s": 28885,
"text": "Qset.order_by(‘fieldname’)\n"
},
{
"code": null,
"e": 29065,
"s": 28913,
"text": "By default, the sort order is ascending. For descending order, attach – sign to name of field. For example, to get price wise list in ascending order −"
},
{
"code": null,
"e": 29389,
"s": 29065,
"text": "from mongoengine import *\ncon=connect('newdb')\n\nclass products (Document):\n ProductID=IntField(required=True)\n company=StringField()\n Name=StringField()\n price=IntField()\nfor product in products.objects.order_by('price'):\n print (\"Name:{} company:{} price:{}\".format(product.Name, product.company, product.price))"
},
{
"code": null,
"e": 29651,
"s": 29389,
"text": "Name:Router company:Iball price:2000\nName:Scanner company:Cannon price:5000\nName:Printer company:Cannon price:12500\nName:Laptop company:Acer price:25000\nName:TV company:Philips price:31000\nName:Laptop company:Dell price:45000\nName:TV company:Samsung price:50000"
},
{
"code": null,
"e": 29714,
"s": 29651,
"text": "Following code will get the list in descending order of name −"
},
{
"code": null,
"e": 29860,
"s": 29714,
"text": "for product in products.objects.order_by('-Name'):\n print (\"Name:{} company:{} price:{}\".format(product.Name, product.company, product.price))\n"
},
{
"code": null,
"e": 30122,
"s": 29860,
"text": "Name:TV company:Samsung price:50000\nName:TV company:Philips price:31000\nName:Scanner company:Cannon price:5000\nName:Router company:Iball price:2000\nName:Printer company:Cannon price:12500\nName:Laptop company:Acer price:25000\nName:Laptop company:Dell price:45000"
},
{
"code": null,
"e": 30238,
"s": 30122,
"text": "You can also get sorting done on multiple fields. This code will get you companywise, pricelist in ascending order."
},
{
"code": null,
"e": 30394,
"s": 30238,
"text": "for product in products.objects.order_by('company','price'):\n print (\"Name:{} company:{} price:{}\".format(product.Name, product.company, product.price))\n"
},
{
"code": null,
"e": 30656,
"s": 30394,
"text": "Name:Laptop company:Acer price:25000\nName:Scanner company:Cannon price:5000\nName:Printer company:Cannon price:12500\nName:Laptop company:Dell price:45000\nName:Router company:Iball price:2000\nName:TV company:Philips price:31000\nName:TV company:Samsung price:50000"
},
{
"code": null,
"e": 30988,
"s": 30656,
"text": "By default, the objects attribute on a document class returns a QuerySet without applying any filter. However, you can define a classmethod on a document that modifies a queryset. Such a method should accept two arguments – doc_cls and queryset and it needs to be decorated with queryset_manager() in order for it to be recognized."
},
{
"code": null,
"e": 31069,
"s": 30988,
"text": "@queryset_manager\n def qry_method(docs_cls,queryset):\n ....\n ----\n"
},
{
"code": null,
"e": 31419,
"s": 31069,
"text": "In the following example, the document class called products has an expensive_prods() method which is decorated by @queryset_manager. The method itself applies a filter to queryset such that only objects with price >20000 are returned. This method is now the default document query and objects attribute of products class returns filtered documents."
},
{
"code": null,
"e": 31846,
"s": 31419,
"text": "from mongoengine import *\ncon=connect('newdb')\n\nclass products (Document):\n ProductID=IntField(required=True)\n company=StringField()\n Name=StringField()\n price=IntField()\n\n @queryset_manager\n def expensive_prods(docs_cls,queryset):\n return queryset.filter(price__gt=20000)\nfor product in products.expensive_prods():\n print (\"Name:{} company:{} price:{}\".format(product.Name, product.company, product.price))"
},
{
"code": null,
"e": 31993,
"s": 31846,
"text": "Name:Laptop company:Acer price:25000\nName:TV company:Samsung price:50000\nName:TV company:Philips price:31000\nName:Laptop company:Dell price:45000\n"
},
{
"code": null,
"e": 32162,
"s": 31993,
"text": "If you wish to customize methods for filtering documents, first declare a subclass of QuerySet class, and use it as value of queryset_class property in meta dictionary."
},
{
"code": null,
"e": 32435,
"s": 32162,
"text": "The example below uses MyQuerySet class as definition of custom queryset. The myqrymethod() in this class filters the documents whose name field ends with ‘er’. In products class, meta attribute refers to this queryset subclass is used as value of queryset_class property."
},
{
"code": null,
"e": 32895,
"s": 32435,
"text": "from mongoengine import *\ncon=connect('newdb')\nclass MyQuerySet(QuerySet):\n def myqrymethod(self):\n return self.filter(Name__endswith='er')\nclass products (Document):\n meta = {'queryset_class': MyQuerySet}\n ProductID=IntField(required=True)\n company=StringField()\n Name=StringField()\n price=IntField()\nfor product in products.objects.myqrymethod():\n print (\"Name:{} company:{} price:{}\".format(product.Name, product.company, product.price))"
},
{
"code": null,
"e": 33012,
"s": 32895,
"text": "Name:Router company:Iball price:2000\nName:Scanner company:Cannon price:5000\nName:Printer company:Cannon price:12500\n"
},
{
"code": null,
"e": 33200,
"s": 33012,
"text": "An indexed collection results in faster processing of queries. By default, every collection is automatically indexed on _id field. In addition, you can create index on one or more fields."
},
{
"code": null,
"e": 33317,
"s": 33200,
"text": "Using Compass, we can build index very easily. Click on CREATE INDEX button on Indexes tab as shown in figure below−"
},
{
"code": null,
"e": 33455,
"s": 33317,
"text": "A dialog box appears as shown. Choose name of index, field on which to index, order of index (ascending or descending) and other options."
},
{
"code": null,
"e": 33580,
"s": 33455,
"text": "While using MongoEngine, indexes are created by specifying ‘indexes’ key in meta dictionary of definition of Document class."
},
{
"code": null,
"e": 33728,
"s": 33580,
"text": "Value of indexes property is a list of fields. In the following example, we ask documents in student collection be indexed according to name field."
},
{
"code": null,
"e": 34021,
"s": 33728,
"text": "from mongoengine import *\ncon=connect('mydata')\nclass student(Document):\n name=StringField(required=True)\n course=StringField()\n meta = {'indexes':['name']}\n \ns1=student()\ns1.name='Avinash'\ns1.course='DataScience'\ns1.save()\ns2=student()\ns2.name='Anita'\ns2.course='WebDesign'\ns2.save()"
},
{
"code": null,
"e": 34146,
"s": 34021,
"text": "By default, indexing order is ascending. Order may be specified by prepending ‘+’ for ascending or ‘-‘ for descending order."
},
{
"code": null,
"e": 34265,
"s": 34146,
"text": "To create compound index, use a tuple of field names, optionally having + or – symbol attached to indicate sort order."
},
{
"code": null,
"e": 34490,
"s": 34265,
"text": "In the following example, student document class contains definition of compound index on name and course (note - symbol prefixed to course field which means index is built namewise ascending and coursewise descending order."
},
{
"code": null,
"e": 34793,
"s": 34490,
"text": "from mongoengine import *\ncon=connect('mydata')\n\nclass student(Document):\n name=StringField(required=True)\n course=StringField()\n meta = {'indexes':[('name','-course')]}\n\ns1=student()\ns1.name='Avinash'\ns1.course='DataScience'\ns1.save()\ns2=student()\ns2.name='Anita'\ns2.course='WebDesign'\ns2.save()"
},
{
"code": null,
"e": 34838,
"s": 34793,
"text": "MongoDB Compass will show indexes as below −"
},
{
"code": null,
"e": 34907,
"s": 34838,
"text": "Value of ‘indexes’ may be a dictionary of various options as below −"
},
{
"code": null,
"e": 34986,
"s": 34907,
"text": "Following example creates index on name field that expires after 3600 seconds."
},
{
"code": null,
"e": 35236,
"s": 34986,
"text": "from mongoengine import *\ncon=connect('mydata')\n\nclass student(Document):\n name=StringField(required=True)\n course=StringField()\n meta = {'indexes':[{\n 'fields': ['name'],\n 'expireAfterSeconds': 3600\n }\n ]\n}\n"
},
{
"code": null,
"e": 35332,
"s": 35236,
"text": "To specify text index, prefix field name with ‘$’ sign and for hashed index, use ‘#’ as prefix."
},
{
"code": null,
"e": 35504,
"s": 35332,
"text": "Indexes so specified are created automatically as documents are added in the collection. To disable automatic creation, set ‘auto_create_index’ to False in meta attribute."
},
{
"code": null,
"e": 35595,
"s": 35504,
"text": "We have list_indexes() method with Document class that displays list of available indexes."
},
{
"code": null,
"e": 35658,
"s": 35595,
"text": "print (student.list_indexes())\n\n[[('name', 1)], [('_id', 1)]]\n"
},
{
"code": null,
"e": 35795,
"s": 35658,
"text": "To create index on a field not in the meta dictionary, use create_index() method. The following code will create index on course field −"
},
{
"code": null,
"e": 36008,
"s": 35795,
"text": "class student(Document):\nname=StringField(required=True)\ncourse=StringField()\nmeta = {'indexes':[{\n 'fields': ['name'],\n 'expireAfterSeconds': 3600\n }\n]}\nstudent.create_index(['course'])\n"
},
{
"code": null,
"e": 36228,
"s": 36008,
"text": "The term ‘aggregation’ is used for the operation that processes data and returns computed result. Finding sum, count and average on one or more fields of documents in a collection can be called as aggregation functions."
},
{
"code": null,
"e": 36417,
"s": 36228,
"text": "MongoEngine provides aggregate() function that encapsulates PyMongo’s aggregation framework. Aggregation operation uses a collection as input and returns one or more documents as a result."
},
{
"code": null,
"e": 36702,
"s": 36417,
"text": "MongoDB uses concept of data processing pipelines. A pipeline can have multiple stages. Basic stage provides that provide filter and operate like queries. Others provide tools for grouping and/or sorting by one or more fields, string concatenation tasks, array aggregation tools, etc."
},
{
"code": null,
"e": 36762,
"s": 36702,
"text": "Following stages are defined in MongoDB pipeline creation −"
},
{
"code": null,
"e": 37062,
"s": 36762,
"text": "Aggregation expressions use field path to access fields in the input documents. To specify a field path, use a string that prefixes with a dollar sign $$$ the field name. Expression can use one or more Boolean operators ($and, $or, $not) and comparison operators ($eq, $gt, $lt, $gte, $lte and $ne)."
},
{
"code": null,
"e": 37127,
"s": 37062,
"text": "Following arithmetic expressions are also used for aggregation −"
},
{
"code": null,
"e": 37189,
"s": 37127,
"text": "Following string expression can also be used in aggregation −"
},
{
"code": null,
"e": 37303,
"s": 37189,
"text": "To demonstrate how aggregate() function works in MongoEngine, let us first define a Document class called orders."
},
{
"code": null,
"e": 37451,
"s": 37303,
"text": "from mongoengine import *\ncon=connect('mydata')\n\nclass orders(Document):\n custID = StringField()\n amount= IntField()\n status = StringField()\n"
},
{
"code": null,
"e": 37506,
"s": 37451,
"text": "We then add following documents in orders collection −"
},
{
"code": null,
"e": 37671,
"s": 37506,
"text": "The aggregate() function is to be used to find sum of amount field for each custID only when status equals ‘A’. Accordingly, the pipeline is constructed as follows."
},
{
"code": null,
"e": 37837,
"s": 37671,
"text": "First stage in pipeline uses $match to filter documents with status=’A’. Second stage uses $group identifier to group documents on CustID and performs sum of amount."
},
{
"code": null,
"e": 37946,
"s": 37837,
"text": " pipeline = [\n{\"$match\" : {\"status\" : \"A\"}},\n{\"$group\": {\"_id\": \"$custID\", \"total\": {\"$sum\": \"$amount\"}}}\n]\n"
},
{
"code": null,
"e": 38009,
"s": 37946,
"text": "This pipeline is now used as argument to aggregate() function."
},
{
"code": null,
"e": 38054,
"s": 38009,
"text": "docs = orders.objects().aggregate(pipeline)\n"
},
{
"code": null,
"e": 38146,
"s": 38054,
"text": "We can iterate over the document cursor with a for loop. The complete code is given below −"
},
{
"code": null,
"e": 38484,
"s": 38146,
"text": "from mongoengine import *\ncon=connect('mydata')\n\nclass orders(Document):\n custID = StringField()\n amount= IntField()\n status = StringField()\n\npipeline = [\n {\"$match\" : {\"status\" : \"A\"}},\n {\"$group\": {\"_id\": \"$custID\", \"total\": {\"$sum\": \"$amount\"}}}\n ]\ndocs = orders.objects().aggregate(pipeline)\nfor doc in docs:\n print (x)"
},
{
"code": null,
"e": 38540,
"s": 38484,
"text": "For the given data, the following output is generated −"
},
{
"code": null,
"e": 38601,
"s": 38540,
"text": "{'_id': 'B212', 'total': 400}\n{'_id': 'A123', 'total': 750}\n"
},
{
"code": null,
"e": 38964,
"s": 38601,
"text": "In order to get more efficiency in retrieving a subset of fields in a document, use only() method of Objects attribute. This will significantly improve performance especially for fields with extremely large length such as ListField. Pass the required field to only() function. If other fields are accessed after executing only() query, default value is returned."
},
{
"code": null,
"e": 39293,
"s": 38964,
"text": "from mongoengine import *\ncon=connect('newdb')\nclass person (Document):\nname=StringField(required=True)\ncity=StringField(default='Mumbai')\npin=IntField()\np1=person(name='Himanshu', city='Delhi', pin=110012).save()\ndoc=person.objects.only('name').first()\nprint ('name:',doc.name)\nprint ('city:', doc.city)\nprint ('PIN:', doc.pin)"
},
{
"code": null,
"e": 39332,
"s": 39293,
"text": "name: Himanshu\ncity: Mumbai\nPIN: None\n"
},
{
"code": null,
"e": 39440,
"s": 39332,
"text": "Note − The value of city attribute is used as default. As default is not specified for PIN, it prints None."
},
{
"code": null,
"e": 39499,
"s": 39440,
"text": "You may call reload() function if you need missing fields."
},
{
"code": null,
"e": 39841,
"s": 39499,
"text": "When a document class has a ListField or DictField, while iterating through it, any DBREf objects are automatically dereferenced. To increase the efficiency further, especially if the document has ReferenceField, number of queries can be limited by using select_related() function which converts QuerySet in a list and effects dereferencing."
},
{
"code": null,
"e": 40072,
"s": 39841,
"text": "MongoEngine API contains Q class which is useful for constructing advanced queries consisting of number of constraints. Q represents a part of query which can be initialized by keyword argument syntax and binary & and | operators."
},
{
"code": null,
"e": 40131,
"s": 40072,
"text": "person.objects(Q(name__startswith=’H’) &Q(city=’Mumbai’))\n"
},
{
"code": null,
"e": 40769,
"s": 40131,
"text": "It is possible to define an inherited class of any user defined Document class. The inherited class may add extra fields if required. However, since such as a class is not a direct subclass of Document class, it will not create a new collection, instead its objects are stored in a collection used by its parent class. In the parent class, meta attribute ‘allow_inheritance the following example, we first define employee as a document class and set allow_inheritance to true. The salary class is derived from employee, adding two more fields dept and sal. Objects of Employee as well as salary classes are stored in employee collection."
},
{
"code": null,
"e": 41036,
"s": 40769,
"text": "In the following example, we first define employee as a document class and set allow_inheritance to true. The salary class is derived from employee, adding two more fields dept and sal. Objects of Employee as well as salary classes are stored in employee collection."
},
{
"code": null,
"e": 41383,
"s": 41036,
"text": "from mongoengine import *\ncon=connect('newdb')\nclass employee (Document):\nname=StringField(required=True)\nbranch=StringField()\nmeta={'allow_inheritance':True}\nclass salary(employee):\ndept=StringField()\nsal=IntField()\ne1=employee(name='Bharat', branch='Chennai').save()\ns1=salary(name='Deep', branch='Hyderabad', dept='Accounts', sal=25000).save()"
},
{
"code": null,
"e": 41463,
"s": 41383,
"text": "We can verify that two documents are stored in employee collection as follows −"
},
{
"code": null,
"e": 41723,
"s": 41463,
"text": "{\n\"_id\":{\"$oid\":\"5ebc34f44baa3752530b278a\"},\n\"_cls\":\"employee\",\n\"name\":\"Bharat\",\n\"branch\":\"Chennai\"\n}\n{\n\"_id\":{\"$oid\":\"5ebc34f44baa3752530b278b\"},\n\"_cls\":\"employee.salary\",\n\"name\":\"Deep\",\n\"branch\":\"Hyderabad\",\n\"dept\":\"Accounts\",\n\"sal\":{\"$numberInt\":\"25000\"}\n}"
},
{
"code": null,
"e": 41874,
"s": 41723,
"text": "Note that, in order to identify the respective Document class, MongoEngine adds a “_cls” field and sets its value as \"employee\" and \"employee.salary\"."
},
{
"code": null,
"e": 42144,
"s": 41874,
"text": "If you want to provide extra functionality to a group of Document classes, but without overhead of inheritance, you can first create an abstract class and then derive one or more classes from the same. To make a class abstract, meta attribute ‘abstract’ is set to True."
},
{
"code": null,
"e": 42435,
"s": 42144,
"text": "from mongoengine import *\ncon=connect('newdb')\n\nclass shape (Document):\n meta={'abstract':True}\n def area(self):\n pass\n\nclass rectangle(shape):\n width=IntField()\n height=IntField()\n def area(self):\n return self.width*self.height\n\nr1=rectangle(width=20, height=30).save()"
},
{
"code": null,
"e": 42737,
"s": 42435,
"text": "Atomicity is one of the ACID transaction properties. A database transaction has to be indivisible and irreducible so that it either occurs completely or doesn’t occur at all. This property is called Atomicity. MongoDB supports Atomicity only on single documents and not on multi-document transactions."
},
{
"code": null,
"e": 42814,
"s": 42737,
"text": "MongoEngine provides the following methods for atomic updates on a queryset."
},
{
"code": null,
"e": 42881,
"s": 42814,
"text": "update_one() − Overwrites or adds first document matched by query."
},
{
"code": null,
"e": 42943,
"s": 42881,
"text": "update() − Performs atomic update on fields matched by query."
},
{
"code": null,
"e": 42987,
"s": 42943,
"text": "modify() − Update a document and return it."
},
{
"code": null,
"e": 43091,
"s": 42987,
"text": "Following modifiers may be used with these methods. (These modifiers come before the field, not after)."
},
{
"code": null,
"e": 43209,
"s": 43091,
"text": "The following is an example of atomic update, we first create a Document class called tests and add a document in it."
},
{
"code": null,
"e": 43421,
"s": 43209,
"text": "from mongoengine import *\ncon=connect('newdb')\n\nclass tests (Document):\n name=StringField()\n attempts=IntField()\n scores=ListField(IntField())\n\nt1=tests()\nt1.name='XYZ'\nt1.attempts=0\nt1.scores=[]\nt1.save()"
},
{
"code": null,
"e": 43494,
"s": 43421,
"text": "Let us use update_one() method to update name field from XYZ to MongoDB."
},
{
"code": null,
"e": 43552,
"s": 43494,
"text": "tests.objects(name='XYZ').update_one(set__name='MongoDB')"
},
{
"code": null,
"e": 43613,
"s": 43552,
"text": "The push modifier is used to add data in ListField (scores)."
},
{
"code": null,
"e": 43671,
"s": 43613,
"text": "tests.objects(name='MongoDB').update_one(push__scores=50)"
},
{
"code": null,
"e": 43732,
"s": 43671,
"text": "To increment attempts field by one, we can use inc modifier."
},
{
"code": null,
"e": 43790,
"s": 43732,
"text": "tests.objects(name='MongoDB').update_one(inc__attempts=1)"
},
{
"code": null,
"e": 43830,
"s": 43790,
"text": "The updated document looks as follows −"
},
{
"code": null,
"e": 43957,
"s": 43830,
"text": "{\n\"_id\":{\"$oid\":\"5ebcf8d353a48858e01ced04\"},\n\"name\":\"MongoDB\",\n\"attempts\":{\"$numberInt\":\"1\"},\n\"scores\":[{\"$numberInt\":\"50\"}]\n}"
},
{
"code": null,
"e": 44125,
"s": 43957,
"text": "QuerySet object of MongoEngine has exec_js() method that allows execution of a Javascript function on MongoDB server. This function processes the following arguments −"
},
{
"code": null,
"e": 44165,
"s": 44125,
"text": "exec_js(code, *field_names, **options)\n"
},
{
"code": null,
"e": 44172,
"s": 44165,
"text": "Where,"
},
{
"code": null,
"e": 44226,
"s": 44172,
"text": "code − a string containing Javascript code to execute"
},
{
"code": null,
"e": 44280,
"s": 44226,
"text": "code − a string containing Javascript code to execute"
},
{
"code": null,
"e": 44352,
"s": 44280,
"text": "fields − to be used in your function, which will be passed as arguments"
},
{
"code": null,
"e": 44424,
"s": 44352,
"text": "fields − to be used in your function, which will be passed as arguments"
},
{
"code": null,
"e": 44534,
"s": 44424,
"text": "options − options that you want available to the function (accessed in Javascript through the options object)"
},
{
"code": null,
"e": 44644,
"s": 44534,
"text": "options − options that you want available to the function (accessed in Javascript through the options object)"
},
{
"code": null,
"e": 44742,
"s": 44644,
"text": "In addition, some more variables are also made available to the function’s scope as given below −"
},
{
"code": null,
"e": 44892,
"s": 44742,
"text": "collection − name of the collection corresponding to the Document class. This should be used to get the Collection object from db in Javascript code."
},
{
"code": null,
"e": 45042,
"s": 44892,
"text": "collection − name of the collection corresponding to the Document class. This should be used to get the Collection object from db in Javascript code."
},
{
"code": null,
"e": 45189,
"s": 45042,
"text": "query − the query that has been generated by the QuerySet object; passed into the find() method on a Collection object in the Javascript function."
},
{
"code": null,
"e": 45336,
"s": 45189,
"text": "query − the query that has been generated by the QuerySet object; passed into the find() method on a Collection object in the Javascript function."
},
{
"code": null,
"e": 45412,
"s": 45336,
"text": "options − an object containing the keyword arguments passed into exec_js()."
},
{
"code": null,
"e": 45488,
"s": 45412,
"text": "options − an object containing the keyword arguments passed into exec_js()."
},
{
"code": null,
"e": 45645,
"s": 45488,
"text": "Note that attributes in MongoEngine document class may use different names in the database (set using the db_field keyword argument to a Field constructor)."
},
{
"code": null,
"e": 45713,
"s": 45645,
"text": "class BlogPost(Document):\ntitle = StringField(db_field='doctitle')\n"
},
{
"code": null,
"e": 45842,
"s": 45713,
"text": "For this purpose, a mechanism exists for replacing MongoEngine field attribute with the database field names in Javascript code."
},
{
"code": null,
"e": 46072,
"s": 45842,
"text": "When accessing a field on a collection object, use square-bracket notation, and prefix the MongoEngine field name with a tilde (~) symbol. The field name that follows the tilde will be translated to the name used in the database."
},
{
"code": null,
"e": 46097,
"s": 46072,
"text": "document': doc[~title];\n"
},
{
"code": null,
"e": 46296,
"s": 46097,
"text": "Note that when Javascript code refers to fields on embedded documents, the name of the EmbeddedDocumentField, followed by a dot, should be used before the name of the field on the embedded document."
},
{
"code": null,
"e": 46570,
"s": 46296,
"text": "In MongoDB, the files with size larger than 16 MB are stored using GridFS specifications. A file is divided into multiple chunks each with a default size of 255KB. Large chunk may be as large as necessary. GridFS uses two collections, one for chunks and other for metadata."
},
{
"code": null,
"e": 46682,
"s": 46570,
"text": "GridFS may be used to store any file if you want to access it without having to load it entirely in the memory."
},
{
"code": null,
"e": 46885,
"s": 46682,
"text": "MongoEngine API supports GridFS through FileField object. Using this object, it is possible to insert and retrieve data. The FileField object’s put() method helps writing the file as a part of Document."
},
{
"code": null,
"e": 47155,
"s": 46885,
"text": "from mongoengine import *\ncon=connect('newdb')\n\nclass lang (Document):\n name=StringField()\n developer=StringField()\n logo=FileField()\n\nl1=lang()\nl1.name='Python'\nl1.developer='Van Rossum'\nf=open('pylogo.png','rb')\nl1.logo.put(f,content_type='image/png')\nl1.save()"
},
{
"code": null,
"e": 47236,
"s": 47155,
"text": "Contents of FileField can be retrieved by read() method of Python’s File object."
},
{
"code": null,
"e": 47258,
"s": 47236,
"text": "logo = l1.logo.read()"
},
{
"code": null,
"e": 47315,
"s": 47258,
"text": "There is also delete() method to delete the stored file."
},
{
"code": null,
"e": 47384,
"s": 47315,
"text": "l1 = lang.objects(name='Python').first()\nl1.logo.delete()\nl1.save()\n"
},
{
"code": null,
"e": 47527,
"s": 47384,
"text": "Note that the FileField stores only the ID of file in a separate GridFS collection. Hence delete() method does not delete the file physically."
},
{
"code": null,
"e": 47604,
"s": 47527,
"text": "The replace() method helps in replacing reference of file with another file."
},
{
"code": null,
"e": 47726,
"s": 47604,
"text": "l1 = lang.objects(name='Python').first()\nf=open('newlogo.png','rb')\nl1.logo.replace(f,content_type='image/png')\nl1.save()"
},
{
"code": null,
"e": 47932,
"s": 47726,
"text": "Signals are events dispatched by a sender object, any number of receiver objects can subscribe to such events. A signal receiver can subscribe to a specific sender or may receive signals from many senders."
},
{
"code": null,
"e": 48125,
"s": 47932,
"text": "In MongoEngine, signal handling is supported by blinker library, which means you need to install it using pip utility. The mongoengine.signals module has the definitions of following signals −"
},
{
"code": null,
"e": 48317,
"s": 48125,
"text": "An event handler function is then attached to Document class. Note that EmbeddedDocument only supports pre/post_init signals. pre/post_save, etc., should be attached to Document’s class only."
},
{
"code": null,
"e": 48469,
"s": 48317,
"text": "You can also use a decorator to quickly create a number of signals and attach them to your Document or EmbeddedDocument subclasses as class decorators."
},
{
"code": null,
"e": 48628,
"s": 48469,
"text": "In the following example, used as demonstration of signal handlers, we also use Python’s standard library module – logging and set the logging level to debug."
},
{
"code": null,
"e": 48742,
"s": 48628,
"text": "from mongoengine import *\nfrom mongoengine import signals\nimport logging\nlogging.basicConfig(level=logging.DEBUG)"
},
{
"code": null,
"e": 49010,
"s": 48742,
"text": "We then write a document class so that corresponding collection is created in newdb database. Inside the class, two class mehods pre_save() and post_save() methods are defined which are intended to be invoked before and after a document is saved in Author collection."
},
{
"code": null,
"e": 49501,
"s": 49010,
"text": "class Author(Document):\n name = StringField()\n \n def __unicode__(self):\n return self.name\n\n @classmethod\n def pre_save(cls, sender, document, **kwargs):\n logging.debug(\"Pre Save: %s\" % document.name)\n\n @classmethod\n def post_save(cls, sender, document, **kwargs):\n logging.debug(\"Post Save: %s\" % document.name)\n if 'created' in kwargs:\n if kwargs['created']:\n logging.debug(\"Created\")\n else:\n logging.debug(\"Updated\")"
},
{
"code": null,
"e": 49634,
"s": 49501,
"text": "Both the class methods are defined with arguments for classname, sender object and document with optional list of keyword arguments."
},
{
"code": null,
"e": 49676,
"s": 49634,
"text": "Finally, we register the signal handlers."
},
{
"code": null,
"e": 49793,
"s": 49676,
"text": "signals.pre_save.connect(Author.pre_save, sender=Author)\nsignals.post_save.connect(Author.post_save, sender=Author)\n"
},
{
"code": null,
"e": 49942,
"s": 49793,
"text": "As we create an instance of Document subclass, the console log will show the pre and post save signals being processed by respective event handlers."
},
{
"code": null,
"e": 49973,
"s": 49942,
"text": "Author(name=\"Lathkar\").save()\n"
},
{
"code": null,
"e": 50021,
"s": 49973,
"text": "Python console reports the log as shown below −"
},
{
"code": null,
"e": 50100,
"s": 50021,
"text": "DEBUG:root:Pre Save: Lathkar\nDEBUG:root:Post Save: Lathkar\nDEBUG:root:Created\n"
},
{
"code": null,
"e": 50498,
"s": 50100,
"text": "MongoDB supports use of query operators that can perform text search on a string content. As described earlier, to set a text index prefix name of index with $ symbol. For a text index, the weight of an indexed field denotes the significance of the field relative to the other indexed fields in terms of the text search score. You can also specify default language in meta dictionary of the class."
},
{
"code": null,
"e": 50743,
"s": 50498,
"text": "List of supported languages can be found at https://docs.mongodb.com/manual/reference/text-search-languages/\nMongoEngine API consists of search_text() method for QuerySet object. The string to be searched in indexed fields is given as argument."
},
{
"code": null,
"e": 50936,
"s": 50743,
"text": "In the following example, we first define a Document class called lang with two string fields, name of language and its features. We also create indexes on both fields with respective weights."
},
{
"code": null,
"e": 51525,
"s": 50936,
"text": "from mongoengine import *\ncon=connect('newdb')\n\nclass lang (Document):\n name=StringField()\n features=StringField()\n meta = {'indexes': [\n {'fields': ['$name', \"$features\"],\n 'default_language': 'english',\n 'weights': {'name': 2, 'features': 10}\n }]\n }\n\nl1=lang()\nl1.name='C++'\nl1.features='Object oriented language for OS development'\nl1.save()\nl2=lang()\nl2.name='Python'\nl2.features='dynamically typed and object oriented for data science, AI and ML'\nl2.save()\nl3=lang()\nl3.name='HTML'\nl3.features='scripting language for web page development'\nl3.save()"
},
{
"code": null,
"e": 51617,
"s": 51525,
"text": "In order to perform search for word ‘oriented’, we employ search_text() method as follows −"
},
{
"code": null,
"e": 51697,
"s": 51617,
"text": "docs=lang.objects.search_text('oriented')\nfor doc in docs:\n print (doc.name)\n"
},
{
"code": null,
"e": 51831,
"s": 51697,
"text": "Output of the above code will be names of languages in whose description the word ‘oriented’ occurs (‘Python and ‘C++’ in this case)."
},
{
"code": null,
"e": 51897,
"s": 51831,
"text": "MongoEngine integrates beautifully with the following libraries −"
},
{
"code": null,
"e": 52164,
"s": 51897,
"text": "marshmallow is an ORM/ODM/framework independent serialization/deserialization library for converting complex datatypes, such as objects, to and from native Python datatypes. Using this extension of MongoEngine, we can easily perform serialize/deserialize operations."
},
{
"code": null,
"e": 52217,
"s": 52164,
"text": "First, create a Document class as usual as follows −"
},
{
"code": null,
"e": 52292,
"s": 52217,
"text": "import mongoengine as me\nclass Book(me.Document):\ntitle = me.StringField()"
},
{
"code": null,
"e": 52347,
"s": 52292,
"text": "Then generate marshmallow schema with the code below −"
},
{
"code": null,
"e": 52480,
"s": 52347,
"text": "from marshmallow_mongoengine import ModelSchema\nclass BookSchema(ModelSchema):\n class Meta:\n model = Book\n\nb_s = BookSchema()"
},
{
"code": null,
"e": 52512,
"s": 52480,
"text": "Save a document using the code:"
},
{
"code": null,
"e": 52558,
"s": 52512,
"text": "book = Book(title='MongoEngine Book').save()\n"
},
{
"code": null,
"e": 52647,
"s": 52558,
"text": "And perform serialization/deserialization using dump(0 and load() using the code below −"
},
{
"code": null,
"e": 52695,
"s": 52647,
"text": "data = b_s.dump(book).data\nb_s.load(data).data\n"
},
{
"code": null,
"e": 52912,
"s": 52695,
"text": "This is a Flask extension that provides integration with MongoEngine. Connection management of MongoDB database for your app is handled easily by this library. You can also use WTForms as model forms for your models."
},
{
"code": null,
"e": 53012,
"s": 52912,
"text": "After installation of flask-mongoengine package, initialize flask app with the following settings −"
},
{
"code": null,
"e": 53219,
"s": 53012,
"text": "from flask import Flask\nfrom flask_mongoengine import MongoEngine\n\napp = Flask(__name__)\napp.config['MONGODB_SETTINGS'] = {\n 'db': 'mydata',\n 'host': 'localhost',\n 'port':27017\n}\ndb = MongoEngine(app)"
},
{
"code": null,
"e": 53275,
"s": 53219,
"text": "Then define a Document sub class using the below code −"
},
{
"code": null,
"e": 53336,
"s": 53275,
"text": "class book(me.Document):\nname=me.StringField(required=True)\n"
},
{
"code": null,
"e": 53428,
"s": 53336,
"text": "Declare an object of above class and call save() method when a particular route is visited."
},
{
"code": null,
"e": 53529,
"s": 53428,
"text": "@app.route('/')\ndef index():\nb1=book(name='Introduction to MongoEngine')\nb1.save()\nreturn 'success'\n"
},
{
"code": null,
"e": 53600,
"s": 53529,
"text": "This extension contains additional Field Types and any other wizardry."
},
{
"code": null,
"e": 53776,
"s": 53600,
"text": "Eve is an open source Python REST API framework designed for human beings. It allows to effortlessly build and deploy highly customizable, fully featured RESTful Web Services."
},
{
"code": null,
"e": 53926,
"s": 53776,
"text": "Eve is powered by Flask and Cerberus and it offers native support for MongoDB data stores. Eve-MongoEngine provides MongoEngine integration with Eve."
},
{
"code": null,
"e": 53982,
"s": 53926,
"text": "Install and import the extension using the code below −"
},
{
"code": null,
"e": 54065,
"s": 53982,
"text": "import mongoengine\nfrom eve import Eve\nfrom eve_mongoengine import EveMongoengine\n"
},
{
"code": null,
"e": 54121,
"s": 54065,
"text": "Configure the settings and initialize the Eve instance."
},
{
"code": null,
"e": 54285,
"s": 54121,
"text": "my_settings = {\n'MONGO_HOST': 'localhost',\n'MONGO_PORT': 27017,\n'MONGO_DBNAME': 'eve_db'\napp = Eve(settings=my_settings)\n# init extension\next = EveMongoengine(app)"
},
{
"code": null,
"e": 54326,
"s": 54285,
"text": "Define a Document class as shown below −"
},
{
"code": null,
"e": 54425,
"s": 54326,
"text": "class Person(mongoengine.Document):\nname = mongoengine.StringField()\nage = mongoengine.IntField()\n"
},
{
"code": null,
"e": 54495,
"s": 54425,
"text": "Add the model and run the application, finally using the below code −"
},
{
"code": null,
"e": 54528,
"s": 54495,
"text": "ext.add_model(Person)\napp.run()\n"
},
{
"code": null,
"e": 54680,
"s": 54528,
"text": "This extension aims to integrate MongoEngine with Django API, a very popular Python web development framework. This project is still under development."
},
{
"code": null,
"e": 54687,
"s": 54680,
"text": " Print"
},
{
"code": null,
"e": 54698,
"s": 54687,
"text": " Add Notes"
}
] |
How to add hours and minutes to a date with JavaScript?
|
To add hours and minutes to a date, use the setHours() and setMinutes() method in JavaScript.
You can try to run the following code to add hours and minutes −
<html>
<head>
<title>JavaScript Dates</title>
</head>
<body>
<script>
var dt = new Date();
document.write("Current Date: "+dt);
dt.setHours(dt.getHours() + 2);
dt.setMinutes(dt.getMinutes() + 20);
document.write("<br>Updated Date: "+dt);
</script>
</body>
</html>
|
[
{
"code": null,
"e": 1156,
"s": 1062,
"text": "To add hours and minutes to a date, use the setHours() and setMinutes() method in JavaScript."
},
{
"code": null,
"e": 1221,
"s": 1156,
"text": "You can try to run the following code to add hours and minutes −"
},
{
"code": null,
"e": 1560,
"s": 1221,
"text": "<html>\n <head>\n <title>JavaScript Dates</title>\n </head>\n <body>\n <script>\n var dt = new Date();\n document.write(\"Current Date: \"+dt);\n dt.setHours(dt.getHours() + 2);\n dt.setMinutes(dt.getMinutes() + 20);\n document.write(\"<br>Updated Date: \"+dt);\n </script>\n </body>\n</html>"
}
] |
Java Program to add Combo Box to JTable
|
Use the JComboBox to add a combo box to a table -
JComboBox<String> comboBox = new JComboBox<>();
Now, add the combo box items -
comboBox.addItem("Asia");
comboBox.addItem("Europe");
comboBox.addItem("North America");
comboBox.addItem("South America");
Now, use the TableColumn and set the column wherein you want to set the above ComboBox items -
TableColumn testColumn = table.getColumnModel().getColumn(0);
Set the editor with the combo box -
testColumn.setCellEditor(new DefaultCellEditor(comboBox));
The following is an example to add JComboBox to JTable:
package my;
import java.awt.Color;
import java.awt.Font;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
public class SwingDemo {
public static void main(String[] argv) throws Exception {
JTable table = new JTable(5, 5);
Font font = new Font("Verdana", Font.PLAIN, 12);
table.setFont(font);
table.setRowHeight(30);
table.setBackground(Color.orange);
table.setForeground(Color.white);
TableColumn testColumn = table.getColumnModel().getColumn(0);
JComboBox<String> comboBox = new JComboBox<>();
comboBox.addItem("Asia");
comboBox.addItem("Europe");
comboBox.addItem("North America");
comboBox.addItem("South America");
comboBox.addItem("Africa");
comboBox.addItem("Antartica");
comboBox.addItem("Australia");
testColumn.setCellEditor(new DefaultCellEditor(comboBox));
JFrame frame = new JFrame();
frame.setSize(600, 400);
frame.add(new JScrollPane(table));
frame.setVisible(true);
}
}
The output is as follows displaying JComboBox in JTable -
|
[
{
"code": null,
"e": 1112,
"s": 1062,
"text": "Use the JComboBox to add a combo box to a table -"
},
{
"code": null,
"e": 1160,
"s": 1112,
"text": "JComboBox<String> comboBox = new JComboBox<>();"
},
{
"code": null,
"e": 1191,
"s": 1160,
"text": "Now, add the combo box items -"
},
{
"code": null,
"e": 1315,
"s": 1191,
"text": "comboBox.addItem(\"Asia\");\ncomboBox.addItem(\"Europe\");\ncomboBox.addItem(\"North America\");\ncomboBox.addItem(\"South America\");"
},
{
"code": null,
"e": 1410,
"s": 1315,
"text": "Now, use the TableColumn and set the column wherein you want to set the above ComboBox items -"
},
{
"code": null,
"e": 1472,
"s": 1410,
"text": "TableColumn testColumn = table.getColumnModel().getColumn(0);"
},
{
"code": null,
"e": 1508,
"s": 1472,
"text": "Set the editor with the combo box -"
},
{
"code": null,
"e": 2816,
"s": 1508,
"text": "testColumn.setCellEditor(new DefaultCellEditor(comboBox));\nThe following is an example to add JComboBox to JTable:\npackage my;\nimport java.awt.Color;\nimport java.awt.Font;\nimport javax.swing.DefaultCellEditor;\nimport javax.swing.JComboBox;\nimport javax.swing.JFrame;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTable;\nimport javax.swing.table.JTableHeader;\nimport javax.swing.table.TableColumn;\npublic class SwingDemo {\n public static void main(String[] argv) throws Exception {\n JTable table = new JTable(5, 5);\n Font font = new Font(\"Verdana\", Font.PLAIN, 12);\n table.setFont(font);\n table.setRowHeight(30);\n table.setBackground(Color.orange);\n table.setForeground(Color.white);\n TableColumn testColumn = table.getColumnModel().getColumn(0);\n JComboBox<String> comboBox = new JComboBox<>();\n comboBox.addItem(\"Asia\");\n comboBox.addItem(\"Europe\");\n comboBox.addItem(\"North America\");\n comboBox.addItem(\"South America\");\n comboBox.addItem(\"Africa\");\n comboBox.addItem(\"Antartica\");\n comboBox.addItem(\"Australia\");\n testColumn.setCellEditor(new DefaultCellEditor(comboBox));\n JFrame frame = new JFrame();\n frame.setSize(600, 400);\n frame.add(new JScrollPane(table));\n frame.setVisible(true);\n }\n}"
},
{
"code": null,
"e": 2874,
"s": 2816,
"text": "The output is as follows displaying JComboBox in JTable -"
}
] |
Find all the names beginning with the letter 'a' or ‘b’ or ‘c’ using MySQL query?
|
You need to use LIKE with OR operator to find all the names that starts with a or b or c. The syntax is as follows:
SELECT *FROM yourTableName WHERE yourColumnName like 'A%' or yourColumnName like 'B%' or yourColumnName like 'C%';
The above query finds all names that starts only with the letter ‘a’ or ‘b’ or ‘c’. To understand the above syntax, let us create a table. The query to create a table is as follows:
mysql> create table AllNamesStartWithAorBorC
-> (
-> Id int NOT NULL AUTO_INCREMENT,
-> EmployeeName varchar(20),
-> PRIMARY KEY(Id)
-> );
Query OK, 0 rows affected (0.70 sec)
Insert some records in the table using insert command. The query is as follows:
mysql> insert into AllNamesStartWithAorBorC(EmployeeName) values('Adam');
Query OK, 1 row affected (0.19 sec)
mysql> insert into AllNamesStartWithAorBorC(EmployeeName) values('Bob');
Query OK, 1 row affected (0.16 sec)
mysql> insert into AllNamesStartWithAorBorC(EmployeeName) values('baden');
Query OK, 1 row affected (0.48 sec)
mysql> insert into AllNamesStartWithAorBorC(EmployeeName) values('Carol');
Query OK, 1 row affected (0.41 sec)
mysql> insert into AllNamesStartWithAorBorC(EmployeeName) values('Mike');
Query OK, 1 row affected (0.13 sec)
mysql> insert into AllNamesStartWithAorBorC(EmployeeName) values('Larry');
Query OK, 1 row affected (0.16 sec)
mysql> insert into AllNamesStartWithAorBorC(EmployeeName) values('Chris');
Query OK, 1 row affected (0.18 sec)
Display all records from the table using select statement. The query is as follows:
mysql> select *from AllNamesStartWithAorBorC;
The following is the output:
+----+--------------+
| Id | EmployeeName |
+----+--------------+
| 1 | Adam |
| 2 | Bob |
| 3 | baden |
| 4 | Carol |
| 5 | Mike |
| 6 | Larry |
| 7 | Chris |
+----+--------------+
7 rows in set (0.00 sec)
Here is the query to find names that begins with a or b or c. The query is as follows:
mysql> select *from AllNamesStartWithAorBorC where EmployeeName like 'A%' or EmployeeName like 'B%' or
-> EmployeeName like 'C%';
The following is the output:
+----+--------------+
| Id | EmployeeName |
+----+--------------+
| 1 | Adam |
| 2 | Bob |
| 3 | baden |
| 4 | Carol |
| 7 | Chris |
+----+--------------+
5 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1178,
"s": 1062,
"text": "You need to use LIKE with OR operator to find all the names that starts with a or b or c. The syntax is as follows:"
},
{
"code": null,
"e": 1293,
"s": 1178,
"text": "SELECT *FROM yourTableName WHERE yourColumnName like 'A%' or yourColumnName like 'B%' or yourColumnName like 'C%';"
},
{
"code": null,
"e": 1475,
"s": 1293,
"text": "The above query finds all names that starts only with the letter ‘a’ or ‘b’ or ‘c’. To understand the above syntax, let us create a table. The query to create a table is as follows:"
},
{
"code": null,
"e": 1666,
"s": 1475,
"text": "mysql> create table AllNamesStartWithAorBorC\n -> (\n -> Id int NOT NULL AUTO_INCREMENT,\n -> EmployeeName varchar(20),\n -> PRIMARY KEY(Id)\n -> );\nQuery OK, 0 rows affected (0.70 sec)"
},
{
"code": null,
"e": 1746,
"s": 1666,
"text": "Insert some records in the table using insert command. The query is as follows:"
},
{
"code": null,
"e": 2519,
"s": 1746,
"text": "mysql> insert into AllNamesStartWithAorBorC(EmployeeName) values('Adam');\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into AllNamesStartWithAorBorC(EmployeeName) values('Bob');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into AllNamesStartWithAorBorC(EmployeeName) values('baden');\nQuery OK, 1 row affected (0.48 sec)\nmysql> insert into AllNamesStartWithAorBorC(EmployeeName) values('Carol');\nQuery OK, 1 row affected (0.41 sec)\nmysql> insert into AllNamesStartWithAorBorC(EmployeeName) values('Mike');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into AllNamesStartWithAorBorC(EmployeeName) values('Larry');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into AllNamesStartWithAorBorC(EmployeeName) values('Chris');\nQuery OK, 1 row affected (0.18 sec)"
},
{
"code": null,
"e": 2603,
"s": 2519,
"text": "Display all records from the table using select statement. The query is as follows:"
},
{
"code": null,
"e": 2649,
"s": 2603,
"text": "mysql> select *from AllNamesStartWithAorBorC;"
},
{
"code": null,
"e": 2678,
"s": 2649,
"text": "The following is the output:"
},
{
"code": null,
"e": 2945,
"s": 2678,
"text": "+----+--------------+\n| Id | EmployeeName |\n+----+--------------+\n| 1 | Adam |\n| 2 | Bob |\n| 3 | baden |\n| 4 | Carol |\n| 5 | Mike |\n| 6 | Larry |\n| 7 | Chris |\n+----+--------------+\n7 rows in set (0.00 sec)"
},
{
"code": null,
"e": 3032,
"s": 2945,
"text": "Here is the query to find names that begins with a or b or c. The query is as follows:"
},
{
"code": null,
"e": 3165,
"s": 3032,
"text": "mysql> select *from AllNamesStartWithAorBorC where EmployeeName like 'A%' or EmployeeName like 'B%' or\n -> EmployeeName like 'C%';"
},
{
"code": null,
"e": 3194,
"s": 3165,
"text": "The following is the output:"
},
{
"code": null,
"e": 3417,
"s": 3194,
"text": "+----+--------------+\n| Id | EmployeeName |\n+----+--------------+\n| 1 | Adam |\n| 2 | Bob |\n| 3 | baden |\n| 4 | Carol |\n| 7 | Chris |\n+----+--------------+\n5 rows in set (0.00 sec)"
}
] |
Deletion of head and tail element logic in a linked list using C language.
|
Linked lists use dynamic memory allocation i.e. they grow and shrink accordingly. It is collection of nodes.
Node has two parts, which are data and link. These are explained below.
There are three types of operations on linked lists which are as follows −
Insertion
Deletion
Traversing
Identify the node.
Adjust the links in such a way that deallocation of the nodes does not make the list as unconnected components.
Return/display element to delete.
Deallocate the memory.
Follow the steps given below to delete a head element in C programming language.
1. void del_head()
2. {
3. int x;
Node *temp;
4. if(Head==NULL)
5. {
6. printf("List is empty");
7. return;
8. }
9. x=Head->ele;
10. temp=Head;
11. if(Head==Tail)
12. Head=Tail=NULL:
13. Else
14. Head=Head->next;
15. printf("Deleted element %d",x);
16. free(temp);
17. }
Here,
Step 4 − Checks for list empty or not.
Step 9 − Reads an element to delete.
Step 10 − Head referred by temp pointer.
Step 11 − Checks for last deletion.
Step 14 − Move head pointer to next element in the list.
Step 15 − Displays element to delete.
Step 16 − Deallocate the memory.
Follow the steps given below to delete a tail element in C programming language.
1. void del_tail()
2. {
3. int x;
4. Node *temp;
5. if(Head==NULL)
6. {
7. printf("List is empty");
8. return;
9. }
10. temp=Head;
11. while(temp->next !=Tail)
12. temp=temp->next;
13. x=Tail->ele;
14. Tail=temp;
15. Temp=temp->next
16. Tail->next=NULL;
17. printf("Deleted element %d",x);
18. free(temp);
19. }
Here,
Step 4 − Checks for list empty.
Step 10, 11, 12 − Move the temp pointer to last but one node of the list.
Step 13 − Reads tail element to delete.
Step 14 − Moves tail pointer to last but one node.
Step 15 − Moves the temp pointer to last node of the list.
Step 16 − Removes the reference from tail node to temp node.
Step 17 − Displays elements to delete.
Step 18 − Deallocate the memory.
|
[
{
"code": null,
"e": 1171,
"s": 1062,
"text": "Linked lists use dynamic memory allocation i.e. they grow and shrink accordingly. It is collection of nodes."
},
{
"code": null,
"e": 1243,
"s": 1171,
"text": "Node has two parts, which are data and link. These are explained below."
},
{
"code": null,
"e": 1318,
"s": 1243,
"text": "There are three types of operations on linked lists which are as follows −"
},
{
"code": null,
"e": 1328,
"s": 1318,
"text": "Insertion"
},
{
"code": null,
"e": 1337,
"s": 1328,
"text": "Deletion"
},
{
"code": null,
"e": 1348,
"s": 1337,
"text": "Traversing"
},
{
"code": null,
"e": 1367,
"s": 1348,
"text": "Identify the node."
},
{
"code": null,
"e": 1479,
"s": 1367,
"text": "Adjust the links in such a way that deallocation of the nodes does not make the list as unconnected components."
},
{
"code": null,
"e": 1513,
"s": 1479,
"text": "Return/display element to delete."
},
{
"code": null,
"e": 1536,
"s": 1513,
"text": "Deallocate the memory."
},
{
"code": null,
"e": 1617,
"s": 1536,
"text": "Follow the steps given below to delete a head element in C programming language."
},
{
"code": null,
"e": 1891,
"s": 1617,
"text": "1. void del_head()\n2. {\n3. int x;\n Node *temp;\n4. if(Head==NULL)\n5. {\n6. printf(\"List is empty\");\n7. return;\n8. }\n9. x=Head->ele;\n10. temp=Head;\n11. if(Head==Tail)\n12. Head=Tail=NULL:\n13. Else\n14. Head=Head->next;\n15. printf(\"Deleted element %d\",x);\n16. free(temp);\n17. }"
},
{
"code": null,
"e": 1897,
"s": 1891,
"text": "Here,"
},
{
"code": null,
"e": 1936,
"s": 1897,
"text": "Step 4 − Checks for list empty or not."
},
{
"code": null,
"e": 1973,
"s": 1936,
"text": "Step 9 − Reads an element to delete."
},
{
"code": null,
"e": 2014,
"s": 1973,
"text": "Step 10 − Head referred by temp pointer."
},
{
"code": null,
"e": 2050,
"s": 2014,
"text": "Step 11 − Checks for last deletion."
},
{
"code": null,
"e": 2107,
"s": 2050,
"text": "Step 14 − Move head pointer to next element in the list."
},
{
"code": null,
"e": 2145,
"s": 2107,
"text": "Step 15 − Displays element to delete."
},
{
"code": null,
"e": 2178,
"s": 2145,
"text": "Step 16 − Deallocate the memory."
},
{
"code": null,
"e": 2259,
"s": 2178,
"text": "Follow the steps given below to delete a tail element in C programming language."
},
{
"code": null,
"e": 2571,
"s": 2259,
"text": "1. void del_tail()\n2. {\n3. int x;\n4. Node *temp;\n5. if(Head==NULL)\n6. {\n7. printf(\"List is empty\");\n8. return;\n9. }\n10. temp=Head;\n11. while(temp->next !=Tail)\n12. temp=temp->next;\n13. x=Tail->ele;\n14. Tail=temp;\n15. Temp=temp->next\n16. Tail->next=NULL;\n17. printf(\"Deleted element %d\",x);\n18. free(temp);\n19. }"
},
{
"code": null,
"e": 2577,
"s": 2571,
"text": "Here,"
},
{
"code": null,
"e": 2609,
"s": 2577,
"text": "Step 4 − Checks for list empty."
},
{
"code": null,
"e": 2683,
"s": 2609,
"text": "Step 10, 11, 12 − Move the temp pointer to last but one node of the list."
},
{
"code": null,
"e": 2723,
"s": 2683,
"text": "Step 13 − Reads tail element to delete."
},
{
"code": null,
"e": 2774,
"s": 2723,
"text": "Step 14 − Moves tail pointer to last but one node."
},
{
"code": null,
"e": 2833,
"s": 2774,
"text": "Step 15 − Moves the temp pointer to last node of the list."
},
{
"code": null,
"e": 2894,
"s": 2833,
"text": "Step 16 − Removes the reference from tail node to temp node."
},
{
"code": null,
"e": 2933,
"s": 2894,
"text": "Step 17 − Displays elements to delete."
},
{
"code": null,
"e": 2966,
"s": 2933,
"text": "Step 18 − Deallocate the memory."
}
] |
Can we change the order of public static void main() to static public void main() in Java?
|
Yes, we can change the order of public static void main() to static public void main() in Java, the compiler doesn't throw any compile-time or runtime error. In Java, we can declare access modifiers in any order, the method name comes last, the return type comes second to last and then after it's our choice. But it's recommended to put access modifier (public, private and protected) at the forefront as per Java coding standards.
public static void main(String args[]) {
// some statements
}
Live Demo
class ParentTest {
int age = 10;
public int getAge() {
age += 25;
return age;
}
}
public class Test {
// Here we can declare static public void main(String args[])
static public void main(String args[]) {
ParentTest pt = new ParentTest();
System.out.println("Age is: "+ pt.getAge());
}
}
In the above example, we have declared static public main() instead of public static void main(), the code runs successfully without any errors.
Age is: 35
|
[
{
"code": null,
"e": 1495,
"s": 1062,
"text": "Yes, we can change the order of public static void main() to static public void main() in Java, the compiler doesn't throw any compile-time or runtime error. In Java, we can declare access modifiers in any order, the method name comes last, the return type comes second to last and then after it's our choice. But it's recommended to put access modifier (public, private and protected) at the forefront as per Java coding standards."
},
{
"code": null,
"e": 1560,
"s": 1495,
"text": "public static void main(String args[]) {\n // some statements\n}"
},
{
"code": null,
"e": 1570,
"s": 1560,
"text": "Live Demo"
},
{
"code": null,
"e": 1900,
"s": 1570,
"text": "class ParentTest {\n int age = 10;\n public int getAge() {\n age += 25;\n return age;\n }\n}\npublic class Test {\n // Here we can declare static public void main(String args[])\n static public void main(String args[]) {\n ParentTest pt = new ParentTest();\n System.out.println(\"Age is: \"+ pt.getAge());\n }\n}"
},
{
"code": null,
"e": 2045,
"s": 1900,
"text": "In the above example, we have declared static public main() instead of public static void main(), the code runs successfully without any errors."
},
{
"code": null,
"e": 2056,
"s": 2045,
"text": "Age is: 35"
}
] |
Python PostgreSQL - Select Data
|
You can retrieve the contents of an existing table in PostgreSQL using the SELECT statement. At this statement, you need to specify the name of the table and, it returns its contents in tabular format which is known as result set.
Following is the syntax of the SELECT statement in PostgreSQL −
SELECT column1, column2, columnN FROM table_name;
Assume we have created a table with name CRICKETERS using the following query −
postgres=# CREATE TABLE CRICKETERS (
First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int,
Place_Of_Birth VARCHAR(255), Country VARCHAR(255)
);
CREATE TABLE
postgres=#
And if we have inserted 5 records in to it using INSERT statements as −
postgres=# insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India');
INSERT 0 1
postgres=# insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');
INSERT 0 1
postgres=# insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');
INSERT 0 1
postgres=# insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');
INSERT 0 1
postgres=# insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');
INSERT 0 1
Following SELECT query retrieves the values of the columns FIRST_NAME, LAST_NAME and, COUNTRY from the CRICKETERS table.
postgres=# SELECT FIRST_NAME, LAST_NAME, COUNTRY FROM CRICKETERS;
first_name | last_name | country
------------+------------+-------------
Shikhar | Dhawan | India
Jonathan | Trott | SouthAfrica
Kumara | Sangakkara | Srilanka
Virat | Kohli | India
Rohit | Sharma | India
(5 rows)
If you want to retrieve all the columns of each record you need to replace the names of the columns with "⚹" as shown below −
postgres=# SELECT * FROM CRICKETERS;
first_name | last_name | age | place_of_birth | country
------------+------------+-----+----------------+-------------
Shikhar | Dhawan | 33 | Delhi | India
Jonathan | Trott | 38 | CapeTown | SouthAfrica
Kumara | Sangakkara | 41 | Matale | Srilanka
Virat | Kohli | 30 | Delhi | India
Rohit | Sharma | 32 | Nagpur | India
(5 rows)
postgres=#
READ Operation on any database means to fetch some useful information from the database. You can fetch data from PostgreSQL using the fetch() method provided by the psycopg2.
The Cursor class provides three methods namely fetchall(), fetchmany() and, fetchone() where,
The fetchall() method retrieves all the rows in the result set of a query and returns them as list of tuples. (If we execute this after retrieving few rows, it returns the remaining ones).
The fetchall() method retrieves all the rows in the result set of a query and returns them as list of tuples. (If we execute this after retrieving few rows, it returns the remaining ones).
The fetchone() method fetches the next row in the result of a query and returns it as a tuple.
The fetchone() method fetches the next row in the result of a query and returns it as a tuple.
Note − A result set is an object that is returned when a cursor object is used to query a table.
The following Python program connects to a database named mydb of PostgreSQL and retrieves all the records from a table named EMPLOYEE.
import psycopg2
#establishing the connection
conn = psycopg2.connect(
database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432'
)
#Setting auto commit false
conn.autocommit = True
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
#Retrieving data
cursor.execute('''SELECT * from EMPLOYEE''')
#Fetching 1st row from the table
result = cursor.fetchone();
print(result)
#Fetching 1st row from the table
result = cursor.fetchall();
print(result)
#Commit your changes in the database
conn.commit()
#Closing the connection
conn.close()
('Ramya', 'Rama priya', 27, 'F', 9000.0)
[
('Vinay', 'Battacharya', 20, 'M', 6000.0),
('Sharukh', 'Sheik', 25, 'M', 8300.0),
('Sarmista', 'Sharma', 26, 'F', 10000.0),
('Tripthi', 'Mishra', 24, 'F', 6000.0)
]
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2321,
"s": 2090,
"text": "You can retrieve the contents of an existing table in PostgreSQL using the SELECT statement. At this statement, you need to specify the name of the table and, it returns its contents in tabular format which is known as result set."
},
{
"code": null,
"e": 2385,
"s": 2321,
"text": "Following is the syntax of the SELECT statement in PostgreSQL −"
},
{
"code": null,
"e": 2436,
"s": 2385,
"text": "SELECT column1, column2, columnN FROM table_name;\n"
},
{
"code": null,
"e": 2516,
"s": 2436,
"text": "Assume we have created a table with name CRICKETERS using the following query −"
},
{
"code": null,
"e": 2699,
"s": 2516,
"text": "postgres=# CREATE TABLE CRICKETERS ( \n First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, \n Place_Of_Birth VARCHAR(255), Country VARCHAR(255)\n);\n\nCREATE TABLE\n\npostgres=#\n"
},
{
"code": null,
"e": 2771,
"s": 2699,
"text": "And if we have inserted 5 records in to it using INSERT statements as −"
},
{
"code": null,
"e": 3263,
"s": 2771,
"text": "postgres=# insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India');\nINSERT 0 1\npostgres=# insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');\nINSERT 0 1\npostgres=# insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');\nINSERT 0 1\npostgres=# insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');\nINSERT 0 1\npostgres=# insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');\nINSERT 0 1"
},
{
"code": null,
"e": 3384,
"s": 3263,
"text": "Following SELECT query retrieves the values of the columns FIRST_NAME, LAST_NAME and, COUNTRY from the CRICKETERS table."
},
{
"code": null,
"e": 3709,
"s": 3384,
"text": "postgres=# SELECT FIRST_NAME, LAST_NAME, COUNTRY FROM CRICKETERS;\n first_name | last_name | country\n------------+------------+-------------\nShikhar | Dhawan | India\nJonathan | Trott | SouthAfrica\nKumara | Sangakkara | Srilanka\nVirat | Kohli | India\nRohit | Sharma | India\n(5 rows)\n"
},
{
"code": null,
"e": 3835,
"s": 3709,
"text": "If you want to retrieve all the columns of each record you need to replace the names of the columns with \"⚹\" as shown below −"
},
{
"code": null,
"e": 4304,
"s": 3835,
"text": "postgres=# SELECT * FROM CRICKETERS;\nfirst_name | last_name | age | place_of_birth | country\n------------+------------+-----+----------------+-------------\nShikhar | Dhawan | 33 | Delhi | India\nJonathan | Trott | 38 | CapeTown | SouthAfrica\nKumara | Sangakkara | 41 | Matale | Srilanka\nVirat | Kohli | 30 | Delhi | India\nRohit | Sharma | 32 | Nagpur | India\n(5 rows)\n\npostgres=#\n"
},
{
"code": null,
"e": 4479,
"s": 4304,
"text": "READ Operation on any database means to fetch some useful information from the database. You can fetch data from PostgreSQL using the fetch() method provided by the psycopg2."
},
{
"code": null,
"e": 4573,
"s": 4479,
"text": "The Cursor class provides three methods namely fetchall(), fetchmany() and, fetchone() where,"
},
{
"code": null,
"e": 4762,
"s": 4573,
"text": "The fetchall() method retrieves all the rows in the result set of a query and returns them as list of tuples. (If we execute this after retrieving few rows, it returns the remaining ones)."
},
{
"code": null,
"e": 4951,
"s": 4762,
"text": "The fetchall() method retrieves all the rows in the result set of a query and returns them as list of tuples. (If we execute this after retrieving few rows, it returns the remaining ones)."
},
{
"code": null,
"e": 5046,
"s": 4951,
"text": "The fetchone() method fetches the next row in the result of a query and returns it as a tuple."
},
{
"code": null,
"e": 5141,
"s": 5046,
"text": "The fetchone() method fetches the next row in the result of a query and returns it as a tuple."
},
{
"code": null,
"e": 5238,
"s": 5141,
"text": "Note − A result set is an object that is returned when a cursor object is used to query a table."
},
{
"code": null,
"e": 5374,
"s": 5238,
"text": "The following Python program connects to a database named mydb of PostgreSQL and retrieves all the records from a table named EMPLOYEE."
},
{
"code": null,
"e": 5968,
"s": 5374,
"text": "import psycopg2\n\n#establishing the connection\nconn = psycopg2.connect(\n database=\"mydb\", user='postgres', password='password', host='127.0.0.1', port= '5432'\n)\n\n#Setting auto commit false\nconn.autocommit = True\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Retrieving data\ncursor.execute('''SELECT * from EMPLOYEE''')\n\n#Fetching 1st row from the table\nresult = cursor.fetchone();\nprint(result)\n\n#Fetching 1st row from the table\nresult = cursor.fetchall();\nprint(result)\n\n#Commit your changes in the database\nconn.commit()\n\n#Closing the connection\nconn.close()"
},
{
"code": null,
"e": 6189,
"s": 5968,
"text": "('Ramya', 'Rama priya', 27, 'F', 9000.0)\n[\n ('Vinay', 'Battacharya', 20, 'M', 6000.0),\n ('Sharukh', 'Sheik', 25, 'M', 8300.0),\n ('Sarmista', 'Sharma', 26, 'F', 10000.0),\n ('Tripthi', 'Mishra', 24, 'F', 6000.0)\n]\n"
},
{
"code": null,
"e": 6226,
"s": 6189,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 6242,
"s": 6226,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6275,
"s": 6242,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 6294,
"s": 6275,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6329,
"s": 6294,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 6351,
"s": 6329,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 6385,
"s": 6351,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 6413,
"s": 6385,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 6448,
"s": 6413,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 6462,
"s": 6448,
"text": " Lets Kode It"
},
{
"code": null,
"e": 6495,
"s": 6462,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 6512,
"s": 6495,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 6519,
"s": 6512,
"text": " Print"
},
{
"code": null,
"e": 6530,
"s": 6519,
"text": " Add Notes"
}
] |
Boxplot with variable length data in Matplotlib
|
To make a boxplot with variable length data in Matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Make a list of data points.
Make a box and whisker plot using boxplot() method.
To display the figure, use show() method.
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
data = [[2, 4, 1, 3], [0, 4, 3, 2], [0, 0, 1, 0]]
plt.boxplot(data)
plt.show()
|
[
{
"code": null,
"e": 1155,
"s": 1062,
"text": "To make a boxplot with variable length data in Matplotlib, we can take the following steps −"
},
{
"code": null,
"e": 1231,
"s": 1155,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1259,
"s": 1231,
"text": "Make a list of data points."
},
{
"code": null,
"e": 1311,
"s": 1259,
"text": "Make a box and whisker plot using boxplot() method."
},
{
"code": null,
"e": 1353,
"s": 1311,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1560,
"s": 1353,
"text": "from matplotlib import pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\ndata = [[2, 4, 1, 3], [0, 4, 3, 2], [0, 0, 1, 0]]\n\nplt.boxplot(data)\n\nplt.show()"
}
] |
Intro to Regular Expressions (Regex) | Towards Data Science
|
We live in a data-centric age. Data has been described as the new oil. But just like oil, data isn’t always useful in its raw form. One form of data that is particularly hard to use in its raw form is unstructured data.
A lot of data is unstructured data. Unstructured data doesn’t fit nicely into a format for analysis, like an Excel spreadsheet or a pandas DataFrame. Text data is a common type of unstructured data and this makes it difficult to work with. Enter regular expressions, or regex for short. They may look a little intimidating at first, but once you start to use them, you’ll be as comfortable as this snake in no time 🐍!
More comfortable with python? Try my tutorial for using regex with R instead:
medium.com
We’ll use the regular expressions module. To import this into your python project, use the following command:
See how easy that is? The re module is built into python, so there is no need to install it. Let’s take a look at a couple of the functions we have available to us in this module:
re.findall(pattern, string): This function returns a list containing all instances of pattern in stringre.sub(pattern, repl, string): This function returns string with instances of pattern in string replaced with repl
re.findall(pattern, string): This function returns a list containing all instances of pattern in string
re.sub(pattern, repl, string): This function returns string with instances of pattern in string replaced with repl
You may have already used these functions. They have pretty straightforward applications without adding regex. Think back to the times before social distancing and imagine a nice picnic in the park. Here’s an example string with what everyone is bringing to the picnic. We can use it to demonstrate the basic usage of the regex functions:
basic_string = 'Drew has 3 watermelons, Alex has 4 hamburgers, Karina has 12 tamales, and Anna has 6 soft pretzels'
If I want to pull every instance of one person’s name from this string, I would simply pass the name and basic_string to re.findall():
The result will be a list with all occurrences of the pattern. Using this example, basic_find will be a list with one item:
['Drew']
Now let’s imagine that Alex left his 4 hamburgers unattended at the picnic and they were stolen by Shawn. re.sub() can replace any instances of Alex with Shawn:
The resulting string will show that Shawn now has 4 hamburgers. What a lucky guy 🍔.
Drew has 3 watermelons, Shawn has 4 hamburgers, Karina has 12 tamales, and Anna has 6 soft pretzels
The examples so far are pretty basic. There is a time and place for them, but what if we want to know how many total food items there are at the picnic? Who are all the people with items? What if we need this data in a pandas dataframe for further analysis? This is where you will start to see the benefits of regex.
There are several concepts that drive regex:
Character setsMeta charactersQuantifiersCapture Groups
Character sets
Meta characters
Quantifiers
Capture Groups
This is not an exhaustive list, but is plenty to help us hit the ground running.
Character sets represent options inside of brackets, with regex matching only one of the options. There are multiple things we can do with character sets:
Match a group of characters: We can find all of the vowels in our string by putting every vowel in brackets, for example,[aeiou]
['e', 'a', 'a', 'e', 'e', 'o', 'e', 'a', 'a', 'u', 'e', 'a', 'i', 'a', 'a', 'a', 'a', 'e', 'a', 'a', 'a', 'o', 'e', 'e']
Match a range of characters: We can find any capital letter from “A” to “F,” by using a hyphen, [A-F]. Character sets are case sensitive, so [A-F] is not the same as [a-f]
['D', 'A', 'K', 'A']
Match a range of numbers: We can find numbers between a range by adding numbers to our character set, [0-9] to find any number.
['3', '4', '1', '2', '6']
Character sets can contain everything from this section simultaneously, so something like [A-Ct-z7-9] is still valid. It will match every character from capital “A” to capital “C,” lowercase “t” to lowercase “z,” and 7 through 9.
So far we can’t answer any of the questions posed earlier with bracket groups. Let’s add some more weapons to our regex arsenal.
Meta characters represent a type of character. They will typically begin with a backslash \. Each one will match to a single character. Here are some of the most important ones in action:
\s: This meta character represents spaces. This will match to each space, tab, and newline character. You may also specify \t and \n for tab and newline character respectively. Side note: our example string does not have any tabs, but be cautious when looking for them. Many integrated development environments, or IDE’s, have a setting that will replace all tabs with spaces while you are typing. In the example string, \s returns a string of 17 spaces, the exact number of spaces in our example string!
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
\w: This meta character represents alphanumeric characters. This includes all the letters a-z, capital and lowercase, and the numbers 0–9. This would be the equivalent of the bracket group [A-Za-z0-9], just much quicker to write. Take caution in remembering that the \w meta character on its own only captures a single character, not entire words or numbers. You’ll see that in the example. Don’t worry, we’ll get to how to handle that soon.
['D', 'r', 'e', 'w', 'h', 'a', 's', '3', 'w', 'a', 't', 'e', 'r', 'm', 'e', 'l', 'o', 'n', 's', 'A', 'l', 'e', 'x', 'h', 'a', 's', '4', 'h', 'a', 'm', 'b', 'u', 'r', 'g', 'e', 'r', 's', 'K', 'a', 'r', 'i', 'n', 'a', 'h', 'a', 's', '1', '2', 't', 'a', 'm', 'a', 'l', 'e', 's', 'a', 'n', 'd', 'A', 'n', 'n', 'a', 'h', 'a', 's', '6', 's', 'o', 'f', 't', 'p', 'r', 'e', 't', 'z', 'e', 'l', 's']
\d: This meta character represents numeric digits. Using our picnic example from earlier, see how it only finds the digits in the string. You’ll notice that like bracket groups, it picks up 5 numbers instead of the 4 we expect. This is because it is looking for each individual digit, not groups of digits. We’ll see how to fix that with quantifiers next.
['3', '4', '1', '2', '6']
As we saw in the previous section, a single meta character can have somewhat limited functionality. When it comes to words or numbers, we usually want to find more than 1 character at a time. This is where quantifiers come in. They allow you to quantify how many of a character you are expecting. They always come after the character they are quantifying and come in a few flavors:
+ quantifies 1 or more matches. Let’s look at a new example to develop some intuition about what each quantifier will return: quant_example
When we use the + quantifier on quant_example, it will return 4 matches. This is a good point to mention that regex looks for non-overlapping matches. In this case, it looks at each B and the character that follows it. Since we used the + quantifier, it continues to match until it reaches the end of a group of B’s.
['B', 'BB', 'BBB', 'BBBB']
{} quantifies a specific number or range of matches. When written like {2} it will match exactly 2 of the preceding character. We’ll see some interesting results. It picked up 4 matches. This is because it is looking for each non-overlapping group of 2 B’s. There is a match in the 1st group, only 1 non-overlapping match in the 2nd group, and 2 non-overlapping matches in the 4th.
['BB', 'BB', 'BB', 'BB']
When written like {2,4}, it will match any number of B’s from 2 to 4 occurrences. Note that putting a space in your regex will NOT work. It will return an empty list.
['BB', 'BBB', 'BBBB']
We can also write this quantifier and omit the upper bound like {2,}. This will match 2 or more instances. For quant_example, it will return the exact same result as {2,4}.
* quantifies zero or more matches. This can be helpful when we are looking for something that may or may not be in our string.
The * quantifier returns some strange matches when used by itself, so we can omit an example with quant_example. We will see in a following example how it can be applied when someone at our picnic is bringing a food item with a multiple word name. Without it, we wouldn’t correctly capture that Anna is bringing soft pretzels!
Let’s combine what we know so far about character sets, meta characters, and quantifiers to answer some questions about our picnic string. We want to know all of the words that are in the string and also the numbers in the string.
For words, we can use a character set with all upper and lower case letters, adding a + quantifier to it. This will find any length of alpha characters grouped together. Said another way, it finds all of the words. Regex is starting to look much more helpful.
['Drew', 'has', 'watermelons', 'Alex', 'has', 'hamburgers', 'Karina', 'has', 'tamales', 'and', 'Anna', 'has', 'soft', 'pretzels']
To find the quantity of each food item, we can use the \d meta character and the quantifier {1,2}. This will find the groups of digits that are 1 or 2 characters long. This is a much more useful output as we have the same number of quantities as we have food items and people!
['3', '4', '12', '6']
To find the quantity and name of each food item, we can combine quantifiers with meta characters. We know that each number has a food item directly after it, so we can just add on to the previous example. We know there is a space and a word (\s\w+) that could be followed by another word like how “soft pretzel” appears. To specify the second word might not be there, we can use the * quantifier with the second word. Just like that we have a list containing the quantity and name of every good at our picnic.
['3 watermelons', '4 hamburgers', '12 tamales', '6 soft pretzels']
Capture groups allow you to look for entire phrases and only return parts of them. With our example, I want each person’s name, what they are bringing, and how much of it they are bringing.
['Drew has 3 watermelons', 'Alex has 4 hamburgers', 'Karina has 12 tamales', 'Anna has 6 soft pretzels']
The regex we used in capture_group1 is looking for a name, which starts with a capital letter and has any amount of lowercase letters after it ([A-Z][a-z]+). Then after a space it matches the pattern space, word, space \s\w+\s. Next we are looking for a 1 to 2 digit number followed by a space and a word (\d{1,2}\s\w+). You can see in the output we get a string with the details for each person.
Now this is a big step up from where we started, but we don’t really care about the word “has”, and we want to be able to make a pandas dataframe out of the quantities. Let’s add in capture groups. By using capture groups, we can return a tuple with the desired information. We’ll create capture groups containing each name, quantity, and item. Capture groups are simply sections of the regex that you wrap in parenthesis.
[('Drew', '3', 'watermelons'), ('Alex', '4', 'hamburgers'), ('Karina', '12', 'tamales'), ('Anna', '6', 'soft pretzels')]
Just like that we now have a list of tuples containing the exact information that we want!
When doing data analysis, one of the most useful python data structures is a pandas dataframe. No doubt you already knew this if you clicked on this article. Dataframes enable things like calculating column statistics and plotting data. Since we have a list of tuples with all of the information we want in our dataframe, we can just iterate over the list, building our dataframe.
| Name | Quantity | Item || ------ | -------- | ------------- || Drew | 3 | watermelons || Alex | 4 | hamburgers || Karina | 12 | tamales || Anna | 6 | soft pretzels |
We only covered a small subset of how regex can help handle unstructured text data. This is a good foundation to get started, but before long you will need to know concepts like how to find everything BUT a character (negation) or find something immediately before or after something else (lookarounds). Check out my other post on those concepts.
towardsdatascience.com
Here are some more resources to help you learn more about these other concepts in regex:
The official re documentation: While documentation can seem intimidating, learning how to read it will only help you later while you program
w3schools References: A huge knowledge base of coding and scripting language references, including python. Many of their examples can be run right from their browser by clicking on the “Try it Yourself” button
Datacamp Courses (PAID link): An online learning community dedicated to data science, machine learning, and data visualization. Check out their course “Regular Expressions in Python.” The first chapter of every course on the site is free!
|
[
{
"code": null,
"e": 392,
"s": 172,
"text": "We live in a data-centric age. Data has been described as the new oil. But just like oil, data isn’t always useful in its raw form. One form of data that is particularly hard to use in its raw form is unstructured data."
},
{
"code": null,
"e": 810,
"s": 392,
"text": "A lot of data is unstructured data. Unstructured data doesn’t fit nicely into a format for analysis, like an Excel spreadsheet or a pandas DataFrame. Text data is a common type of unstructured data and this makes it difficult to work with. Enter regular expressions, or regex for short. They may look a little intimidating at first, but once you start to use them, you’ll be as comfortable as this snake in no time 🐍!"
},
{
"code": null,
"e": 888,
"s": 810,
"text": "More comfortable with python? Try my tutorial for using regex with R instead:"
},
{
"code": null,
"e": 899,
"s": 888,
"text": "medium.com"
},
{
"code": null,
"e": 1009,
"s": 899,
"text": "We’ll use the regular expressions module. To import this into your python project, use the following command:"
},
{
"code": null,
"e": 1189,
"s": 1009,
"text": "See how easy that is? The re module is built into python, so there is no need to install it. Let’s take a look at a couple of the functions we have available to us in this module:"
},
{
"code": null,
"e": 1407,
"s": 1189,
"text": "re.findall(pattern, string): This function returns a list containing all instances of pattern in stringre.sub(pattern, repl, string): This function returns string with instances of pattern in string replaced with repl"
},
{
"code": null,
"e": 1511,
"s": 1407,
"text": "re.findall(pattern, string): This function returns a list containing all instances of pattern in string"
},
{
"code": null,
"e": 1626,
"s": 1511,
"text": "re.sub(pattern, repl, string): This function returns string with instances of pattern in string replaced with repl"
},
{
"code": null,
"e": 1965,
"s": 1626,
"text": "You may have already used these functions. They have pretty straightforward applications without adding regex. Think back to the times before social distancing and imagine a nice picnic in the park. Here’s an example string with what everyone is bringing to the picnic. We can use it to demonstrate the basic usage of the regex functions:"
},
{
"code": null,
"e": 2081,
"s": 1965,
"text": "basic_string = 'Drew has 3 watermelons, Alex has 4 hamburgers, Karina has 12 tamales, and Anna has 6 soft pretzels'"
},
{
"code": null,
"e": 2216,
"s": 2081,
"text": "If I want to pull every instance of one person’s name from this string, I would simply pass the name and basic_string to re.findall():"
},
{
"code": null,
"e": 2340,
"s": 2216,
"text": "The result will be a list with all occurrences of the pattern. Using this example, basic_find will be a list with one item:"
},
{
"code": null,
"e": 2349,
"s": 2340,
"text": "['Drew']"
},
{
"code": null,
"e": 2510,
"s": 2349,
"text": "Now let’s imagine that Alex left his 4 hamburgers unattended at the picnic and they were stolen by Shawn. re.sub() can replace any instances of Alex with Shawn:"
},
{
"code": null,
"e": 2594,
"s": 2510,
"text": "The resulting string will show that Shawn now has 4 hamburgers. What a lucky guy 🍔."
},
{
"code": null,
"e": 2694,
"s": 2594,
"text": "Drew has 3 watermelons, Shawn has 4 hamburgers, Karina has 12 tamales, and Anna has 6 soft pretzels"
},
{
"code": null,
"e": 3011,
"s": 2694,
"text": "The examples so far are pretty basic. There is a time and place for them, but what if we want to know how many total food items there are at the picnic? Who are all the people with items? What if we need this data in a pandas dataframe for further analysis? This is where you will start to see the benefits of regex."
},
{
"code": null,
"e": 3056,
"s": 3011,
"text": "There are several concepts that drive regex:"
},
{
"code": null,
"e": 3111,
"s": 3056,
"text": "Character setsMeta charactersQuantifiersCapture Groups"
},
{
"code": null,
"e": 3126,
"s": 3111,
"text": "Character sets"
},
{
"code": null,
"e": 3142,
"s": 3126,
"text": "Meta characters"
},
{
"code": null,
"e": 3154,
"s": 3142,
"text": "Quantifiers"
},
{
"code": null,
"e": 3169,
"s": 3154,
"text": "Capture Groups"
},
{
"code": null,
"e": 3250,
"s": 3169,
"text": "This is not an exhaustive list, but is plenty to help us hit the ground running."
},
{
"code": null,
"e": 3405,
"s": 3250,
"text": "Character sets represent options inside of brackets, with regex matching only one of the options. There are multiple things we can do with character sets:"
},
{
"code": null,
"e": 3534,
"s": 3405,
"text": "Match a group of characters: We can find all of the vowels in our string by putting every vowel in brackets, for example,[aeiou]"
},
{
"code": null,
"e": 3655,
"s": 3534,
"text": "['e', 'a', 'a', 'e', 'e', 'o', 'e', 'a', 'a', 'u', 'e', 'a', 'i', 'a', 'a', 'a', 'a', 'e', 'a', 'a', 'a', 'o', 'e', 'e']"
},
{
"code": null,
"e": 3827,
"s": 3655,
"text": "Match a range of characters: We can find any capital letter from “A” to “F,” by using a hyphen, [A-F]. Character sets are case sensitive, so [A-F] is not the same as [a-f]"
},
{
"code": null,
"e": 3848,
"s": 3827,
"text": "['D', 'A', 'K', 'A']"
},
{
"code": null,
"e": 3976,
"s": 3848,
"text": "Match a range of numbers: We can find numbers between a range by adding numbers to our character set, [0-9] to find any number."
},
{
"code": null,
"e": 4002,
"s": 3976,
"text": "['3', '4', '1', '2', '6']"
},
{
"code": null,
"e": 4232,
"s": 4002,
"text": "Character sets can contain everything from this section simultaneously, so something like [A-Ct-z7-9] is still valid. It will match every character from capital “A” to capital “C,” lowercase “t” to lowercase “z,” and 7 through 9."
},
{
"code": null,
"e": 4361,
"s": 4232,
"text": "So far we can’t answer any of the questions posed earlier with bracket groups. Let’s add some more weapons to our regex arsenal."
},
{
"code": null,
"e": 4549,
"s": 4361,
"text": "Meta characters represent a type of character. They will typically begin with a backslash \\. Each one will match to a single character. Here are some of the most important ones in action:"
},
{
"code": null,
"e": 5054,
"s": 4549,
"text": "\\s: This meta character represents spaces. This will match to each space, tab, and newline character. You may also specify \\t and \\n for tab and newline character respectively. Side note: our example string does not have any tabs, but be cautious when looking for them. Many integrated development environments, or IDE’s, have a setting that will replace all tabs with spaces while you are typing. In the example string, \\s returns a string of 17 spaces, the exact number of spaces in our example string!"
},
{
"code": null,
"e": 5140,
"s": 5054,
"text": "[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']"
},
{
"code": null,
"e": 5582,
"s": 5140,
"text": "\\w: This meta character represents alphanumeric characters. This includes all the letters a-z, capital and lowercase, and the numbers 0–9. This would be the equivalent of the bracket group [A-Za-z0-9], just much quicker to write. Take caution in remembering that the \\w meta character on its own only captures a single character, not entire words or numbers. You’ll see that in the example. Don’t worry, we’ll get to how to handle that soon."
},
{
"code": null,
"e": 5973,
"s": 5582,
"text": "['D', 'r', 'e', 'w', 'h', 'a', 's', '3', 'w', 'a', 't', 'e', 'r', 'm', 'e', 'l', 'o', 'n', 's', 'A', 'l', 'e', 'x', 'h', 'a', 's', '4', 'h', 'a', 'm', 'b', 'u', 'r', 'g', 'e', 'r', 's', 'K', 'a', 'r', 'i', 'n', 'a', 'h', 'a', 's', '1', '2', 't', 'a', 'm', 'a', 'l', 'e', 's', 'a', 'n', 'd', 'A', 'n', 'n', 'a', 'h', 'a', 's', '6', 's', 'o', 'f', 't', 'p', 'r', 'e', 't', 'z', 'e', 'l', 's']"
},
{
"code": null,
"e": 6329,
"s": 5973,
"text": "\\d: This meta character represents numeric digits. Using our picnic example from earlier, see how it only finds the digits in the string. You’ll notice that like bracket groups, it picks up 5 numbers instead of the 4 we expect. This is because it is looking for each individual digit, not groups of digits. We’ll see how to fix that with quantifiers next."
},
{
"code": null,
"e": 6355,
"s": 6329,
"text": "['3', '4', '1', '2', '6']"
},
{
"code": null,
"e": 6737,
"s": 6355,
"text": "As we saw in the previous section, a single meta character can have somewhat limited functionality. When it comes to words or numbers, we usually want to find more than 1 character at a time. This is where quantifiers come in. They allow you to quantify how many of a character you are expecting. They always come after the character they are quantifying and come in a few flavors:"
},
{
"code": null,
"e": 6877,
"s": 6737,
"text": "+ quantifies 1 or more matches. Let’s look at a new example to develop some intuition about what each quantifier will return: quant_example"
},
{
"code": null,
"e": 7194,
"s": 6877,
"text": "When we use the + quantifier on quant_example, it will return 4 matches. This is a good point to mention that regex looks for non-overlapping matches. In this case, it looks at each B and the character that follows it. Since we used the + quantifier, it continues to match until it reaches the end of a group of B’s."
},
{
"code": null,
"e": 7221,
"s": 7194,
"text": "['B', 'BB', 'BBB', 'BBBB']"
},
{
"code": null,
"e": 7603,
"s": 7221,
"text": "{} quantifies a specific number or range of matches. When written like {2} it will match exactly 2 of the preceding character. We’ll see some interesting results. It picked up 4 matches. This is because it is looking for each non-overlapping group of 2 B’s. There is a match in the 1st group, only 1 non-overlapping match in the 2nd group, and 2 non-overlapping matches in the 4th."
},
{
"code": null,
"e": 7628,
"s": 7603,
"text": "['BB', 'BB', 'BB', 'BB']"
},
{
"code": null,
"e": 7795,
"s": 7628,
"text": "When written like {2,4}, it will match any number of B’s from 2 to 4 occurrences. Note that putting a space in your regex will NOT work. It will return an empty list."
},
{
"code": null,
"e": 7817,
"s": 7795,
"text": "['BB', 'BBB', 'BBBB']"
},
{
"code": null,
"e": 7990,
"s": 7817,
"text": "We can also write this quantifier and omit the upper bound like {2,}. This will match 2 or more instances. For quant_example, it will return the exact same result as {2,4}."
},
{
"code": null,
"e": 8117,
"s": 7990,
"text": "* quantifies zero or more matches. This can be helpful when we are looking for something that may or may not be in our string."
},
{
"code": null,
"e": 8444,
"s": 8117,
"text": "The * quantifier returns some strange matches when used by itself, so we can omit an example with quant_example. We will see in a following example how it can be applied when someone at our picnic is bringing a food item with a multiple word name. Without it, we wouldn’t correctly capture that Anna is bringing soft pretzels!"
},
{
"code": null,
"e": 8675,
"s": 8444,
"text": "Let’s combine what we know so far about character sets, meta characters, and quantifiers to answer some questions about our picnic string. We want to know all of the words that are in the string and also the numbers in the string."
},
{
"code": null,
"e": 8935,
"s": 8675,
"text": "For words, we can use a character set with all upper and lower case letters, adding a + quantifier to it. This will find any length of alpha characters grouped together. Said another way, it finds all of the words. Regex is starting to look much more helpful."
},
{
"code": null,
"e": 9065,
"s": 8935,
"text": "['Drew', 'has', 'watermelons', 'Alex', 'has', 'hamburgers', 'Karina', 'has', 'tamales', 'and', 'Anna', 'has', 'soft', 'pretzels']"
},
{
"code": null,
"e": 9342,
"s": 9065,
"text": "To find the quantity of each food item, we can use the \\d meta character and the quantifier {1,2}. This will find the groups of digits that are 1 or 2 characters long. This is a much more useful output as we have the same number of quantities as we have food items and people!"
},
{
"code": null,
"e": 9364,
"s": 9342,
"text": "['3', '4', '12', '6']"
},
{
"code": null,
"e": 9874,
"s": 9364,
"text": "To find the quantity and name of each food item, we can combine quantifiers with meta characters. We know that each number has a food item directly after it, so we can just add on to the previous example. We know there is a space and a word (\\s\\w+) that could be followed by another word like how “soft pretzel” appears. To specify the second word might not be there, we can use the * quantifier with the second word. Just like that we have a list containing the quantity and name of every good at our picnic."
},
{
"code": null,
"e": 9941,
"s": 9874,
"text": "['3 watermelons', '4 hamburgers', '12 tamales', '6 soft pretzels']"
},
{
"code": null,
"e": 10131,
"s": 9941,
"text": "Capture groups allow you to look for entire phrases and only return parts of them. With our example, I want each person’s name, what they are bringing, and how much of it they are bringing."
},
{
"code": null,
"e": 10236,
"s": 10131,
"text": "['Drew has 3 watermelons', 'Alex has 4 hamburgers', 'Karina has 12 tamales', 'Anna has 6 soft pretzels']"
},
{
"code": null,
"e": 10633,
"s": 10236,
"text": "The regex we used in capture_group1 is looking for a name, which starts with a capital letter and has any amount of lowercase letters after it ([A-Z][a-z]+). Then after a space it matches the pattern space, word, space \\s\\w+\\s. Next we are looking for a 1 to 2 digit number followed by a space and a word (\\d{1,2}\\s\\w+). You can see in the output we get a string with the details for each person."
},
{
"code": null,
"e": 11056,
"s": 10633,
"text": "Now this is a big step up from where we started, but we don’t really care about the word “has”, and we want to be able to make a pandas dataframe out of the quantities. Let’s add in capture groups. By using capture groups, we can return a tuple with the desired information. We’ll create capture groups containing each name, quantity, and item. Capture groups are simply sections of the regex that you wrap in parenthesis."
},
{
"code": null,
"e": 11177,
"s": 11056,
"text": "[('Drew', '3', 'watermelons'), ('Alex', '4', 'hamburgers'), ('Karina', '12', 'tamales'), ('Anna', '6', 'soft pretzels')]"
},
{
"code": null,
"e": 11268,
"s": 11177,
"text": "Just like that we now have a list of tuples containing the exact information that we want!"
},
{
"code": null,
"e": 11649,
"s": 11268,
"text": "When doing data analysis, one of the most useful python data structures is a pandas dataframe. No doubt you already knew this if you clicked on this article. Dataframes enable things like calculating column statistics and plotting data. Since we have a list of tuples with all of the information we want in our dataframe, we can just iterate over the list, building our dataframe."
},
{
"code": null,
"e": 11872,
"s": 11649,
"text": "| Name | Quantity | Item || ------ | -------- | ------------- || Drew | 3 | watermelons || Alex | 4 | hamburgers || Karina | 12 | tamales || Anna | 6 | soft pretzels |"
},
{
"code": null,
"e": 12219,
"s": 11872,
"text": "We only covered a small subset of how regex can help handle unstructured text data. This is a good foundation to get started, but before long you will need to know concepts like how to find everything BUT a character (negation) or find something immediately before or after something else (lookarounds). Check out my other post on those concepts."
},
{
"code": null,
"e": 12242,
"s": 12219,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 12331,
"s": 12242,
"text": "Here are some more resources to help you learn more about these other concepts in regex:"
},
{
"code": null,
"e": 12472,
"s": 12331,
"text": "The official re documentation: While documentation can seem intimidating, learning how to read it will only help you later while you program"
},
{
"code": null,
"e": 12682,
"s": 12472,
"text": "w3schools References: A huge knowledge base of coding and scripting language references, including python. Many of their examples can be run right from their browser by clicking on the “Try it Yourself” button"
}
] |
C++ Class Member Functions
|
A member function of a class is a function that has its definition or its prototype within the class definition like any other variable. It operates on any object of the class of which it is a member, and has access to all the members of a class for that object.
Let us take previously defined class to access the members of the class using a member function instead of directly accessing them −
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
double getVolume(void);// Returns box volume
};
Member functions can be defined within the class definition or separately using scope resolution operator, : −. Defining a member function within the class definition declares the function inline, even if you do not use the inline specifier. So either you can define Volume() function as below −
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
double getVolume(void) {
return length * breadth * height;
}
};
If you like, you can define the same function outside the class using the scope resolution operator (::) as follows −
double Box::getVolume(void) {
return length * breadth * height;
}
Here, only important point is that you would have to use class name just before :: operator. A member function will be called using a dot operator (.) on a object where it will manipulate data related to that object only as follows −
Box myBox; // Create an object
myBox.getVolume(); // Call member function for the object
Let us put above concepts to set and get the value of different class members in a class −
#include <iostream>
using namespace std;
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
// Member functions declaration
double getVolume(void);
void setLength( double len );
void setBreadth( double bre );
void setHeight( double hei );
};
// Member functions definitions
double Box::getVolume(void) {
return length * breadth * height;
}
void Box::setLength( double len ) {
length = len;
}
void Box::setBreadth( double bre ) {
breadth = bre;
}
void Box::setHeight( double hei ) {
height = hei;
}
// Main function for the program
int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Volume of Box1 : 210
Volume of Box2 : 1560
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": 2581,
"s": 2318,
"text": "A member function of a class is a function that has its definition or its prototype within the class definition like any other variable. It operates on any object of the class of which it is a member, and has access to all the members of a class for that object."
},
{
"code": null,
"e": 2715,
"s": 2581,
"text": "Let us take previously defined class to access the members of the class using a member function instead of directly accessing them −"
},
{
"code": null,
"e": 2938,
"s": 2715,
"text": "class Box {\n public:\n double length; // Length of a box\n double breadth; // Breadth of a box\n double height; // Height of a box\n double getVolume(void);// Returns box volume\n};\n"
},
{
"code": null,
"e": 3234,
"s": 2938,
"text": "Member functions can be defined within the class definition or separately using scope resolution operator, : −. Defining a member function within the class definition declares the function inline, even if you do not use the inline specifier. So either you can define Volume() function as below −"
},
{
"code": null,
"e": 3483,
"s": 3234,
"text": "class Box {\n public:\n double length; // Length of a box\n double breadth; // Breadth of a box\n double height; // Height of a box\n \n double getVolume(void) {\n return length * breadth * height;\n }\n};\n"
},
{
"code": null,
"e": 3601,
"s": 3483,
"text": "If you like, you can define the same function outside the class using the scope resolution operator (::) as follows −"
},
{
"code": null,
"e": 3671,
"s": 3601,
"text": "double Box::getVolume(void) {\n return length * breadth * height;\n}\n"
},
{
"code": null,
"e": 3905,
"s": 3671,
"text": "Here, only important point is that you would have to use class name just before :: operator. A member function will be called using a dot operator (.) on a object where it will manipulate data related to that object only as follows −"
},
{
"code": null,
"e": 4006,
"s": 3905,
"text": "Box myBox; // Create an object\n\nmyBox.getVolume(); // Call member function for the object\n"
},
{
"code": null,
"e": 4097,
"s": 4006,
"text": "Let us put above concepts to set and get the value of different class members in a class −"
},
{
"code": null,
"e": 5407,
"s": 4097,
"text": "#include <iostream>\n\nusing namespace std;\n\nclass Box {\n public:\n double length; // Length of a box\n double breadth; // Breadth of a box\n double height; // Height of a box\n\n // Member functions declaration\n double getVolume(void);\n void setLength( double len );\n void setBreadth( double bre );\n void setHeight( double hei );\n};\n\n// Member functions definitions\ndouble Box::getVolume(void) {\n return length * breadth * height;\n}\n\nvoid Box::setLength( double len ) {\n length = len;\n}\nvoid Box::setBreadth( double bre ) {\n breadth = bre;\n}\nvoid Box::setHeight( double hei ) {\n height = hei;\n}\n\n// Main function for the program\nint main() {\n Box Box1; // Declare Box1 of type Box\n Box Box2; // Declare Box2 of type Box\n double volume = 0.0; // Store the volume of a box here\n \n // box 1 specification\n Box1.setLength(6.0); \n Box1.setBreadth(7.0); \n Box1.setHeight(5.0);\n\n // box 2 specification\n Box2.setLength(12.0); \n Box2.setBreadth(13.0); \n Box2.setHeight(10.0);\n\n // volume of box 1\n volume = Box1.getVolume();\n cout << \"Volume of Box1 : \" << volume <<endl;\n\n // volume of box 2\n volume = Box2.getVolume();\n cout << \"Volume of Box2 : \" << volume <<endl;\n return 0;\n}"
},
{
"code": null,
"e": 5488,
"s": 5407,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 5532,
"s": 5488,
"text": "Volume of Box1 : 210\nVolume of Box2 : 1560\n"
},
{
"code": null,
"e": 5569,
"s": 5532,
"text": "\n 154 Lectures \n 11.5 hours \n"
},
{
"code": null,
"e": 5588,
"s": 5569,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5620,
"s": 5588,
"text": "\n 14 Lectures \n 57 mins\n"
},
{
"code": null,
"e": 5643,
"s": 5620,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 5679,
"s": 5643,
"text": "\n 30 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 5696,
"s": 5679,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5731,
"s": 5696,
"text": "\n 54 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5748,
"s": 5731,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5783,
"s": 5748,
"text": "\n 77 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5800,
"s": 5783,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5835,
"s": 5800,
"text": "\n 12 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5852,
"s": 5835,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5859,
"s": 5852,
"text": " Print"
},
{
"code": null,
"e": 5870,
"s": 5859,
"text": " Add Notes"
}
] |
Convert JSON file into CSV file and displaying the data using Node.js - GeeksforGeeks
|
09 Apr, 2021
There are so many ways to store data for better understanding for individual purposes, in few cases, JSON files will be more suitable in few cases, CSV files, and there are also lots of other types as well like XML, etc. In this article, we will convert the JSON file data into CSV file data and also display that through Node.js.
JSON stands for JavaScript Object Notation. It is a text-based data interchange format to maintain the structure of the data. JSON is the replacement of the XML data exchange format in JSON. It is easy to struct the data compare to XML. It supports data structures like arrays and objects and the JSON documents that are rapidly executed on the server. It is also a Language-Independent format that is derived from JavaScript.
CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format.
Storing data into CSV: There is a csv-writer is a module which is used to store data into CSV.
Syntax :
csv-writer(path,header);
path: File path to download CSV file.
header: Column names in a CSV file just like a dictionary.
Approach:
Import csv-writer after installing it.
Create an object for it.
Mention the values for each column in a constant variable
Use csvWriter.writeRecords(results) for write the data into CSV by csv_writer_object.writeRecords(constant variable)
Follow the below steps to convert a JSON file into a CSV file:
Installing Dependencies:npm install csv-writer
npm install csv-writer
Examplecode1.jscode1.js// Import csv-writerimport csvwriter from 'csv-writer' var createCsvWriter = csvwriter.createObjectCsvWriter // Passing the column names intp the moduleconst csvWriter = createCsvWriter({ // Output csv file name is geek_data path: 'geek_data.csv', header: [ // Title of the columns (column_names) {id: 'id', title: 'ID'}, {id: 'name', title: 'NAME'}, {id: 'age', title: 'AGE'}, ]}); // Values for each column through an arrayconst results = [ { id: '7058', name: 'Sravan Kumar Gottumukkala', age: 22 }, { id: '7004', name: 'Sudheer', age: 29 }, { id: '7059', name: 'Radha', age: 45 },{ id: '7060', name: 'vani', age: 34 } ];// Writerecords function to add recordscsvWriter .writeRecords(results) .then(()=> console.log('Data uploaded into csv successfully'));
Example
code1.js
// Import csv-writerimport csvwriter from 'csv-writer' var createCsvWriter = csvwriter.createObjectCsvWriter // Passing the column names intp the moduleconst csvWriter = createCsvWriter({ // Output csv file name is geek_data path: 'geek_data.csv', header: [ // Title of the columns (column_names) {id: 'id', title: 'ID'}, {id: 'name', title: 'NAME'}, {id: 'age', title: 'AGE'}, ]}); // Values for each column through an arrayconst results = [ { id: '7058', name: 'Sravan Kumar Gottumukkala', age: 22 }, { id: '7004', name: 'Sudheer', age: 29 }, { id: '7059', name: 'Radha', age: 45 },{ id: '7060', name: 'vani', age: 34 } ];// Writerecords function to add recordscsvWriter .writeRecords(results) .then(()=> console.log('Data uploaded into csv successfully'));
To start the conversion run the below command.node code1.js
node code1.js
Output:
Output:
Display data in CSV: Sometimes we will have to display the JSON file on the server before converting JSON to CSV file to check the data.
Approach:
Import fs and csv-parser modules.Create objects for these two(fsdata and csvdata).Create a data stream by using method called createReadStream with pipe method by passing csv-parser object.
Import fs and csv-parser modules.
Create objects for these two(fsdata and csvdata).
Create a data stream by using method called createReadStream with pipe method by passing csv-parser object.
Syntax:
fs_object.createReadStream('file_name.csv'),pipe(csv_parser_object())
Example:Code1.jsCode1.js// Importing csv-parser into csvdataimport csvdata from 'csv-parser' // Importing csv-parser into fsdataconst fsdata = require('fs'); // Reading csv data row wise from geek_data csv filefsdata.createReadStream('geek_data.csv') .pipe(csvdata()) .on('data', (row) => { // Display data row by row console.log(row); }) .on('end', () => { console.log('success'); });
Example:
Code1.js
// Importing csv-parser into csvdataimport csvdata from 'csv-parser' // Importing csv-parser into fsdataconst fsdata = require('fs'); // Reading csv data row wise from geek_data csv filefsdata.createReadStream('geek_data.csv') .pipe(csvdata()) .on('data', (row) => { // Display data row by row console.log(row); }) .on('end', () => { console.log('success'); });
To display the JSON data run the below command.node code1.js
node code1.js
Output:
Output:
Convert JSON to CSV: In the first method we pass the JSON data inside of our script but we can also attach the JSON file which was laready created.
It is used to process the data with in less number of time.It is similar to array structure.JSON is Human-readable and writable which is lightweight text based data interchange formatThough it is derived from a subset of JavaScript, yet it is Language independent.Thus, the code for generating and parsing JSON data can be written in any other programming language.
It is used to process the data with in less number of time.
It is similar to array structure.
JSON is Human-readable and writable which is lightweight text based data interchange format
Though it is derived from a subset of JavaScript, yet it is Language independent.
Thus, the code for generating and parsing JSON data can be written in any other programming language.
Syntax:
csvjson_object.toCSV(fileContent);
Approach :
Define the modules in Node.jsRead a file using fs packageUse toCSV method for convert JSON to CSVWrite this data into CSV file using fs package
Define the modules in Node.js
Read a file using fs package
Use toCSV method for convert JSON to CSV
Write this data into CSV file using fs package
Follow the below steps to convert a JSON file into a CSV file:
Installing Dependencies:npm install csvjson fs
Installing Dependencies:
npm install csvjson fs
Example:code1.jscode1.js// Import package csvjsonimport csvjson from 'csvjson' // Import fs package(file system) // for read and write filesimport fs from 'fs'const readFile = fs.readFile;const writeFile = fs.writeFile; // Reading json file(filename -data.json)readFile('./data.json', 'utf-8', (err, fileContent) => { if (err) { // Doing something to handle the error or just throw it console.log(err); throw new Error(err); } // Convert json to csv function const csvData = csvjson.toCSV(fileContent, { headers: 'key' }); // Write data into csv file named college_data.csv writeFile('./college_data.csv', csvData, (err) => { if(err) { // Do something to handle the error or just throw it console.log(err); throw new Error(err); } console.log('Data stored into csv file successfully'); });});
Example:
code1.js
// Import package csvjsonimport csvjson from 'csvjson' // Import fs package(file system) // for read and write filesimport fs from 'fs'const readFile = fs.readFile;const writeFile = fs.writeFile; // Reading json file(filename -data.json)readFile('./data.json', 'utf-8', (err, fileContent) => { if (err) { // Doing something to handle the error or just throw it console.log(err); throw new Error(err); } // Convert json to csv function const csvData = csvjson.toCSV(fileContent, { headers: 'key' }); // Write data into csv file named college_data.csv writeFile('./college_data.csv', csvData, (err) => { if(err) { // Do something to handle the error or just throw it console.log(err); throw new Error(err); } console.log('Data stored into csv file successfully'); });});
To start the conversion run the below command.node code1.js
node code1.js
Output:
JSON
NodeJS-Questions
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Express.js express.Router() Function
JWT Authentication with Node.js
Express.js req.params Property
Mongoose Populate() Method
Difference between npm i and npm ci in Node.js
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25002,
"s": 24974,
"text": "\n09 Apr, 2021"
},
{
"code": null,
"e": 25333,
"s": 25002,
"text": "There are so many ways to store data for better understanding for individual purposes, in few cases, JSON files will be more suitable in few cases, CSV files, and there are also lots of other types as well like XML, etc. In this article, we will convert the JSON file data into CSV file data and also display that through Node.js."
},
{
"code": null,
"e": 25760,
"s": 25333,
"text": "JSON stands for JavaScript Object Notation. It is a text-based data interchange format to maintain the structure of the data. JSON is the replacement of the XML data exchange format in JSON. It is easy to struct the data compare to XML. It supports data structures like arrays and objects and the JSON documents that are rapidly executed on the server. It is also a Language-Independent format that is derived from JavaScript."
},
{
"code": null,
"e": 26134,
"s": 25760,
"text": "CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format."
},
{
"code": null,
"e": 26229,
"s": 26134,
"text": "Storing data into CSV: There is a csv-writer is a module which is used to store data into CSV."
},
{
"code": null,
"e": 26238,
"s": 26229,
"text": "Syntax :"
},
{
"code": null,
"e": 26263,
"s": 26238,
"text": "csv-writer(path,header);"
},
{
"code": null,
"e": 26301,
"s": 26263,
"text": "path: File path to download CSV file."
},
{
"code": null,
"e": 26360,
"s": 26301,
"text": "header: Column names in a CSV file just like a dictionary."
},
{
"code": null,
"e": 26370,
"s": 26360,
"text": "Approach:"
},
{
"code": null,
"e": 26409,
"s": 26370,
"text": "Import csv-writer after installing it."
},
{
"code": null,
"e": 26434,
"s": 26409,
"text": "Create an object for it."
},
{
"code": null,
"e": 26492,
"s": 26434,
"text": "Mention the values for each column in a constant variable"
},
{
"code": null,
"e": 26609,
"s": 26492,
"text": "Use csvWriter.writeRecords(results) for write the data into CSV by csv_writer_object.writeRecords(constant variable)"
},
{
"code": null,
"e": 26672,
"s": 26609,
"text": "Follow the below steps to convert a JSON file into a CSV file:"
},
{
"code": null,
"e": 26719,
"s": 26672,
"text": "Installing Dependencies:npm install csv-writer"
},
{
"code": null,
"e": 26742,
"s": 26719,
"text": "npm install csv-writer"
},
{
"code": null,
"e": 27594,
"s": 26742,
"text": "Examplecode1.jscode1.js// Import csv-writerimport csvwriter from 'csv-writer' var createCsvWriter = csvwriter.createObjectCsvWriter // Passing the column names intp the moduleconst csvWriter = createCsvWriter({ // Output csv file name is geek_data path: 'geek_data.csv', header: [ // Title of the columns (column_names) {id: 'id', title: 'ID'}, {id: 'name', title: 'NAME'}, {id: 'age', title: 'AGE'}, ]}); // Values for each column through an arrayconst results = [ { id: '7058', name: 'Sravan Kumar Gottumukkala', age: 22 }, { id: '7004', name: 'Sudheer', age: 29 }, { id: '7059', name: 'Radha', age: 45 },{ id: '7060', name: 'vani', age: 34 } ];// Writerecords function to add recordscsvWriter .writeRecords(results) .then(()=> console.log('Data uploaded into csv successfully'));"
},
{
"code": null,
"e": 27602,
"s": 27594,
"text": "Example"
},
{
"code": null,
"e": 27611,
"s": 27602,
"text": "code1.js"
},
{
"code": "// Import csv-writerimport csvwriter from 'csv-writer' var createCsvWriter = csvwriter.createObjectCsvWriter // Passing the column names intp the moduleconst csvWriter = createCsvWriter({ // Output csv file name is geek_data path: 'geek_data.csv', header: [ // Title of the columns (column_names) {id: 'id', title: 'ID'}, {id: 'name', title: 'NAME'}, {id: 'age', title: 'AGE'}, ]}); // Values for each column through an arrayconst results = [ { id: '7058', name: 'Sravan Kumar Gottumukkala', age: 22 }, { id: '7004', name: 'Sudheer', age: 29 }, { id: '7059', name: 'Radha', age: 45 },{ id: '7060', name: 'vani', age: 34 } ];// Writerecords function to add recordscsvWriter .writeRecords(results) .then(()=> console.log('Data uploaded into csv successfully'));",
"e": 28440,
"s": 27611,
"text": null
},
{
"code": null,
"e": 28500,
"s": 28440,
"text": "To start the conversion run the below command.node code1.js"
},
{
"code": null,
"e": 28514,
"s": 28500,
"text": "node code1.js"
},
{
"code": null,
"e": 28522,
"s": 28514,
"text": "Output:"
},
{
"code": null,
"e": 28530,
"s": 28522,
"text": "Output:"
},
{
"code": null,
"e": 28667,
"s": 28530,
"text": "Display data in CSV: Sometimes we will have to display the JSON file on the server before converting JSON to CSV file to check the data."
},
{
"code": null,
"e": 28677,
"s": 28667,
"text": "Approach:"
},
{
"code": null,
"e": 28867,
"s": 28677,
"text": "Import fs and csv-parser modules.Create objects for these two(fsdata and csvdata).Create a data stream by using method called createReadStream with pipe method by passing csv-parser object."
},
{
"code": null,
"e": 28901,
"s": 28867,
"text": "Import fs and csv-parser modules."
},
{
"code": null,
"e": 28951,
"s": 28901,
"text": "Create objects for these two(fsdata and csvdata)."
},
{
"code": null,
"e": 29059,
"s": 28951,
"text": "Create a data stream by using method called createReadStream with pipe method by passing csv-parser object."
},
{
"code": null,
"e": 29067,
"s": 29059,
"text": "Syntax:"
},
{
"code": null,
"e": 29137,
"s": 29067,
"text": "fs_object.createReadStream('file_name.csv'),pipe(csv_parser_object())"
},
{
"code": null,
"e": 29541,
"s": 29137,
"text": "Example:Code1.jsCode1.js// Importing csv-parser into csvdataimport csvdata from 'csv-parser' // Importing csv-parser into fsdataconst fsdata = require('fs'); // Reading csv data row wise from geek_data csv filefsdata.createReadStream('geek_data.csv') .pipe(csvdata()) .on('data', (row) => { // Display data row by row console.log(row); }) .on('end', () => { console.log('success'); });"
},
{
"code": null,
"e": 29550,
"s": 29541,
"text": "Example:"
},
{
"code": null,
"e": 29559,
"s": 29550,
"text": "Code1.js"
},
{
"code": "// Importing csv-parser into csvdataimport csvdata from 'csv-parser' // Importing csv-parser into fsdataconst fsdata = require('fs'); // Reading csv data row wise from geek_data csv filefsdata.createReadStream('geek_data.csv') .pipe(csvdata()) .on('data', (row) => { // Display data row by row console.log(row); }) .on('end', () => { console.log('success'); });",
"e": 29939,
"s": 29559,
"text": null
},
{
"code": null,
"e": 30000,
"s": 29939,
"text": "To display the JSON data run the below command.node code1.js"
},
{
"code": null,
"e": 30014,
"s": 30000,
"text": "node code1.js"
},
{
"code": null,
"e": 30022,
"s": 30014,
"text": "Output:"
},
{
"code": null,
"e": 30030,
"s": 30022,
"text": "Output:"
},
{
"code": null,
"e": 30178,
"s": 30030,
"text": "Convert JSON to CSV: In the first method we pass the JSON data inside of our script but we can also attach the JSON file which was laready created."
},
{
"code": null,
"e": 30544,
"s": 30178,
"text": "It is used to process the data with in less number of time.It is similar to array structure.JSON is Human-readable and writable which is lightweight text based data interchange formatThough it is derived from a subset of JavaScript, yet it is Language independent.Thus, the code for generating and parsing JSON data can be written in any other programming language."
},
{
"code": null,
"e": 30604,
"s": 30544,
"text": "It is used to process the data with in less number of time."
},
{
"code": null,
"e": 30638,
"s": 30604,
"text": "It is similar to array structure."
},
{
"code": null,
"e": 30730,
"s": 30638,
"text": "JSON is Human-readable and writable which is lightweight text based data interchange format"
},
{
"code": null,
"e": 30812,
"s": 30730,
"text": "Though it is derived from a subset of JavaScript, yet it is Language independent."
},
{
"code": null,
"e": 30914,
"s": 30812,
"text": "Thus, the code for generating and parsing JSON data can be written in any other programming language."
},
{
"code": null,
"e": 30922,
"s": 30914,
"text": "Syntax:"
},
{
"code": null,
"e": 30957,
"s": 30922,
"text": "csvjson_object.toCSV(fileContent);"
},
{
"code": null,
"e": 30968,
"s": 30957,
"text": "Approach :"
},
{
"code": null,
"e": 31112,
"s": 30968,
"text": "Define the modules in Node.jsRead a file using fs packageUse toCSV method for convert JSON to CSVWrite this data into CSV file using fs package"
},
{
"code": null,
"e": 31142,
"s": 31112,
"text": "Define the modules in Node.js"
},
{
"code": null,
"e": 31171,
"s": 31142,
"text": "Read a file using fs package"
},
{
"code": null,
"e": 31212,
"s": 31171,
"text": "Use toCSV method for convert JSON to CSV"
},
{
"code": null,
"e": 31259,
"s": 31212,
"text": "Write this data into CSV file using fs package"
},
{
"code": null,
"e": 31322,
"s": 31259,
"text": "Follow the below steps to convert a JSON file into a CSV file:"
},
{
"code": null,
"e": 31369,
"s": 31322,
"text": "Installing Dependencies:npm install csvjson fs"
},
{
"code": null,
"e": 31394,
"s": 31369,
"text": "Installing Dependencies:"
},
{
"code": null,
"e": 31417,
"s": 31394,
"text": "npm install csvjson fs"
},
{
"code": null,
"e": 32324,
"s": 31417,
"text": "Example:code1.jscode1.js// Import package csvjsonimport csvjson from 'csvjson' // Import fs package(file system) // for read and write filesimport fs from 'fs'const readFile = fs.readFile;const writeFile = fs.writeFile; // Reading json file(filename -data.json)readFile('./data.json', 'utf-8', (err, fileContent) => { if (err) { // Doing something to handle the error or just throw it console.log(err); throw new Error(err); } // Convert json to csv function const csvData = csvjson.toCSV(fileContent, { headers: 'key' }); // Write data into csv file named college_data.csv writeFile('./college_data.csv', csvData, (err) => { if(err) { // Do something to handle the error or just throw it console.log(err); throw new Error(err); } console.log('Data stored into csv file successfully'); });});"
},
{
"code": null,
"e": 32333,
"s": 32324,
"text": "Example:"
},
{
"code": null,
"e": 32342,
"s": 32333,
"text": "code1.js"
},
{
"code": "// Import package csvjsonimport csvjson from 'csvjson' // Import fs package(file system) // for read and write filesimport fs from 'fs'const readFile = fs.readFile;const writeFile = fs.writeFile; // Reading json file(filename -data.json)readFile('./data.json', 'utf-8', (err, fileContent) => { if (err) { // Doing something to handle the error or just throw it console.log(err); throw new Error(err); } // Convert json to csv function const csvData = csvjson.toCSV(fileContent, { headers: 'key' }); // Write data into csv file named college_data.csv writeFile('./college_data.csv', csvData, (err) => { if(err) { // Do something to handle the error or just throw it console.log(err); throw new Error(err); } console.log('Data stored into csv file successfully'); });});",
"e": 33225,
"s": 32342,
"text": null
},
{
"code": null,
"e": 33285,
"s": 33225,
"text": "To start the conversion run the below command.node code1.js"
},
{
"code": null,
"e": 33299,
"s": 33285,
"text": "node code1.js"
},
{
"code": null,
"e": 33307,
"s": 33299,
"text": "Output:"
},
{
"code": null,
"e": 33312,
"s": 33307,
"text": "JSON"
},
{
"code": null,
"e": 33329,
"s": 33312,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 33337,
"s": 33329,
"text": "Node.js"
},
{
"code": null,
"e": 33354,
"s": 33337,
"text": "Web Technologies"
},
{
"code": null,
"e": 33452,
"s": 33354,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33489,
"s": 33452,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 33521,
"s": 33489,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 33552,
"s": 33521,
"text": "Express.js req.params Property"
},
{
"code": null,
"e": 33579,
"s": 33552,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 33626,
"s": 33579,
"text": "Difference between npm i and npm ci in Node.js"
},
{
"code": null,
"e": 33668,
"s": 33626,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 33711,
"s": 33668,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 33773,
"s": 33711,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 33818,
"s": 33773,
"text": "Convert a string to an integer in JavaScript"
}
] |
How to run an Android service always in background?
|
This example demonstrates how do I run an android service always in background.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:text="Click here to start background Service"
android:textStyle="bold"
android:textSize="16sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
Step 3 – Right click on the project, Select New >> Service >> Service and add the following to MyServices.java
package app.com.sample;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service {
public MyService() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId){
onTaskRemoved(intent);
Toast.makeText(getApplicationContext(),"This is a Service running in Background",
Toast.LENGTH_SHORT).show();
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onTaskRemoved(Intent rootIntent) {
Intent restartServiceIntent = new Intent(getApplicationContext(),this.getClass());
restartServiceIntent.setPackage(getPackageName());
startService(restartServiceIntent);
super.onTaskRemoved(rootIntent);
}
}
Step 4 − Add the following code to src/MainActivity.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startService(new Intent(getApplicationContext(),MyService.class));
}
});
}
}
Step 5 - Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<service
android:name=".MyService"
android:enabled="true"
android:exported="true"></service>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code.
|
[
{
"code": null,
"e": 1142,
"s": 1062,
"text": "This example demonstrates how do I run an android service always in background."
},
{
"code": null,
"e": 1271,
"s": 1142,
"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": 1336,
"s": 1271,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1925,
"s": 1336,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <Button\n android:id=\"@+id/button\"\n android:text=\"Click here to start background Service\"\n android:textStyle=\"bold\"\n android:textSize=\"16sp\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2036,
"s": 1925,
"text": "Step 3 – Right click on the project, Select New >> Service >> Service and add the following to MyServices.java"
},
{
"code": null,
"e": 3001,
"s": 2036,
"text": "package app.com.sample;\nimport android.app.Service;\nimport android.content.Intent;\nimport android.os.IBinder;\nimport android.widget.Toast;\npublic class MyService extends Service {\n public MyService() {\n }\n @Override\n public int onStartCommand(Intent intent, int flags, int startId){\n onTaskRemoved(intent);\n Toast.makeText(getApplicationContext(),\"This is a Service running in Background\",\n Toast.LENGTH_SHORT).show();\n return START_STICKY;\n }\n @Override\n public IBinder onBind(Intent intent) {\n // TODO: Return the communication channel to the service.\n throw new UnsupportedOperationException(\"Not yet implemented\");\n }\n @Override\n public void onTaskRemoved(Intent rootIntent) {\n Intent restartServiceIntent = new Intent(getApplicationContext(),this.getClass());\n restartServiceIntent.setPackage(getPackageName());\n startService(restartServiceIntent);\n super.onTaskRemoved(rootIntent);\n }\n}"
},
{
"code": null,
"e": 3058,
"s": 3001,
"text": "Step 4 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3717,
"s": 3058,
"text": "import android.content.Intent;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\npublic class MainActivity extends AppCompatActivity {\n Button button;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n button = findViewById(R.id.button);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n startService(new Intent(getApplicationContext(),MyService.class));\n }\n });\n }\n}"
},
{
"code": null,
"e": 3772,
"s": 3717,
"text": "Step 5 - Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4571,
"s": 3772,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <service\n android:name=\".MyService\"\n android:enabled=\"true\"\n android:exported=\"true\"></service>\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4918,
"s": 4571,
"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": 4961,
"s": 4920,
"text": "Click here to download the project code."
}
] |
Python & MySQL - Create Database Example
|
Python uses c.execute(q) function to create or delete a MySQL database where c is cursor and q is the query to be executed.
# execute SQL query using execute() method.
cursor.execute(sql)
$sql
Required - SQL query to create a MySQL database.
Try the following example to create a database −
Copy and paste the following example as mysql_example.ty −
#!/usr/bin/python
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","root","root@123")
# prepare a cursor object using cursor() method
cursor = db.cursor()
# execute SQL query using execute() method.
cursor.execute("CREATE DATABASE TUTORIALS")
print('Database created');
# disconnect from server
db.close()
Execute the mysql_example.py script using python and verify the output.
Database created
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2343,
"s": 2219,
"text": "Python uses c.execute(q) function to create or delete a MySQL database where c is cursor and q is the query to be executed."
},
{
"code": null,
"e": 2408,
"s": 2343,
"text": "# execute SQL query using execute() method.\ncursor.execute(sql)\n"
},
{
"code": null,
"e": 2413,
"s": 2408,
"text": "$sql"
},
{
"code": null,
"e": 2462,
"s": 2413,
"text": "Required - SQL query to create a MySQL database."
},
{
"code": null,
"e": 2511,
"s": 2462,
"text": "Try the following example to create a database −"
},
{
"code": null,
"e": 2570,
"s": 2511,
"text": "Copy and paste the following example as mysql_example.ty −"
},
{
"code": null,
"e": 2908,
"s": 2570,
"text": "#!/usr/bin/python\n\nimport MySQLdb\n\n# Open database connection\ndb = MySQLdb.connect(\"localhost\",\"root\",\"root@123\")\n\n# prepare a cursor object using cursor() method\ncursor = db.cursor()\n\n# execute SQL query using execute() method.\ncursor.execute(\"CREATE DATABASE TUTORIALS\")\n\nprint('Database created');\n\n# disconnect from server\ndb.close()"
},
{
"code": null,
"e": 2980,
"s": 2908,
"text": "Execute the mysql_example.py script using python and verify the output."
},
{
"code": null,
"e": 2998,
"s": 2980,
"text": "Database created\n"
},
{
"code": null,
"e": 3035,
"s": 2998,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3051,
"s": 3035,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3084,
"s": 3051,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3103,
"s": 3084,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3138,
"s": 3103,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3160,
"s": 3138,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3194,
"s": 3160,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3222,
"s": 3194,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3257,
"s": 3222,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3271,
"s": 3257,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3304,
"s": 3271,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3321,
"s": 3304,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3328,
"s": 3321,
"text": " Print"
},
{
"code": null,
"e": 3339,
"s": 3328,
"text": " Add Notes"
}
] |
Selecting a drop-down list by using the Selenium.select_by_visible_text() method in Python - GeeksforGeeks
|
11 Oct, 2020
Selenium is an effective device for controlling an internet browser thru the program. It is purposeful for all browsers, works on all fundamental OS and its scripts are written in numerous languages i.e Python, Java, C#, etc, we can be running with Python.
Different methods of Select class:
Selection an option from the dropdown menu by INDEX.
Selection an option from the dropdown by VISIBLE TEXT.
Selection an option from the dropdown menu by VALUE.
we are discussing on visible text method in the drop-down list.
The strategy chooses the alternative by its obvious choice label esteem. It acknowledges the noticeable content estimation of the choice tag and brings nothing back.
Requirement: You need to install chromedriver and set path. Click here to download.for more information follows this link.
Working with Drop-down list: Initially, you have to import the Select class and afterward you have to make the case of Select class. After making the case of Select class, you can perform select strategies on that occasion to choose the choices from the dropdown list.
from selenium.webdriver.support.ui import Select
for selection by using
drop=Select(driver.find_element_by_id(‘ ‘)
drop.select_by_visible_text(” “)
Example: We will be doing the following:
Import selenium module
Import select class module
Using web page for drop down list (URL).
Navigate to the id of option bar.
Python3
# importing the modulesfrom selenium import webdriverfrom selenium.webdriver.support.ui import Selectimport time # using chrome driverdriver=webdriver.Chrome() # web page urldriver.get("https://fs2.formsite.com/meherpavan/form2/index.html?1537702596407") # find id of optionx = driver.find_element_by_id('RESULT_RadioButton-9')drop=Select(x) # select by visible textdrop.select_by_visible_text("Afternoon")time.sleep(4)driver.close()
Output:
Python-selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
|
[
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n11 Oct, 2020"
},
{
"code": null,
"e": 24158,
"s": 23901,
"text": "Selenium is an effective device for controlling an internet browser thru the program. It is purposeful for all browsers, works on all fundamental OS and its scripts are written in numerous languages i.e Python, Java, C#, etc, we can be running with Python."
},
{
"code": null,
"e": 24193,
"s": 24158,
"text": "Different methods of Select class:"
},
{
"code": null,
"e": 24246,
"s": 24193,
"text": "Selection an option from the dropdown menu by INDEX."
},
{
"code": null,
"e": 24301,
"s": 24246,
"text": "Selection an option from the dropdown by VISIBLE TEXT."
},
{
"code": null,
"e": 24354,
"s": 24301,
"text": "Selection an option from the dropdown menu by VALUE."
},
{
"code": null,
"e": 24418,
"s": 24354,
"text": "we are discussing on visible text method in the drop-down list."
},
{
"code": null,
"e": 24584,
"s": 24418,
"text": "The strategy chooses the alternative by its obvious choice label esteem. It acknowledges the noticeable content estimation of the choice tag and brings nothing back."
},
{
"code": null,
"e": 24707,
"s": 24584,
"text": "Requirement: You need to install chromedriver and set path. Click here to download.for more information follows this link."
},
{
"code": null,
"e": 24976,
"s": 24707,
"text": "Working with Drop-down list: Initially, you have to import the Select class and afterward you have to make the case of Select class. After making the case of Select class, you can perform select strategies on that occasion to choose the choices from the dropdown list."
},
{
"code": null,
"e": 25025,
"s": 24976,
"text": "from selenium.webdriver.support.ui import Select"
},
{
"code": null,
"e": 25049,
"s": 25025,
"text": " for selection by using"
},
{
"code": null,
"e": 25092,
"s": 25049,
"text": "drop=Select(driver.find_element_by_id(‘ ‘)"
},
{
"code": null,
"e": 25125,
"s": 25092,
"text": "drop.select_by_visible_text(” “)"
},
{
"code": null,
"e": 25166,
"s": 25125,
"text": "Example: We will be doing the following:"
},
{
"code": null,
"e": 25189,
"s": 25166,
"text": "Import selenium module"
},
{
"code": null,
"e": 25216,
"s": 25189,
"text": "Import select class module"
},
{
"code": null,
"e": 25257,
"s": 25216,
"text": "Using web page for drop down list (URL)."
},
{
"code": null,
"e": 25291,
"s": 25257,
"text": "Navigate to the id of option bar."
},
{
"code": null,
"e": 25299,
"s": 25291,
"text": "Python3"
},
{
"code": "# importing the modulesfrom selenium import webdriverfrom selenium.webdriver.support.ui import Selectimport time # using chrome driverdriver=webdriver.Chrome() # web page urldriver.get(\"https://fs2.formsite.com/meherpavan/form2/index.html?1537702596407\") # find id of optionx = driver.find_element_by_id('RESULT_RadioButton-9')drop=Select(x) # select by visible textdrop.select_by_visible_text(\"Afternoon\")time.sleep(4)driver.close()",
"e": 25737,
"s": 25299,
"text": null
},
{
"code": null,
"e": 25745,
"s": 25737,
"text": "Output:"
},
{
"code": null,
"e": 25761,
"s": 25745,
"text": "Python-selenium"
},
{
"code": null,
"e": 25768,
"s": 25761,
"text": "Python"
},
{
"code": null,
"e": 25866,
"s": 25768,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25875,
"s": 25866,
"text": "Comments"
},
{
"code": null,
"e": 25888,
"s": 25875,
"text": "Old Comments"
},
{
"code": null,
"e": 25920,
"s": 25888,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25976,
"s": 25920,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26018,
"s": 25976,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26060,
"s": 26018,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26096,
"s": 26060,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 26118,
"s": 26096,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26157,
"s": 26118,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26184,
"s": 26157,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26215,
"s": 26184,
"text": "Python | os.path.join() method"
}
] |
C program to print digital clock with current time
|
In this section we will see how to make a digital clock using C. To work with time we can use the time.h header file. This header file has some function signatures that are used to handle date and time related issues.
The four important components of time.h is like below
size_t This size_t is basically the unsigned integral type. This is the result of sizeof().
size_t This size_t is basically the unsigned integral type. This is the result of sizeof().
clock_t This is used to store the processor time
clock_t This is used to store the processor time
time_t This is used to store calendar time
time_t This is used to store calendar time
struct tm This is a structure. It helps to hold the entire date and time.
struct tm This is a structure. It helps to hold the entire date and time.
#include <stdio.h>
#include <time.h>
int main() {
time_t s, val = 1;
struct tm* curr_time;
s = time(NULL); //This will store the time in seconds
curr_time = localtime(&s); //get the current time using localtime()
function
//Display in HH:mm:ss format
printf("%02d:%02d:%02d", curr_time->tm_hour, curr_time->tm_min,
curr_time->tm_sec);
}
23:35:44
|
[
{
"code": null,
"e": 1280,
"s": 1062,
"text": "In this section we will see how to make a digital clock using C. To work with time we can use the time.h header file. This header file has some function signatures that are used to handle date and time related issues."
},
{
"code": null,
"e": 1334,
"s": 1280,
"text": "The four important components of time.h is like below"
},
{
"code": null,
"e": 1426,
"s": 1334,
"text": "size_t This size_t is basically the unsigned integral type. This is the result of sizeof()."
},
{
"code": null,
"e": 1518,
"s": 1426,
"text": "size_t This size_t is basically the unsigned integral type. This is the result of sizeof()."
},
{
"code": null,
"e": 1567,
"s": 1518,
"text": "clock_t This is used to store the processor time"
},
{
"code": null,
"e": 1616,
"s": 1567,
"text": "clock_t This is used to store the processor time"
},
{
"code": null,
"e": 1659,
"s": 1616,
"text": "time_t This is used to store calendar time"
},
{
"code": null,
"e": 1702,
"s": 1659,
"text": "time_t This is used to store calendar time"
},
{
"code": null,
"e": 1776,
"s": 1702,
"text": "struct tm This is a structure. It helps to hold the entire date and time."
},
{
"code": null,
"e": 1850,
"s": 1776,
"text": "struct tm This is a structure. It helps to hold the entire date and time."
},
{
"code": null,
"e": 2217,
"s": 1850,
"text": "#include <stdio.h>\n#include <time.h>\nint main() {\n time_t s, val = 1;\n struct tm* curr_time;\n s = time(NULL); //This will store the time in seconds\n curr_time = localtime(&s); //get the current time using localtime()\n function\n //Display in HH:mm:ss format\n printf(\"%02d:%02d:%02d\", curr_time->tm_hour, curr_time->tm_min,\n curr_time->tm_sec);\n}"
},
{
"code": null,
"e": 2226,
"s": 2217,
"text": "23:35:44"
}
] |
File isHidden() method in Java with Examples - GeeksforGeeks
|
28 Jan, 2019
The isHidden() function is a part of File class in Java . This function determines whether the is a file or Directory denoted by the abstract filename is Hidden or not.The function returns true if the abstract file path is Hidden else return false.
Function signature:
public boolean isHidden()
Syntax:
file.isHidden()
Parameters: This method does not accept any parameter.
Return Type The function returns boolean data type representing whether a file is hidden or not
Exception: This method throws Security Exception if the write access to the file is denied
Below programs illustrates the use of isHidden() function:
Example 1: The file “F:\\program.txt” is not hidden
// Java program to demonstrate// isHidden() method of File Class import java.io.*; public class solution { public static void main(String args[]) { // Get the file File f = new File("F:\\program.txt"); // Check if the specified file // is Hidden or not if (f.isHidden()) System.out.println("File Hidden"); else System.out.println("File Not Hidden"); }}
Output:
File Hidden
Example 2: The file “F:\\program1.txt” is hidden
// Java program to demonstrate// isHidden() method of File Class import java.io.*; public class solution { public static void main(String args[]) { // Get the file File f = new File("F:\\program1.txt"); // Check if the specified file // is Hidden or not if (f.isHidden()) System.out.println("File Hidden"); else System.out.println("File Not Hidden"); }}
Output:
File Not Hidden
Note: The programs might not run in an online IDE. Please use an offline IDE and set the path of the file.
Java-File Class
Java-Functions
Java-IO package
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Apply Different Styles to a Cell in a Spreadsheet using Java?
How to Iterate HashMap in Java?
Java Program to Sort Names in an Alphabetical Order
Iterate Over the Characters of a String in Java
Create Password Protected Zip File in Java
How to Get Elements By Index from HashSet in Java?
Java Program to Write into a File
Pizza Shop Billing System using Java Swing
How to Replace a Element in Java ArrayList?
How to Write Data into Excel Sheet using Java?
|
[
{
"code": null,
"e": 24824,
"s": 24796,
"text": "\n28 Jan, 2019"
},
{
"code": null,
"e": 25073,
"s": 24824,
"text": "The isHidden() function is a part of File class in Java . This function determines whether the is a file or Directory denoted by the abstract filename is Hidden or not.The function returns true if the abstract file path is Hidden else return false."
},
{
"code": null,
"e": 25093,
"s": 25073,
"text": "Function signature:"
},
{
"code": null,
"e": 25119,
"s": 25093,
"text": "public boolean isHidden()"
},
{
"code": null,
"e": 25127,
"s": 25119,
"text": "Syntax:"
},
{
"code": null,
"e": 25143,
"s": 25127,
"text": "file.isHidden()"
},
{
"code": null,
"e": 25198,
"s": 25143,
"text": "Parameters: This method does not accept any parameter."
},
{
"code": null,
"e": 25294,
"s": 25198,
"text": "Return Type The function returns boolean data type representing whether a file is hidden or not"
},
{
"code": null,
"e": 25385,
"s": 25294,
"text": "Exception: This method throws Security Exception if the write access to the file is denied"
},
{
"code": null,
"e": 25444,
"s": 25385,
"text": "Below programs illustrates the use of isHidden() function:"
},
{
"code": null,
"e": 25496,
"s": 25444,
"text": "Example 1: The file “F:\\\\program.txt” is not hidden"
},
{
"code": "// Java program to demonstrate// isHidden() method of File Class import java.io.*; public class solution { public static void main(String args[]) { // Get the file File f = new File(\"F:\\\\program.txt\"); // Check if the specified file // is Hidden or not if (f.isHidden()) System.out.println(\"File Hidden\"); else System.out.println(\"File Not Hidden\"); }}",
"e": 25928,
"s": 25496,
"text": null
},
{
"code": null,
"e": 25936,
"s": 25928,
"text": "Output:"
},
{
"code": null,
"e": 25948,
"s": 25936,
"text": "File Hidden"
},
{
"code": null,
"e": 25997,
"s": 25948,
"text": "Example 2: The file “F:\\\\program1.txt” is hidden"
},
{
"code": "// Java program to demonstrate// isHidden() method of File Class import java.io.*; public class solution { public static void main(String args[]) { // Get the file File f = new File(\"F:\\\\program1.txt\"); // Check if the specified file // is Hidden or not if (f.isHidden()) System.out.println(\"File Hidden\"); else System.out.println(\"File Not Hidden\"); }}",
"e": 26430,
"s": 25997,
"text": null
},
{
"code": null,
"e": 26438,
"s": 26430,
"text": "Output:"
},
{
"code": null,
"e": 26454,
"s": 26438,
"text": "File Not Hidden"
},
{
"code": null,
"e": 26561,
"s": 26454,
"text": "Note: The programs might not run in an online IDE. Please use an offline IDE and set the path of the file."
},
{
"code": null,
"e": 26577,
"s": 26561,
"text": "Java-File Class"
},
{
"code": null,
"e": 26592,
"s": 26577,
"text": "Java-Functions"
},
{
"code": null,
"e": 26608,
"s": 26592,
"text": "Java-IO package"
},
{
"code": null,
"e": 26622,
"s": 26608,
"text": "Java Programs"
},
{
"code": null,
"e": 26720,
"s": 26622,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26729,
"s": 26720,
"text": "Comments"
},
{
"code": null,
"e": 26742,
"s": 26729,
"text": "Old Comments"
},
{
"code": null,
"e": 26811,
"s": 26742,
"text": "How to Apply Different Styles to a Cell in a Spreadsheet using Java?"
},
{
"code": null,
"e": 26843,
"s": 26811,
"text": "How to Iterate HashMap in Java?"
},
{
"code": null,
"e": 26895,
"s": 26843,
"text": "Java Program to Sort Names in an Alphabetical Order"
},
{
"code": null,
"e": 26943,
"s": 26895,
"text": "Iterate Over the Characters of a String in Java"
},
{
"code": null,
"e": 26986,
"s": 26943,
"text": "Create Password Protected Zip File in Java"
},
{
"code": null,
"e": 27037,
"s": 26986,
"text": "How to Get Elements By Index from HashSet in Java?"
},
{
"code": null,
"e": 27071,
"s": 27037,
"text": "Java Program to Write into a File"
},
{
"code": null,
"e": 27114,
"s": 27071,
"text": "Pizza Shop Billing System using Java Swing"
},
{
"code": null,
"e": 27158,
"s": 27114,
"text": "How to Replace a Element in Java ArrayList?"
}
] |
Basic Line Chart with curved lines
|
Following is an example of a basic line chart with smooth curved lines. We've already seen the configuration used to draw this chart in Google Charts Configuration Syntax chapter. So, let's see the complete example.
We've added backgroundColor configuration to change default background color.
// Set chart options
var options = {
curveType: 'function'
};
googlecharts_line_curve.htm
<html>
<head>
<title>Google Charts Tutorial</title>
<script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js"></script>
<script type = "text/javascript">
google.charts.load('current', {packages: ['corechart','line']});
</script>
</head>
<body>
<div id = "container" style = "width: 550px; height: 400px; margin: 0 auto">
</div>
<script language = "JavaScript">
function drawChart() {
// Define the chart to be drawn.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Month');
data.addColumn('number', 'Tokyo');
data.addColumn('number', 'New York');
data.addColumn('number', 'Berlin');
data.addColumn('number', 'London');
data.addRows([
['Jan', 7.0, -0.2, -0.9, 3.9],
['Feb', 6.9, 0.8, 0.6, 4.2],
['Mar', 9.5, 5.7, 3.5, 5.7],
['Apr', 14.5, 11.3, 8.4, 8.5],
['May', 18.2, 17.0, 13.5, 11.9],
['Jun', 21.5, 22.0, 17.0, 15.2],
['Jul', 25.2, 24.8, 18.6, 17.0],
['Aug', 26.5, 24.1, 17.9, 16.6],
['Sep', 23.3, 20.1, 14.3, 14.2],
['Oct', 18.3, 14.1, 9.0, 10.3],
['Nov', 13.9, 8.6, 3.9, 6.6],
['Dec', 9.6, 2.5, 1.0, 4.8]
]);
// Set chart options
var options = {'title' : 'Average Temperatures of Cities',
hAxis: {
title: 'Month'
},
vAxis: {
title: 'Temperature'
},
'width':550,
'height':400,
curveType: 'function'
};
// Instantiate and draw the chart.
var chart = new google.visualization.LineChart(document.getElementById('container'));
chart.draw(data, options);
}
google.charts.setOnLoadCallback(drawChart);
</script>
</body>
</html>
Verify the result.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2477,
"s": 2261,
"text": "Following is an example of a basic line chart with smooth curved lines. We've already seen the configuration used to draw this chart in Google Charts Configuration Syntax chapter. So, let's see the complete example."
},
{
"code": null,
"e": 2555,
"s": 2477,
"text": "We've added backgroundColor configuration to change default background color."
},
{
"code": null,
"e": 2620,
"s": 2555,
"text": "// Set chart options\nvar options = {\n curveType: 'function'\n};"
},
{
"code": null,
"e": 2648,
"s": 2620,
"text": "googlecharts_line_curve.htm"
},
{
"code": null,
"e": 4776,
"s": 2648,
"text": "<html>\n <head>\n <title>Google Charts Tutorial</title>\n <script type = \"text/javascript\" src = \"https://www.gstatic.com/charts/loader.js\"></script>\n <script type = \"text/javascript\">\n google.charts.load('current', {packages: ['corechart','line']}); \n </script>\n </head>\n \n <body>\n <div id = \"container\" style = \"width: 550px; height: 400px; margin: 0 auto\">\n </div>\n <script language = \"JavaScript\">\n function drawChart() {\n // Define the chart to be drawn.\n var data = new google.visualization.DataTable();\n data.addColumn('string', 'Month');\n data.addColumn('number', 'Tokyo');\n data.addColumn('number', 'New York');\n data.addColumn('number', 'Berlin');\n data.addColumn('number', 'London');\n data.addRows([\n ['Jan', 7.0, -0.2, -0.9, 3.9],\n ['Feb', 6.9, 0.8, 0.6, 4.2],\n ['Mar', 9.5, 5.7, 3.5, 5.7],\n ['Apr', 14.5, 11.3, 8.4, 8.5],\n ['May', 18.2, 17.0, 13.5, 11.9],\n ['Jun', 21.5, 22.0, 17.0, 15.2],\n \n ['Jul', 25.2, 24.8, 18.6, 17.0],\n ['Aug', 26.5, 24.1, 17.9, 16.6],\n ['Sep', 23.3, 20.1, 14.3, 14.2],\n ['Oct', 18.3, 14.1, 9.0, 10.3],\n ['Nov', 13.9, 8.6, 3.9, 6.6],\n ['Dec', 9.6, 2.5, 1.0, 4.8]\n ]);\n \n // Set chart options\n var options = {'title' : 'Average Temperatures of Cities',\n hAxis: {\n title: 'Month'\n },\n vAxis: {\n title: 'Temperature'\n }, \n 'width':550,\n 'height':400,\n curveType: 'function'\n };\n\n // Instantiate and draw the chart.\n var chart = new google.visualization.LineChart(document.getElementById('container'));\n chart.draw(data, options);\n }\n google.charts.setOnLoadCallback(drawChart);\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 4795,
"s": 4776,
"text": "Verify the result."
},
{
"code": null,
"e": 4802,
"s": 4795,
"text": " Print"
},
{
"code": null,
"e": 4813,
"s": 4802,
"text": " Add Notes"
}
] |
How GIN Indices Can Make Your Postgres Queries 15x Faster | by GreekDataGuy | Towards Data Science
|
Adding an index has improved query time from minutes to milliseconds more than I can count during my career. As data scientists, we spend A LOT of time querying and analyzing data so we should know how to do it efficiently.
Postgres has 6 index types. Today we’re covering GIN indices.
We’re going to seed a database with increasingly large amounts of data and compare query time with and without a GIN index. You’ll benefit more if you follow along in your SQL editor (I’m using DBeaver).
A data structure that makes retrieving data from a database more efficient at the cost of slower insert speeds and more disk space.
GIN stands for Generalized Inverted Index. In general, an inverted index maps words to its position in a table.
Below is an abstraction I drew of an inverted index.
If we wanted to find sentences in the table with the word lazy without an index, we’d need to iterate over every sentence in the table looking for matches.
But by adding an index, we know in advance which sentences contain the word lazy and can load those directly. This makes things a lot faster!
This type of index is good for querying composite datatypes, meaning they store more than 1 value. Examples are hStores, Arrays, Ranges and JSONs.
Let’s find out.
Start by creating a table and populating it with data.
# create tableCREATE TABLE articles ( body text, body_indexed text);# add an indexCREATE INDEX articles_search_idx ON articles USING gin (body_indexed gin_trgm_ops);# populate table with dataINSERT INTO articlesSELECT md5(random()::text), md5(random()::text)from ( SELECT * FROM generate_series(1,100000) AS id) AS x;
Awesome we now have a table called articles with 100k records, and 2 columns of random strings.
If you’re curious about the index. We didn’t index strings directly but used Postgres’s gin_trgm_ops to create trigrams (think ngrams in sklearn) from each string, and indexed that.
The table looks like this in my SQL editor.
I’m going to track query time after each 100k new records I add.
I’ll be running these queries.
SELECT count(*) FROM articles where body ilike '%abc%';SELECT count(*) FROM articles where body_indexed ilike'%abc%';
The same or a similar query run multiple times can vary in run time. This is due varying system load on your machine and changing query plans. For our purposes ignore fluctuations and look at general trends of time differences.
Wow! That’s a big difference on only 2 million records. Imagine we were querying on a database of billions.
Most of the time we just need to add a B-tree index. But sometimes another index like GIN is more appropriate. Just knowing that other index types are out there can be useful when you eventually come across a problem B-trees don’t solve.
Have you come across any cool use cases of indices or applied them in interesting ways?
|
[
{
"code": null,
"e": 396,
"s": 172,
"text": "Adding an index has improved query time from minutes to milliseconds more than I can count during my career. As data scientists, we spend A LOT of time querying and analyzing data so we should know how to do it efficiently."
},
{
"code": null,
"e": 458,
"s": 396,
"text": "Postgres has 6 index types. Today we’re covering GIN indices."
},
{
"code": null,
"e": 662,
"s": 458,
"text": "We’re going to seed a database with increasingly large amounts of data and compare query time with and without a GIN index. You’ll benefit more if you follow along in your SQL editor (I’m using DBeaver)."
},
{
"code": null,
"e": 794,
"s": 662,
"text": "A data structure that makes retrieving data from a database more efficient at the cost of slower insert speeds and more disk space."
},
{
"code": null,
"e": 906,
"s": 794,
"text": "GIN stands for Generalized Inverted Index. In general, an inverted index maps words to its position in a table."
},
{
"code": null,
"e": 959,
"s": 906,
"text": "Below is an abstraction I drew of an inverted index."
},
{
"code": null,
"e": 1115,
"s": 959,
"text": "If we wanted to find sentences in the table with the word lazy without an index, we’d need to iterate over every sentence in the table looking for matches."
},
{
"code": null,
"e": 1257,
"s": 1115,
"text": "But by adding an index, we know in advance which sentences contain the word lazy and can load those directly. This makes things a lot faster!"
},
{
"code": null,
"e": 1404,
"s": 1257,
"text": "This type of index is good for querying composite datatypes, meaning they store more than 1 value. Examples are hStores, Arrays, Ranges and JSONs."
},
{
"code": null,
"e": 1420,
"s": 1404,
"text": "Let’s find out."
},
{
"code": null,
"e": 1475,
"s": 1420,
"text": "Start by creating a table and populating it with data."
},
{
"code": null,
"e": 1798,
"s": 1475,
"text": "# create tableCREATE TABLE articles ( body text, body_indexed text);# add an indexCREATE INDEX articles_search_idx ON articles USING gin (body_indexed gin_trgm_ops);# populate table with dataINSERT INTO articlesSELECT md5(random()::text), md5(random()::text)from ( SELECT * FROM generate_series(1,100000) AS id) AS x;"
},
{
"code": null,
"e": 1894,
"s": 1798,
"text": "Awesome we now have a table called articles with 100k records, and 2 columns of random strings."
},
{
"code": null,
"e": 2076,
"s": 1894,
"text": "If you’re curious about the index. We didn’t index strings directly but used Postgres’s gin_trgm_ops to create trigrams (think ngrams in sklearn) from each string, and indexed that."
},
{
"code": null,
"e": 2120,
"s": 2076,
"text": "The table looks like this in my SQL editor."
},
{
"code": null,
"e": 2185,
"s": 2120,
"text": "I’m going to track query time after each 100k new records I add."
},
{
"code": null,
"e": 2216,
"s": 2185,
"text": "I’ll be running these queries."
},
{
"code": null,
"e": 2334,
"s": 2216,
"text": "SELECT count(*) FROM articles where body ilike '%abc%';SELECT count(*) FROM articles where body_indexed ilike'%abc%';"
},
{
"code": null,
"e": 2562,
"s": 2334,
"text": "The same or a similar query run multiple times can vary in run time. This is due varying system load on your machine and changing query plans. For our purposes ignore fluctuations and look at general trends of time differences."
},
{
"code": null,
"e": 2670,
"s": 2562,
"text": "Wow! That’s a big difference on only 2 million records. Imagine we were querying on a database of billions."
},
{
"code": null,
"e": 2908,
"s": 2670,
"text": "Most of the time we just need to add a B-tree index. But sometimes another index like GIN is more appropriate. Just knowing that other index types are out there can be useful when you eventually come across a problem B-trees don’t solve."
}
] |
How to convert row index number or row index name of an R data frame to a vector?
|
We might want to extract row index irrespective of its type (whether numeric or string) to do some calculations if it is incorrectly set as a row index. It happens during the data collection process or incorrect processing of data. Also, since row indexes are helpful to access row we must have proper names to them instead of values that might makes confusion. For example, if a data frame has row indexes as 43, 94, etc. then it might be confusing. Therefore, we should convert row indexes to a vector or a column if required.
Consider the below data frame (Here, we are using simple sequence of numbers) −
> set.seed(1)
> x1<-rnorm(20,0.01)
> x2<-rpois(20,2)
> x3<-runif(20,2,5)
> df<-data.frame(x1,x2,x3)
> df
x1 x2 x3
1 -0.616453811 3 4.738628
2 0.193643324 2 2.880810
3 -0.825628612 3 3.377197
4 1.605280802 2 2.997184
5 0.339507772 2 3.952611
6 -0.810468384 3 2.774050
7 0.497429052 0 3.435636
8 0.748324705 2 4.298932
9 0.585781352 3 2.252741
10 -0.295388387 3 4.625964
11 1.521781168 2 3.017219
12 0.399843236 4 4.518321
13 -0.611240581 2 3.040050
14 -2.204699887 1 3.001325
15 1.134930918 0 3.429054
16 -0.034933609 0 4.676595
17 -0.006190263 1 4.593018
18 0.953836211 2 3.169969
19 0.831221195 2 4.331962
20 0.603901321 2 4.881854
Converting row index number to a vector −
> Numeric_Vector_of_row_names<-as.numeric(rownames(df))
> Numeric_Vector_of_row_names
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
> is.vector(Numeric_Vector_of_row_names)
[1] TRUE
Now suppose that the row index was not a number as shown below −
> rownames(df)<-LETTERS[1:20]
> df
x1 x2 x3
A -0.616453811 3 4.738628
B 0.193643324 2 2.880810
C -0.825628612 3 3.377197
D 1.605280802 2 2.997184
E 0.339507772 2 3.952611
F -0.810468384 3 2.774050
G 0.497429052 0 3.435636
H 0.748324705 2 4.298932
I 0.585781352 3 2.252741
J -0.295388387 3 4.625964
K 1.521781168 2 3.017219
L 0.399843236 4 4.518321
M -0.611240581 2 3.040050
N -2.204699887 1 3.001325
O 1.134930918 0 3.429054
P -0.034933609 0 4.676595
Q -0.006190263 1 4.593018
R 0.953836211 2 3.169969
S 0.831221195 2 4.331962
T 0.603901321 2 4.881854
These row indexes can be converted to a vector as shown below −
> Row_names_String<-rownames(df)
> Row_names_String
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S"
[20] "T"
> is.vector(Row_names_String)
[1] TRUE
|
[
{
"code": null,
"e": 1591,
"s": 1062,
"text": "We might want to extract row index irrespective of its type (whether numeric or string) to do some calculations if it is incorrectly set as a row index. It happens during the data collection process or incorrect processing of data. Also, since row indexes are helpful to access row we must have proper names to them instead of values that might makes confusion. For example, if a data frame has row indexes as 43, 94, etc. then it might be confusing. Therefore, we should convert row indexes to a vector or a column if required."
},
{
"code": null,
"e": 1671,
"s": 1591,
"text": "Consider the below data frame (Here, we are using simple sequence of numbers) −"
},
{
"code": null,
"e": 2339,
"s": 1671,
"text": "> set.seed(1)\n> x1<-rnorm(20,0.01)\n> x2<-rpois(20,2)\n> x3<-runif(20,2,5)\n> df<-data.frame(x1,x2,x3)\n> df\n x1 x2 x3\n1 -0.616453811 3 4.738628\n2 0.193643324 2 2.880810\n3 -0.825628612 3 3.377197\n4 1.605280802 2 2.997184\n5 0.339507772 2 3.952611\n6 -0.810468384 3 2.774050\n7 0.497429052 0 3.435636\n8 0.748324705 2 4.298932\n9 0.585781352 3 2.252741\n10 -0.295388387 3 4.625964\n11 1.521781168 2 3.017219\n12 0.399843236 4 4.518321\n13 -0.611240581 2 3.040050\n14 -2.204699887 1 3.001325\n15 1.134930918 0 3.429054\n16 -0.034933609 0 4.676595\n17 -0.006190263 1 4.593018\n18 0.953836211 2 3.169969\n19 0.831221195 2 4.331962\n20 0.603901321 2 4.881854"
},
{
"code": null,
"e": 2381,
"s": 2339,
"text": "Converting row index number to a vector −"
},
{
"code": null,
"e": 2572,
"s": 2381,
"text": "> Numeric_Vector_of_row_names<-as.numeric(rownames(df))\n> Numeric_Vector_of_row_names\n[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20\n> is.vector(Numeric_Vector_of_row_names)\n[1] TRUE"
},
{
"code": null,
"e": 2637,
"s": 2572,
"text": "Now suppose that the row index was not a number as shown below −"
},
{
"code": null,
"e": 3212,
"s": 2637,
"text": "> rownames(df)<-LETTERS[1:20]\n> df\n x1 x2 x3\nA -0.616453811 3 4.738628\nB 0.193643324 2 2.880810\nC -0.825628612 3 3.377197\nD 1.605280802 2 2.997184\nE 0.339507772 2 3.952611\nF -0.810468384 3 2.774050\nG 0.497429052 0 3.435636\nH 0.748324705 2 4.298932\nI 0.585781352 3 2.252741\nJ -0.295388387 3 4.625964\nK 1.521781168 2 3.017219\nL 0.399843236 4 4.518321\nM -0.611240581 2 3.040050\nN -2.204699887 1 3.001325\nO 1.134930918 0 3.429054\nP -0.034933609 0 4.676595\nQ -0.006190263 1 4.593018\nR 0.953836211 2 3.169969\nS 0.831221195 2 4.331962\nT 0.603901321 2 4.881854"
},
{
"code": null,
"e": 3276,
"s": 3212,
"text": "These row indexes can be converted to a vector as shown below −"
},
{
"code": null,
"e": 3456,
"s": 3276,
"text": "> Row_names_String<-rownames(df)\n> Row_names_String\n[1] \"A\" \"B\" \"C\" \"D\" \"E\" \"F\" \"G\" \"H\" \"I\" \"J\" \"K\" \"L\" \"M\" \"N\" \"O\" \"P\" \"Q\" \"R\" \"S\"\n[20] \"T\"\n> is.vector(Row_names_String)\n[1] TRUE"
}
] |
Hide or show HTML elements using visibility property in JavaScript - GeeksforGeeks
|
02 Mar, 2021
The visibility property is used to hide or show the content of HTML elements. The visibility property specifies that the element is currently visible on the page. The ‘hidden’ value can be used to hide the element. This hides the element but does not remove the space taken by the element, unlike the display property.
Syntax:
element.style.visibility = 'hidden';
element.style.visibility = 'visible';
Example:
html
<!DOCTYPE html><html> <head> <style> .container { height: 80px; width: 250px; border: 2px solid black; background-color: green; color: white; } </style></head> <body> <div class="container"> <h1>GeeksforGeeks</h1> </div> <p> Click the buttons to show or hide the green box </p> <button onclick="showElement()"> Show Element </button> <button onclick="hideElement()"> Hide Element </button> <script type="text/javascript"> function showElement() { element = document.querySelector('.container'); element.style.visibility = 'visible'; } function hideElement() { element = document.querySelector('.container'); element.style.visibility = 'hidden'; } </script></body> </html>
Output:
ghoshsuman0129
JavaScript-Properties
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer 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 ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24711,
"s": 24683,
"text": "\n02 Mar, 2021"
},
{
"code": null,
"e": 25030,
"s": 24711,
"text": "The visibility property is used to hide or show the content of HTML elements. The visibility property specifies that the element is currently visible on the page. The ‘hidden’ value can be used to hide the element. This hides the element but does not remove the space taken by the element, unlike the display property."
},
{
"code": null,
"e": 25038,
"s": 25030,
"text": "Syntax:"
},
{
"code": null,
"e": 25113,
"s": 25038,
"text": "element.style.visibility = 'hidden';\nelement.style.visibility = 'visible';"
},
{
"code": null,
"e": 25123,
"s": 25113,
"text": "Example: "
},
{
"code": null,
"e": 25128,
"s": 25123,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <style> .container { height: 80px; width: 250px; border: 2px solid black; background-color: green; color: white; } </style></head> <body> <div class=\"container\"> <h1>GeeksforGeeks</h1> </div> <p> Click the buttons to show or hide the green box </p> <button onclick=\"showElement()\"> Show Element </button> <button onclick=\"hideElement()\"> Hide Element </button> <script type=\"text/javascript\"> function showElement() { element = document.querySelector('.container'); element.style.visibility = 'visible'; } function hideElement() { element = document.querySelector('.container'); element.style.visibility = 'hidden'; } </script></body> </html>",
"e": 26021,
"s": 25128,
"text": null
},
{
"code": null,
"e": 26031,
"s": 26021,
"text": "Output: "
},
{
"code": null,
"e": 26050,
"s": 26035,
"text": "ghoshsuman0129"
},
{
"code": null,
"e": 26072,
"s": 26050,
"text": "JavaScript-Properties"
},
{
"code": null,
"e": 26079,
"s": 26072,
"text": "Picked"
},
{
"code": null,
"e": 26090,
"s": 26079,
"text": "JavaScript"
},
{
"code": null,
"e": 26107,
"s": 26090,
"text": "Web Technologies"
},
{
"code": null,
"e": 26134,
"s": 26107,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 26232,
"s": 26134,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26241,
"s": 26232,
"text": "Comments"
},
{
"code": null,
"e": 26254,
"s": 26241,
"text": "Old Comments"
},
{
"code": null,
"e": 26315,
"s": 26254,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26360,
"s": 26315,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 26432,
"s": 26360,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 26484,
"s": 26432,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 26530,
"s": 26484,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 26586,
"s": 26530,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 26619,
"s": 26586,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26681,
"s": 26619,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 26724,
"s": 26681,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How To Apply Data Science To Real Business Problems | by Ben Rogojan | Towards Data Science
|
Focused on E-Commerce and Healthcare
*Heads up, if you want to skip the intro and go straight to the examples, scroll to the first header
Data science and statistics are not magic. They won’t magically fix all of a company’s problems. However, they are useful tools to help companies make more accurate decisions and automate repetitive work and choices that teams need to make.
Machine learning and data science get referenced a lot when referring to natural language processing, imaging recognition and chat bots.
However, you can also apply data science techniques to help your managers make decisions, predict future revenues, segment markets, produce better content and diagnosis patients more effectively.
Below, we are going to discuss some case examples of statistics and applied data science algorithms that can help your business and team produce more accurate results.
This doesn’t require complex hadoop clusters and cloud analytics. Not that those aren’t amazing. Just, let’s get the basics going first!
Before we jump to far down the rabbit hole of technology and hype!
We are going to be giving examples on e-commerce and medical operations.
Our team focuses mostly on practical and applied data science. So we are reaching into our past experiences to show you some awesome but easy to apply ways you can use statistics today to start making better decisions.
The methods below are typically only a small piece of a larger system. We believe that getting these small pieces and details are required to start building systems that are accurate and effective.
Some of these statistical methods won’t even require heavy programming or technical expertise. However, these basic techniques could be applied on a much larger scale in larger systems if implemented correctly.
We are doing this because we know it requires a lot of effort to implement an algorithm.
Teams have to plan properly how they are going to integrate databases, business logic, algorithms, and new policies to ensure projects succeed.
That takes a large amount of resources and time.
Whether you are an insurance company that deals with medical, property, or vehicle claims. Insurance fraud is a major problem.
How do they solve it? Insurance providers have to either set up an algorithm, or have auditors manually go through and see if a claim is fraudulent or not.
Believe it or not, there are still a large handful of insurance companies who do this manually(In this case, we are considering getting a data feed from a database and filtering in excel as manual).
Insurance providers will put a lot of effort into auditing. For at least these two reasons:
To get money back
To attempt to deter future insurance fraud claims
The issue here is this takes up valuable resource hours and if they incorrectly identify claims, it can cost even more money in salaries and other resources than what costs are recouped from getting money back from fraudulent claims.
In this example, an Insurance provider named Itena has created an algorithm to help increase the speed at which their team can handle claims.
So how does Itena know if the algorithm they have developed is worth it?
Well, what if you had a mathematical theorem to analyze your algorithm!
Woah! That is so “meta”.
Just think of it as a confidence check, that can later help them calculate whether it is worth the costs to invest in the algorithm
In this case, they are going to use Bayes Theorem
What Bayes is great at doing is providing statistical backing for how accurate the information they are being provided actually is.
How much can they trust their algorithm? Since more than likely they will have both false positives and false negatives. How accurate is their algorithm really?
Let’s say that Itena’s data science team knows that 2% of the claims received are fraudulent.
They calculate that they could save $1 million dollars if they correctly identify all the claims that are fraudulent!
Woah! They just got all your executives signing off on this! I mean, it is $1 million dollars! Even if the company nets $100 million dollars. This is a great save
Awesome!
So the Itena data science team develops an algorithm to detect fraudulent claims.
It isn’t perfect, but it is a great start!
But, how accurate is it really? Sure, they know that 85% of fraudulent claims that are predicted fraudulent actually are?
As good data scientists, and scientists in general. They also know you have to check for errors as well. Like false positives.
For them to go to management and to say that this test is 85% accurate is incorrect! Look in the normal claims column.
They also have a 4% false positive rate. How does that come into play?
This is when they bring in our old friend Bayes Theorem.
Bayes Theorem is great for testing how much they should trust tests.
Algorithms, like medical tests, can have false positives.
Just like some medical exams can return false positives for cancer. Algorithms can return false positives for fraudulent claims, whether you should get a loan or not, and if you should get a discount or not when you visit Amazon.com.
We know the data science team could possibly save the company $1 million dollars. However, they are also going to be costing the Itena money with resource hours. So they need to make sure they return more than they cost!
So how accurate is this algorithm?
They might actually be surprised to find out how inaccurate it actually is!
Here is the scratch math:
P(Fraud Claim) = 2%
P(Positively Flagged As Fraud| True Fraud Claim) = 85%
P(Not Fraud) = 98%
P(Flagged Fraud Claim | True Not Fraud) = 4%
P(Fraud Claim)*P(Positively Flagged As Fraud | True Fraud Claim)/
(P(Fraud Claim)*P(Positively Flagged As Fraud | True Fraud Claim) + P(Flagged Fraud Claim | True Not Fraud)+P(Not Fraud))
In this case only about 30% predicted claims predicted to be fraudulent actually are according to Bayes Theorem.
Why?
It is due to the fact that only 2% of claims are fraudulent. That means, although the algorithm is 85% accurate. It is only 85% accurate for 2% worth of the data.
It also incorrectly classifiys 4% of 98% of their data.
They have a mucher bigger set of data in the false negatives than in the true positives.
It is kind of intersting when you really sit and think about it.
Now the question is, can they justify the savings? What will it costs the company to look into all the claims? This really depends on the claim size.
If they are dealing with $7 upcoding in medical claims...maybe not so much.
On the other hand, if it is $10,000 car accident claims, the company will still want to jump on it!
Luckily we have computers that can run these algorithms quickly and hopefully have an amazing process set up that quickly allows claims to be adjudicated.
We do want to put this into perspective if the computer were not there.
What if instead you had the same accuracy and had a human performing the task. Let’s say it cost them $200 worth of resources to perform the analysis on one claim!
If the claim is worth $500, is it worth the time?
E-commerce is predicted to have over $2 trillion dollars worth of purchases in 2017. Although plenty of people go straight through Amazon or Alibaba, there are plenty of other sites trying to get customers to buy their products.
This involves heavy amounts of cross platform marketing, content marketing, and advertising.
How do companies know if their ads or sites where they promote are actually effective? Are the impressions and engagements they are getting actually turning into real dollars?
How do you start to answer these questions?
Let’s say your company sells kitchen equipment online.
You pay several sites to cross promote your products and e-commerce site. You know the average purchase rate you get from each site as you have been diligent about tracking cookies and keeping a clean database.
You want to know how much money you should invest into future campaigns. Based off of current data, you know that 10 people an hour purchase a product if they come from “site A”. You believe that as long as you have a greater than 80% chance of keeping a rate of at least 6 per hour. You can justify the cost to market.
How can we figure this out?
Well, we can use poisson’s distribution to help us out.
If you already know that on average 10 people buy products from your site every hour, you can calculate the probability that n amount of people will show up every hour.
You can take this information to an even more granular level. That would allow you to utilize a combination of seasonality techniques with the poisson distribution to predict future revenues and allocate funds more effectively.
That would be require a more extensive explanation and also a lot of data. For now, we are going to focus on this first problem.
We will utilize the Poisson cumulative probability function. Essentially, you are just adding each probabilty greater than 6 from the poisson distribution equation.
If you run it for a lambda of 10, you get a graph like the one below.
Using Poisson cumulative probability function you will get about 94%
So your company can continue to pay for marketing on Site A!
However!
If it had only been about 7 an hour. Then you would only have a 70% chance of selling at least 6 items an hour! So the program would have to be cut.
You can easily set this threshold and start to create an auction type system where your budget is automatically allocated based on a ratio of future returns and probability of purchases!
That sounds like a fun project!
Don’t get us wrong. At the end of the day, data science can be used to create systems that interact with your customers.
However, it can also be used to help increase the rate of accurate decision making. As well as develop systems that make decisions with FAIL SAFES that limit the amount of simple and complex decisions that are made by analysts and management.
Let’s say you work for a hospital and you noticed the cost of a specific surgery has been going up consistently month over month for the past few years.
You wonder if there might be a linear relationship between the months and cost of surgery.
Step one of your analysis would be to figure out if there was a model that could be built to predict the rising cost of surgery.
There would be a second step that we are not going to go over which would be to figure out the why!
Data science does not only supply the tools to create models.
It also supplies the tools the allow people to figure out the why! So after you finish with the model, you would want to look into why.
Maybe you would theorize it is increasing salaries, equipment costs, increased complexity of steps, etc. That would require more complex data compared to price per surgery and month.
If your scatter plot seems to follow a linear pattern like the one below. You can start to look at the problem with the concept of linear regression or even multivariate linear regression . This depends on what looks like it will fit(or even better, which model your automated system detects!)
This is one of the simplest forms of predictions as you are simply trying to create a trend line.
You could estimate this by taking a line from your starting point to your end point. However, this might not be the “Goodness-of-Fit”
Although you can use excel, python, R or just about any other language to find a linear regression model. We wanted to show you a video on how to do it by hand.
It involves a lot of summations, but don’t let that scare you. In the end, the reason most people don’t do it by hand is not because the math is hard
Instead, the math is pretty straight forward. However, a lot can go wrong. Especially with simple calculations.
Just because you have finished the model, does not mean you are done! Your data sets are not often perfect fit to the line. So it is important to test the validity of your model.
There are several methods. Below we will discuss the R-Squared error.
What is R-Squared? also known as the coefficient of determination.
Most models have one or several methods to calculate the accuracy of a model.
We have ROC curves, AUC, Mean Squared Error, Variance, and so on.
In this case, R-Squared error is equal to:
The Sum Squared regression error is the delta between the current point you are examining and what is the corresponding point on the model line.
Let the point on your trend line be equal to ŷ
((mx1+b)-ŷ )2+...((mxn+b)-ŷ )2
The total variatian is the difference between the point on the model and the average y from the actual data.
(y1-y ̄) 2+ (yn-y ̄)2
So in this case, we can run linear regression in excel, R, or python and get the model that fits the line pretty well.
In this case, based off the data the R-Squared error is .93. This is really only stating the amount of explained variance.
The importance is to remember what the model is being used for! Not every line that fits is correct!
Especially when you start developing more complex models!
This is why data scientists don’t just create models. They also look for the why!
That is one of the biggest changes in the last 20 or so years! We have the power to give context. Before statistics were limited to numbers.
They could only tell what had happened and what might happen.
There was very little information on what needed to change! Now data scientists can give the why! So we have the ability to actually give strategic advice when we know the why.
For instance, in this case, you can show your medical directors this simple trend and then analyze the why!
When we go out to help teams. Part of our focus is helping them go to their directors with their analysis to get their approval.
This is the start of being data driven. It requires curiosity and a little bit of entrepreneurial spirit.
With the discovery above image if you could find out that you can reduce surgery costs by $5.37 on average and the hospital does 100,000 surgeries a year.
You can prove that you saved your company $537,000 annually. Hopefully you get a raise!
It is still important to remember that “All models are wrong, but some are useful”.
Logistic regression, unlike linear regression has a binary output. Typically it is pass or fail, 1 or 0. Linear regression’s output is continuous where as logistic is defined typically by yes or no.
This is why it is used a lot for business tasks like deciding whether you should give someone a loan , it can predict if a patient has a specific disease or not and many other yes or no type questions that plague us every day.
Using logistic regression allows for multiple variables to be utilized. So even if you have a complex business decision that needs to take several different variables, logistic regression can be a great solution.
We can look back to the example of the fraudulent claims. The algorithm that determines whether or not the claim is fraudulent could be a logistic regression model? You might have certain information about if the claim is fraudulent or not. You might have location, patient information, hospital stats, etc.
Let’s say you wanted to know if a doctor was actually doing open heart surgery and not just pretending to bill for it (it’s a stretch, but go with it).
You might know that the same claim for open heart surgery should also have billed for specific equipment usage like an MRI or Lab work. If this did not occur, there is a good chance it is fraudulent.
You can also engineer some features. You could find the probability that the heart surgery from that specific doctor is fradulent based off of passed claims and audits, you could count the number of surgeries done per day by doctor, or anything else your team has subject matter expert or contextual data supports as playing a role in fraudulent claims.
This model is much harder to calculate by hand. Luckily! That is why R and Python are amazing languages. Here is the R code implementation(glm stands for the general linear model libraries). This is basically a 1 line implementation
Note: This is a little misleading. Although it seams like 1 line implementation. There is probably a lot of data cleansing and normalizing prior to using the formula before!
model <- glm(formula = FraudulentClaim ~ ., family = binomial(link = "logit"), data = train)
To explain some of this implementation. The formula variable is set up with the output on the left side. Then the tilde symbol states that “FraudulentClaims” is dependent on the period. In R, the period represents all the variables in the training set except the dependent variable.
If your team only believes it is another set of variables then they could use the example below instead of the period.
model <- glm(formula = FraudulentClaim ~ income + age + X, family = binomial(link = "logit"), data = train)
The mathematical model would look like:
picture from http://www.saedsayad.com/logistic_regression.htm[/caption]
Each of those “b” variables represents another possible variable. It could be sex, age, income(all normalized typically!)
This statistical principal could also be used in other hospital tasks like readmission, diagnostics, and fraudulent claims
These were a few basic case studies where we showed how you could implement some theorems and algorithms into your decisions processes.
They are a great start and could be used in much larger project to help improve your data science and companies data driven culture!
With that, comes a few things we would like to note
Some pros and cons with algorithm and data science usage
Focuses On Data Driven Decisions Over Politics and Gut Feelings
Automates Decisions That Might Be Financially and Mentally Taxing
Improves Consistency, Accuracy And Forces Teams To Draw Out Their Decisions Processes
Reduce Time Spent On Tasks
If An Algorithm Is Incorrect The Team Might Overly Trust It
Next Data Science Post
Our next post our hope is to focus on some more technical and programming based implementations and applications! If you have any specific case studies you would like us to explore us, please let us know!!
Other Data Science Resources You Might Enjoy:
Personalization With Contextual Bandits
How To Survive Corporate Politics As A Data Scientist
What Is A Decision Tree
|
[
{
"code": null,
"e": 208,
"s": 171,
"text": "Focused on E-Commerce and Healthcare"
},
{
"code": null,
"e": 309,
"s": 208,
"text": "*Heads up, if you want to skip the intro and go straight to the examples, scroll to the first header"
},
{
"code": null,
"e": 550,
"s": 309,
"text": "Data science and statistics are not magic. They won’t magically fix all of a company’s problems. However, they are useful tools to help companies make more accurate decisions and automate repetitive work and choices that teams need to make."
},
{
"code": null,
"e": 687,
"s": 550,
"text": "Machine learning and data science get referenced a lot when referring to natural language processing, imaging recognition and chat bots."
},
{
"code": null,
"e": 883,
"s": 687,
"text": "However, you can also apply data science techniques to help your managers make decisions, predict future revenues, segment markets, produce better content and diagnosis patients more effectively."
},
{
"code": null,
"e": 1051,
"s": 883,
"text": "Below, we are going to discuss some case examples of statistics and applied data science algorithms that can help your business and team produce more accurate results."
},
{
"code": null,
"e": 1188,
"s": 1051,
"text": "This doesn’t require complex hadoop clusters and cloud analytics. Not that those aren’t amazing. Just, let’s get the basics going first!"
},
{
"code": null,
"e": 1255,
"s": 1188,
"text": "Before we jump to far down the rabbit hole of technology and hype!"
},
{
"code": null,
"e": 1328,
"s": 1255,
"text": "We are going to be giving examples on e-commerce and medical operations."
},
{
"code": null,
"e": 1547,
"s": 1328,
"text": "Our team focuses mostly on practical and applied data science. So we are reaching into our past experiences to show you some awesome but easy to apply ways you can use statistics today to start making better decisions."
},
{
"code": null,
"e": 1745,
"s": 1547,
"text": "The methods below are typically only a small piece of a larger system. We believe that getting these small pieces and details are required to start building systems that are accurate and effective."
},
{
"code": null,
"e": 1956,
"s": 1745,
"text": "Some of these statistical methods won’t even require heavy programming or technical expertise. However, these basic techniques could be applied on a much larger scale in larger systems if implemented correctly."
},
{
"code": null,
"e": 2045,
"s": 1956,
"text": "We are doing this because we know it requires a lot of effort to implement an algorithm."
},
{
"code": null,
"e": 2189,
"s": 2045,
"text": "Teams have to plan properly how they are going to integrate databases, business logic, algorithms, and new policies to ensure projects succeed."
},
{
"code": null,
"e": 2238,
"s": 2189,
"text": "That takes a large amount of resources and time."
},
{
"code": null,
"e": 2365,
"s": 2238,
"text": "Whether you are an insurance company that deals with medical, property, or vehicle claims. Insurance fraud is a major problem."
},
{
"code": null,
"e": 2521,
"s": 2365,
"text": "How do they solve it? Insurance providers have to either set up an algorithm, or have auditors manually go through and see if a claim is fraudulent or not."
},
{
"code": null,
"e": 2720,
"s": 2521,
"text": "Believe it or not, there are still a large handful of insurance companies who do this manually(In this case, we are considering getting a data feed from a database and filtering in excel as manual)."
},
{
"code": null,
"e": 2812,
"s": 2720,
"text": "Insurance providers will put a lot of effort into auditing. For at least these two reasons:"
},
{
"code": null,
"e": 2830,
"s": 2812,
"text": "To get money back"
},
{
"code": null,
"e": 2880,
"s": 2830,
"text": "To attempt to deter future insurance fraud claims"
},
{
"code": null,
"e": 3114,
"s": 2880,
"text": "The issue here is this takes up valuable resource hours and if they incorrectly identify claims, it can cost even more money in salaries and other resources than what costs are recouped from getting money back from fraudulent claims."
},
{
"code": null,
"e": 3256,
"s": 3114,
"text": "In this example, an Insurance provider named Itena has created an algorithm to help increase the speed at which their team can handle claims."
},
{
"code": null,
"e": 3329,
"s": 3256,
"text": "So how does Itena know if the algorithm they have developed is worth it?"
},
{
"code": null,
"e": 3401,
"s": 3329,
"text": "Well, what if you had a mathematical theorem to analyze your algorithm!"
},
{
"code": null,
"e": 3426,
"s": 3401,
"text": "Woah! That is so “meta”."
},
{
"code": null,
"e": 3558,
"s": 3426,
"text": "Just think of it as a confidence check, that can later help them calculate whether it is worth the costs to invest in the algorithm"
},
{
"code": null,
"e": 3608,
"s": 3558,
"text": "In this case, they are going to use Bayes Theorem"
},
{
"code": null,
"e": 3740,
"s": 3608,
"text": "What Bayes is great at doing is providing statistical backing for how accurate the information they are being provided actually is."
},
{
"code": null,
"e": 3901,
"s": 3740,
"text": "How much can they trust their algorithm? Since more than likely they will have both false positives and false negatives. How accurate is their algorithm really?"
},
{
"code": null,
"e": 3995,
"s": 3901,
"text": "Let’s say that Itena’s data science team knows that 2% of the claims received are fraudulent."
},
{
"code": null,
"e": 4113,
"s": 3995,
"text": "They calculate that they could save $1 million dollars if they correctly identify all the claims that are fraudulent!"
},
{
"code": null,
"e": 4276,
"s": 4113,
"text": "Woah! They just got all your executives signing off on this! I mean, it is $1 million dollars! Even if the company nets $100 million dollars. This is a great save"
},
{
"code": null,
"e": 4285,
"s": 4276,
"text": "Awesome!"
},
{
"code": null,
"e": 4367,
"s": 4285,
"text": "So the Itena data science team develops an algorithm to detect fraudulent claims."
},
{
"code": null,
"e": 4410,
"s": 4367,
"text": "It isn’t perfect, but it is a great start!"
},
{
"code": null,
"e": 4532,
"s": 4410,
"text": "But, how accurate is it really? Sure, they know that 85% of fraudulent claims that are predicted fraudulent actually are?"
},
{
"code": null,
"e": 4659,
"s": 4532,
"text": "As good data scientists, and scientists in general. They also know you have to check for errors as well. Like false positives."
},
{
"code": null,
"e": 4778,
"s": 4659,
"text": "For them to go to management and to say that this test is 85% accurate is incorrect! Look in the normal claims column."
},
{
"code": null,
"e": 4849,
"s": 4778,
"text": "They also have a 4% false positive rate. How does that come into play?"
},
{
"code": null,
"e": 4906,
"s": 4849,
"text": "This is when they bring in our old friend Bayes Theorem."
},
{
"code": null,
"e": 4975,
"s": 4906,
"text": "Bayes Theorem is great for testing how much they should trust tests."
},
{
"code": null,
"e": 5033,
"s": 4975,
"text": "Algorithms, like medical tests, can have false positives."
},
{
"code": null,
"e": 5267,
"s": 5033,
"text": "Just like some medical exams can return false positives for cancer. Algorithms can return false positives for fraudulent claims, whether you should get a loan or not, and if you should get a discount or not when you visit Amazon.com."
},
{
"code": null,
"e": 5488,
"s": 5267,
"text": "We know the data science team could possibly save the company $1 million dollars. However, they are also going to be costing the Itena money with resource hours. So they need to make sure they return more than they cost!"
},
{
"code": null,
"e": 5523,
"s": 5488,
"text": "So how accurate is this algorithm?"
},
{
"code": null,
"e": 5599,
"s": 5523,
"text": "They might actually be surprised to find out how inaccurate it actually is!"
},
{
"code": null,
"e": 5625,
"s": 5599,
"text": "Here is the scratch math:"
},
{
"code": null,
"e": 5645,
"s": 5625,
"text": "P(Fraud Claim) = 2%"
},
{
"code": null,
"e": 5700,
"s": 5645,
"text": "P(Positively Flagged As Fraud| True Fraud Claim) = 85%"
},
{
"code": null,
"e": 5719,
"s": 5700,
"text": "P(Not Fraud) = 98%"
},
{
"code": null,
"e": 5764,
"s": 5719,
"text": "P(Flagged Fraud Claim | True Not Fraud) = 4%"
},
{
"code": null,
"e": 5830,
"s": 5764,
"text": "P(Fraud Claim)*P(Positively Flagged As Fraud | True Fraud Claim)/"
},
{
"code": null,
"e": 5952,
"s": 5830,
"text": "(P(Fraud Claim)*P(Positively Flagged As Fraud | True Fraud Claim) + P(Flagged Fraud Claim | True Not Fraud)+P(Not Fraud))"
},
{
"code": null,
"e": 6065,
"s": 5952,
"text": "In this case only about 30% predicted claims predicted to be fraudulent actually are according to Bayes Theorem."
},
{
"code": null,
"e": 6070,
"s": 6065,
"text": "Why?"
},
{
"code": null,
"e": 6233,
"s": 6070,
"text": "It is due to the fact that only 2% of claims are fraudulent. That means, although the algorithm is 85% accurate. It is only 85% accurate for 2% worth of the data."
},
{
"code": null,
"e": 6289,
"s": 6233,
"text": "It also incorrectly classifiys 4% of 98% of their data."
},
{
"code": null,
"e": 6378,
"s": 6289,
"text": "They have a mucher bigger set of data in the false negatives than in the true positives."
},
{
"code": null,
"e": 6443,
"s": 6378,
"text": "It is kind of intersting when you really sit and think about it."
},
{
"code": null,
"e": 6593,
"s": 6443,
"text": "Now the question is, can they justify the savings? What will it costs the company to look into all the claims? This really depends on the claim size."
},
{
"code": null,
"e": 6669,
"s": 6593,
"text": "If they are dealing with $7 upcoding in medical claims...maybe not so much."
},
{
"code": null,
"e": 6769,
"s": 6669,
"text": "On the other hand, if it is $10,000 car accident claims, the company will still want to jump on it!"
},
{
"code": null,
"e": 6924,
"s": 6769,
"text": "Luckily we have computers that can run these algorithms quickly and hopefully have an amazing process set up that quickly allows claims to be adjudicated."
},
{
"code": null,
"e": 6996,
"s": 6924,
"text": "We do want to put this into perspective if the computer were not there."
},
{
"code": null,
"e": 7160,
"s": 6996,
"text": "What if instead you had the same accuracy and had a human performing the task. Let’s say it cost them $200 worth of resources to perform the analysis on one claim!"
},
{
"code": null,
"e": 7210,
"s": 7160,
"text": "If the claim is worth $500, is it worth the time?"
},
{
"code": null,
"e": 7439,
"s": 7210,
"text": "E-commerce is predicted to have over $2 trillion dollars worth of purchases in 2017. Although plenty of people go straight through Amazon or Alibaba, there are plenty of other sites trying to get customers to buy their products."
},
{
"code": null,
"e": 7532,
"s": 7439,
"text": "This involves heavy amounts of cross platform marketing, content marketing, and advertising."
},
{
"code": null,
"e": 7708,
"s": 7532,
"text": "How do companies know if their ads or sites where they promote are actually effective? Are the impressions and engagements they are getting actually turning into real dollars?"
},
{
"code": null,
"e": 7752,
"s": 7708,
"text": "How do you start to answer these questions?"
},
{
"code": null,
"e": 7807,
"s": 7752,
"text": "Let’s say your company sells kitchen equipment online."
},
{
"code": null,
"e": 8018,
"s": 7807,
"text": "You pay several sites to cross promote your products and e-commerce site. You know the average purchase rate you get from each site as you have been diligent about tracking cookies and keeping a clean database."
},
{
"code": null,
"e": 8338,
"s": 8018,
"text": "You want to know how much money you should invest into future campaigns. Based off of current data, you know that 10 people an hour purchase a product if they come from “site A”. You believe that as long as you have a greater than 80% chance of keeping a rate of at least 6 per hour. You can justify the cost to market."
},
{
"code": null,
"e": 8366,
"s": 8338,
"text": "How can we figure this out?"
},
{
"code": null,
"e": 8422,
"s": 8366,
"text": "Well, we can use poisson’s distribution to help us out."
},
{
"code": null,
"e": 8591,
"s": 8422,
"text": "If you already know that on average 10 people buy products from your site every hour, you can calculate the probability that n amount of people will show up every hour."
},
{
"code": null,
"e": 8819,
"s": 8591,
"text": "You can take this information to an even more granular level. That would allow you to utilize a combination of seasonality techniques with the poisson distribution to predict future revenues and allocate funds more effectively."
},
{
"code": null,
"e": 8948,
"s": 8819,
"text": "That would be require a more extensive explanation and also a lot of data. For now, we are going to focus on this first problem."
},
{
"code": null,
"e": 9113,
"s": 8948,
"text": "We will utilize the Poisson cumulative probability function. Essentially, you are just adding each probabilty greater than 6 from the poisson distribution equation."
},
{
"code": null,
"e": 9183,
"s": 9113,
"text": "If you run it for a lambda of 10, you get a graph like the one below."
},
{
"code": null,
"e": 9252,
"s": 9183,
"text": "Using Poisson cumulative probability function you will get about 94%"
},
{
"code": null,
"e": 9313,
"s": 9252,
"text": "So your company can continue to pay for marketing on Site A!"
},
{
"code": null,
"e": 9322,
"s": 9313,
"text": "However!"
},
{
"code": null,
"e": 9471,
"s": 9322,
"text": "If it had only been about 7 an hour. Then you would only have a 70% chance of selling at least 6 items an hour! So the program would have to be cut."
},
{
"code": null,
"e": 9658,
"s": 9471,
"text": "You can easily set this threshold and start to create an auction type system where your budget is automatically allocated based on a ratio of future returns and probability of purchases!"
},
{
"code": null,
"e": 9690,
"s": 9658,
"text": "That sounds like a fun project!"
},
{
"code": null,
"e": 9811,
"s": 9690,
"text": "Don’t get us wrong. At the end of the day, data science can be used to create systems that interact with your customers."
},
{
"code": null,
"e": 10054,
"s": 9811,
"text": "However, it can also be used to help increase the rate of accurate decision making. As well as develop systems that make decisions with FAIL SAFES that limit the amount of simple and complex decisions that are made by analysts and management."
},
{
"code": null,
"e": 10207,
"s": 10054,
"text": "Let’s say you work for a hospital and you noticed the cost of a specific surgery has been going up consistently month over month for the past few years."
},
{
"code": null,
"e": 10298,
"s": 10207,
"text": "You wonder if there might be a linear relationship between the months and cost of surgery."
},
{
"code": null,
"e": 10427,
"s": 10298,
"text": "Step one of your analysis would be to figure out if there was a model that could be built to predict the rising cost of surgery."
},
{
"code": null,
"e": 10527,
"s": 10427,
"text": "There would be a second step that we are not going to go over which would be to figure out the why!"
},
{
"code": null,
"e": 10589,
"s": 10527,
"text": "Data science does not only supply the tools to create models."
},
{
"code": null,
"e": 10725,
"s": 10589,
"text": "It also supplies the tools the allow people to figure out the why! So after you finish with the model, you would want to look into why."
},
{
"code": null,
"e": 10908,
"s": 10725,
"text": "Maybe you would theorize it is increasing salaries, equipment costs, increased complexity of steps, etc. That would require more complex data compared to price per surgery and month."
},
{
"code": null,
"e": 11202,
"s": 10908,
"text": "If your scatter plot seems to follow a linear pattern like the one below. You can start to look at the problem with the concept of linear regression or even multivariate linear regression . This depends on what looks like it will fit(or even better, which model your automated system detects!)"
},
{
"code": null,
"e": 11300,
"s": 11202,
"text": "This is one of the simplest forms of predictions as you are simply trying to create a trend line."
},
{
"code": null,
"e": 11434,
"s": 11300,
"text": "You could estimate this by taking a line from your starting point to your end point. However, this might not be the “Goodness-of-Fit”"
},
{
"code": null,
"e": 11595,
"s": 11434,
"text": "Although you can use excel, python, R or just about any other language to find a linear regression model. We wanted to show you a video on how to do it by hand."
},
{
"code": null,
"e": 11745,
"s": 11595,
"text": "It involves a lot of summations, but don’t let that scare you. In the end, the reason most people don’t do it by hand is not because the math is hard"
},
{
"code": null,
"e": 11857,
"s": 11745,
"text": "Instead, the math is pretty straight forward. However, a lot can go wrong. Especially with simple calculations."
},
{
"code": null,
"e": 12036,
"s": 11857,
"text": "Just because you have finished the model, does not mean you are done! Your data sets are not often perfect fit to the line. So it is important to test the validity of your model."
},
{
"code": null,
"e": 12106,
"s": 12036,
"text": "There are several methods. Below we will discuss the R-Squared error."
},
{
"code": null,
"e": 12173,
"s": 12106,
"text": "What is R-Squared? also known as the coefficient of determination."
},
{
"code": null,
"e": 12251,
"s": 12173,
"text": "Most models have one or several methods to calculate the accuracy of a model."
},
{
"code": null,
"e": 12317,
"s": 12251,
"text": "We have ROC curves, AUC, Mean Squared Error, Variance, and so on."
},
{
"code": null,
"e": 12360,
"s": 12317,
"text": "In this case, R-Squared error is equal to:"
},
{
"code": null,
"e": 12505,
"s": 12360,
"text": "The Sum Squared regression error is the delta between the current point you are examining and what is the corresponding point on the model line."
},
{
"code": null,
"e": 12553,
"s": 12505,
"text": "Let the point on your trend line be equal to ŷ"
},
{
"code": null,
"e": 12586,
"s": 12553,
"text": "((mx1+b)-ŷ )2+...((mxn+b)-ŷ )2"
},
{
"code": null,
"e": 12695,
"s": 12586,
"text": "The total variatian is the difference between the point on the model and the average y from the actual data."
},
{
"code": null,
"e": 12717,
"s": 12695,
"text": "(y1-y ̄) 2+ (yn-y ̄)2"
},
{
"code": null,
"e": 12836,
"s": 12717,
"text": "So in this case, we can run linear regression in excel, R, or python and get the model that fits the line pretty well."
},
{
"code": null,
"e": 12959,
"s": 12836,
"text": "In this case, based off the data the R-Squared error is .93. This is really only stating the amount of explained variance."
},
{
"code": null,
"e": 13060,
"s": 12959,
"text": "The importance is to remember what the model is being used for! Not every line that fits is correct!"
},
{
"code": null,
"e": 13118,
"s": 13060,
"text": "Especially when you start developing more complex models!"
},
{
"code": null,
"e": 13200,
"s": 13118,
"text": "This is why data scientists don’t just create models. They also look for the why!"
},
{
"code": null,
"e": 13341,
"s": 13200,
"text": "That is one of the biggest changes in the last 20 or so years! We have the power to give context. Before statistics were limited to numbers."
},
{
"code": null,
"e": 13403,
"s": 13341,
"text": "They could only tell what had happened and what might happen."
},
{
"code": null,
"e": 13580,
"s": 13403,
"text": "There was very little information on what needed to change! Now data scientists can give the why! So we have the ability to actually give strategic advice when we know the why."
},
{
"code": null,
"e": 13688,
"s": 13580,
"text": "For instance, in this case, you can show your medical directors this simple trend and then analyze the why!"
},
{
"code": null,
"e": 13817,
"s": 13688,
"text": "When we go out to help teams. Part of our focus is helping them go to their directors with their analysis to get their approval."
},
{
"code": null,
"e": 13923,
"s": 13817,
"text": "This is the start of being data driven. It requires curiosity and a little bit of entrepreneurial spirit."
},
{
"code": null,
"e": 14078,
"s": 13923,
"text": "With the discovery above image if you could find out that you can reduce surgery costs by $5.37 on average and the hospital does 100,000 surgeries a year."
},
{
"code": null,
"e": 14166,
"s": 14078,
"text": "You can prove that you saved your company $537,000 annually. Hopefully you get a raise!"
},
{
"code": null,
"e": 14250,
"s": 14166,
"text": "It is still important to remember that “All models are wrong, but some are useful”."
},
{
"code": null,
"e": 14449,
"s": 14250,
"text": "Logistic regression, unlike linear regression has a binary output. Typically it is pass or fail, 1 or 0. Linear regression’s output is continuous where as logistic is defined typically by yes or no."
},
{
"code": null,
"e": 14676,
"s": 14449,
"text": "This is why it is used a lot for business tasks like deciding whether you should give someone a loan , it can predict if a patient has a specific disease or not and many other yes or no type questions that plague us every day."
},
{
"code": null,
"e": 14889,
"s": 14676,
"text": "Using logistic regression allows for multiple variables to be utilized. So even if you have a complex business decision that needs to take several different variables, logistic regression can be a great solution."
},
{
"code": null,
"e": 15197,
"s": 14889,
"text": "We can look back to the example of the fraudulent claims. The algorithm that determines whether or not the claim is fraudulent could be a logistic regression model? You might have certain information about if the claim is fraudulent or not. You might have location, patient information, hospital stats, etc."
},
{
"code": null,
"e": 15349,
"s": 15197,
"text": "Let’s say you wanted to know if a doctor was actually doing open heart surgery and not just pretending to bill for it (it’s a stretch, but go with it)."
},
{
"code": null,
"e": 15549,
"s": 15349,
"text": "You might know that the same claim for open heart surgery should also have billed for specific equipment usage like an MRI or Lab work. If this did not occur, there is a good chance it is fraudulent."
},
{
"code": null,
"e": 15903,
"s": 15549,
"text": "You can also engineer some features. You could find the probability that the heart surgery from that specific doctor is fradulent based off of passed claims and audits, you could count the number of surgeries done per day by doctor, or anything else your team has subject matter expert or contextual data supports as playing a role in fraudulent claims."
},
{
"code": null,
"e": 16136,
"s": 15903,
"text": "This model is much harder to calculate by hand. Luckily! That is why R and Python are amazing languages. Here is the R code implementation(glm stands for the general linear model libraries). This is basically a 1 line implementation"
},
{
"code": null,
"e": 16310,
"s": 16136,
"text": "Note: This is a little misleading. Although it seams like 1 line implementation. There is probably a lot of data cleansing and normalizing prior to using the formula before!"
},
{
"code": null,
"e": 16407,
"s": 16310,
"text": "model <- glm(formula = FraudulentClaim ~ ., family = binomial(link = \"logit\"), data = train)"
},
{
"code": null,
"e": 16690,
"s": 16407,
"text": "To explain some of this implementation. The formula variable is set up with the output on the left side. Then the tilde symbol states that “FraudulentClaims” is dependent on the period. In R, the period represents all the variables in the training set except the dependent variable."
},
{
"code": null,
"e": 16809,
"s": 16690,
"text": "If your team only believes it is another set of variables then they could use the example below instead of the period."
},
{
"code": null,
"e": 16921,
"s": 16809,
"text": "model <- glm(formula = FraudulentClaim ~ income + age + X, family = binomial(link = \"logit\"), data = train)"
},
{
"code": null,
"e": 16961,
"s": 16921,
"text": "The mathematical model would look like:"
},
{
"code": null,
"e": 17033,
"s": 16961,
"text": "picture from http://www.saedsayad.com/logistic_regression.htm[/caption]"
},
{
"code": null,
"e": 17155,
"s": 17033,
"text": "Each of those “b” variables represents another possible variable. It could be sex, age, income(all normalized typically!)"
},
{
"code": null,
"e": 17278,
"s": 17155,
"text": "This statistical principal could also be used in other hospital tasks like readmission, diagnostics, and fraudulent claims"
},
{
"code": null,
"e": 17414,
"s": 17278,
"text": "These were a few basic case studies where we showed how you could implement some theorems and algorithms into your decisions processes."
},
{
"code": null,
"e": 17547,
"s": 17414,
"text": "They are a great start and could be used in much larger project to help improve your data science and companies data driven culture!"
},
{
"code": null,
"e": 17599,
"s": 17547,
"text": "With that, comes a few things we would like to note"
},
{
"code": null,
"e": 17656,
"s": 17599,
"text": "Some pros and cons with algorithm and data science usage"
},
{
"code": null,
"e": 17720,
"s": 17656,
"text": "Focuses On Data Driven Decisions Over Politics and Gut Feelings"
},
{
"code": null,
"e": 17786,
"s": 17720,
"text": "Automates Decisions That Might Be Financially and Mentally Taxing"
},
{
"code": null,
"e": 17872,
"s": 17786,
"text": "Improves Consistency, Accuracy And Forces Teams To Draw Out Their Decisions Processes"
},
{
"code": null,
"e": 17899,
"s": 17872,
"text": "Reduce Time Spent On Tasks"
},
{
"code": null,
"e": 17959,
"s": 17899,
"text": "If An Algorithm Is Incorrect The Team Might Overly Trust It"
},
{
"code": null,
"e": 17982,
"s": 17959,
"text": "Next Data Science Post"
},
{
"code": null,
"e": 18188,
"s": 17982,
"text": "Our next post our hope is to focus on some more technical and programming based implementations and applications! If you have any specific case studies you would like us to explore us, please let us know!!"
},
{
"code": null,
"e": 18234,
"s": 18188,
"text": "Other Data Science Resources You Might Enjoy:"
},
{
"code": null,
"e": 18274,
"s": 18234,
"text": "Personalization With Contextual Bandits"
},
{
"code": null,
"e": 18328,
"s": 18274,
"text": "How To Survive Corporate Politics As A Data Scientist"
}
] |
How to sum elements of a column in MySQL?
|
Use aggregate function sum() to sum the elements of a column in MySQL. The syntax is as follows −
select sum(yourColumnName1) as anyVariableName1,sum(yourColumnName2) as anyVariableName2,sum(yourColumnName3) as anyVariableName3,............N from yourTableName;
To understand the above syntax, let us create a table. The following is the query to create a table −
mysql> create table SumDemoOnColumns
−> (
−> First int,
−> Second int,
−> Third int
−> );
Query OK, 0 rows affected (0.56 sec)
Insert some data in the table using insert command. The query is as follows −
mysql> insert into SumDemoOnColumns values(10,20,30);
Query OK, 1 row affected (0.18 sec)
mysql> insert into SumDemoOnColumns values(40,50,60);
Query OK, 1 row affected (0.32 sec)
mysql> insert into SumDemoOnColumns values(70,80,90);
Query OK, 1 row affected (0.10 sec)
mysql> insert into SumDemoOnColumns values(100,110,120);
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from SumDemoOnColumns;
The following is the output −
+-------+--------+-------+
| First | Second | Third |
+-------+--------+-------+
| 10 | 20 | 30 |
| 40 | 50 | 60 |
| 70 | 80 | 90 |
| 100 | 110 | 120 |
+-------+--------+-------+
4 rows in set (0.00 sec)
The following is the query to get sum of columns −
mysql> select sum(First) as First,sum(Second) as Second,sum(Third) as Third from SumDemoOnColumns;
The following is the output −
+-------+--------+-------+
| First | Second | Third |
+-------+--------+-------+
| 220 | 260 | 300 |
+-------+--------+-------+
1 row in set (0.00 sec)
|
[
{
"code": null,
"e": 1160,
"s": 1062,
"text": "Use aggregate function sum() to sum the elements of a column in MySQL. The syntax is as follows −"
},
{
"code": null,
"e": 1324,
"s": 1160,
"text": "select sum(yourColumnName1) as anyVariableName1,sum(yourColumnName2) as anyVariableName2,sum(yourColumnName3) as anyVariableName3,............N from yourTableName;"
},
{
"code": null,
"e": 1426,
"s": 1324,
"text": "To understand the above syntax, let us create a table. The following is the query to create a table −"
},
{
"code": null,
"e": 1570,
"s": 1426,
"text": "mysql> create table SumDemoOnColumns\n −> (\n −> First int, \n −> Second int,\n −> Third int\n −> );\nQuery OK, 0 rows affected (0.56 sec)"
},
{
"code": null,
"e": 1648,
"s": 1570,
"text": "Insert some data in the table using insert command. The query is as follows −"
},
{
"code": null,
"e": 2014,
"s": 1648,
"text": "mysql> insert into SumDemoOnColumns values(10,20,30);\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into SumDemoOnColumns values(40,50,60);\nQuery OK, 1 row affected (0.32 sec)\n\nmysql> insert into SumDemoOnColumns values(70,80,90);\nQuery OK, 1 row affected (0.10 sec)\n\nmysql> insert into SumDemoOnColumns values(100,110,120);\nQuery OK, 1 row affected (0.16 sec)"
},
{
"code": null,
"e": 2099,
"s": 2014,
"text": "Display all records from the table using select statement. The query is as follows −"
},
{
"code": null,
"e": 2137,
"s": 2099,
"text": "mysql> select *from SumDemoOnColumns;"
},
{
"code": null,
"e": 2167,
"s": 2137,
"text": "The following is the output −"
},
{
"code": null,
"e": 2408,
"s": 2167,
"text": "+-------+--------+-------+\n| First | Second | Third |\n+-------+--------+-------+\n| 10 | 20 | 30 |\n| 40 | 50 | 60 |\n| 70 | 80 | 90 |\n| 100 | 110 | 120 |\n+-------+--------+-------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2459,
"s": 2408,
"text": "The following is the query to get sum of columns −"
},
{
"code": null,
"e": 2558,
"s": 2459,
"text": "mysql> select sum(First) as First,sum(Second) as Second,sum(Third) as Third from SumDemoOnColumns;"
},
{
"code": null,
"e": 2588,
"s": 2558,
"text": "The following is the output −"
},
{
"code": null,
"e": 2747,
"s": 2588,
"text": "+-------+--------+-------+\n| First | Second | Third |\n+-------+--------+-------+\n| 220 | 260 | 300 |\n+-------+--------+-------+\n1 row in set (0.00 sec)"
}
] |
How to Scroll top in RecyclerView with LinearLayoutManager in Android?
|
Before getting into example, we should know what is Recycler view in android. Recycler view is more advanced version of list view and it works based on View holder design pattern. Using recycler view we can show grids and list of items .
This example demonstrate
about how to Scroll top in RecyclerView with LinearLayoutManager by creating a beautiful student records app that displays student name with age .
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 − Open build.gradle and add Recycler view & Card view library dependencies.
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.andy.tutorialspoint"
minSdkVersion 19
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:cardview-v7:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
Step 3 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
xmlns:app = "http://schemas.android.com/apk/res-auto"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
app:layout_behavior = "@string/appbar_scrolling_view_behavior"
tools:showIn = "@layout/activity_main"
android:fitsSystemWindows = "true"
tools:context = ".MainActivity">
<android.support.v7.widget.RecyclerView
android:id = "@+id/recycler_view"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:scrollbars = "horizontal" />
<android.support.design.widget.FloatingActionButton
android:id = "@+id/top"
app:backgroundTint = "#FFFF00"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_gravity = "bottom|end"
android:src = "@android:drawable/arrow_up_float" />
</android.support.design.widget.CoordinatorLayout >
In the above code we have added recycler view to window manger as relative parent layout and add FloatingActionButton. FloatingActionButton supports CoordinatorLayout. So we have used parent layout is CoordinatorLayout. When you click on FloatingActionButton, it will scroll to top position.
Step 4 − Add the following code to src/MainActivity.java
package com.example.andy.tutorialspoint;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private StudentAdapter studentAdapter;
private List studentDataList = new ArrayList<>();
@TargetApi(Build.VERSION_CODES.O)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FloatingActionButton moveTop = findViewById(R.id.top);
recyclerView = findViewById(R.id.recycler_view);
studentAdapter = new StudentAdapter(studentDataList,MainActivity.this);
RecyclerView.LayoutManager manager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(manager);
recyclerView.setAdapter(studentAdapter);
StudentDataPrepare();
moveTop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
recyclerView.smoothScrollToPosition(0);
}
});
}
@RequiresApi(api = Build.VERSION_CODES.N)
private void StudentDataPrepare() {
studentData data = new studentData("sai", 25);
studentDataList.add(data);
data = new studentData("sai raj", 25);
studentDataList.add(data);
data = new studentData("raghu", 20);
studentDataList.add(data);
data = new studentData("raj", 28);
studentDataList.add(data);
data = new studentData("amar", 15);
studentDataList.add(data);
data = new studentData("bapu", 19);
studentDataList.add(data);
data = new studentData("chandra", 52);
studentDataList.add(data);
data = new studentData("deraj", 30);
studentDataList.add(data);
data = new studentData("eshanth", 28);
studentDataList.add(data);
Collections.sort(studentDataList, new Comparator() {
@Override
public int compare(studentData o1, studentData o2) {
return o1.name.compareTo(o2.name);
}
});
}
}
In the above code we have added recycler view and studentAdapter. In that student adapter we have passed studentDatalist as arraylist. In Student data list contains name of the student and age.
We have using smoothScrollToPosition() to scroll 0 th position, we can assign any position according to our requirement. In this example, it going to scroll zero(top) position as shown below -
moveTop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
recyclerView.smoothScrollToPosition(0);
}
});
Step 5 − Following is the content of the modified file src/ StudentAdapter.java. package com.example.andy.tutorialspoint;
package com.example.andy.tutorialspoint;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
import java.util.Random;
class StudentAdapter extends RecyclerView.Adapter {
List studentDataList;
public StudentAdapter(List studentDataList) {
this.studentDataList = studentDataList;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.student_list_row, viewGroup, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(MyViewHolder viewHolder, int i) {
studentData data = studentDataList.get(i);
Random rnd = new Random();
int currentColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
viewHolder.parent.setBackgroundColor(currentColor);
viewHolder.name.setText(data.name);
viewHolder.age.setText(String.valueOf(data.age));
}
@Override
public int getItemCount() {
return studentDataList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView name,age;
LinearLayout parent;
public MyViewHolder(View itemView) {
super(itemView);
parent = itemView.findViewById(R.id.parent);
name = itemView.findViewById(R.id.name);
age = itemView.findViewById(R.id.age);
}
}
}
In the adapter class we have four methods as shown below -
onCreateViewHolder() :- It is used to create a view holder and it returns a view.
onCreateViewHolder() :- It is used to create a view holder and it returns a view.
onBindViewHolder() - it going to bind with created view holder.
onBindViewHolder() - it going to bind with created view holder.
getItemCount() - it contains size of list.
getItemCount() - it contains size of list.
MyViewHolder class- it is view holder inner class which is extended by RecyclerView.ViewHolder
MyViewHolder class- it is view holder inner class which is extended by RecyclerView.ViewHolder
To set random background for recycler view items, we have generated random colors using random class(which is predefined class in Android) and added color to parent of view item as shown below -
Random rnd = new Random();
int currentColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
viewHolder.parent.setBackgroundColor(currentColor);
Step 6 − Following is the modified content of the xml res/layout/student_list_row.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<android.support.v7.widget.CardView xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:card_view = "http://schemas.android.com/apk/res-auto"
android:layout_width = "match_parent"
card_view:cardCornerRadius = "4dp"
android:id = "@+id/card_view"
android:layout_margin = "10dp"
android:layout_height = "200dp">
<LinearLayout
android:id = "@+id/parent"
android:layout_gravity = "center"
android:layout_width = "match_parent"
android:orientation = "vertical"
android:gravity = "center"
android:layout_height = "match_parent">
<TextView
android:id = "@+id/name"
android:layout_width = "wrap_content"
android:gravity = "center"
android:textSize = "25sp"
android:textColor = "#FFF"
android:layout_height = "wrap_content" />
<TextView
android:id = "@+id/age"
android:layout_width = "wrap_content"
android:gravity = "center"
android:textSize = "25sp"
android:textColor = "#FFF"
android:layout_height = "wrap_content" />
</LinearLayout>
</android.support.v7.widget.CardView>
In the above list item view we have created two text views for name and age inside the cardview. Card view contains pre defined corner radius and shadow property. So we have used corner radius with card view.
Step 7 − Following is the content of the modified file src/ studentData.java. package com.example.andy.tutorialspoint;
class studentData {
String name;
int age;
public studentData(String name, int age) {
this.name = name;
this.age = age;
}
}
In the above code informs about student data object. 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 −
Now clock yellow button scroll to top of recyclerview, it will show the result as shown below -
|
[
{
"code": null,
"e": 1300,
"s": 1062,
"text": "Before getting into example, we should know what is Recycler view in android. Recycler view is more advanced version of list view and it works based on View holder design pattern. Using recycler view we can show grids and list of items ."
},
{
"code": null,
"e": 1472,
"s": 1300,
"text": "This example demonstrate\nabout how to Scroll top in RecyclerView with LinearLayoutManager by creating a beautiful student records app that displays student name with age ."
},
{
"code": null,
"e": 1601,
"s": 1472,
"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": 1684,
"s": 1601,
"text": "Step 2 − Open build.gradle and add Recycler view & Card view library dependencies."
},
{
"code": null,
"e": 2762,
"s": 1684,
"text": "apply plugin: 'com.android.application'\n\nandroid {\n compileSdkVersion 28\n defaultConfig {\n applicationId \"com.example.andy.tutorialspoint\"\n minSdkVersion 19\n targetSdkVersion 28\n versionCode 1\n versionName \"1.0\"\n testInstrumentationRunner \"android.support.test.runner.AndroidJUnitRunner\"\n }\n buildTypes {\n release {\n minifyEnabled false\n proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\n }\n }\n}\ndependencies {\n implementation fileTree(dir: 'libs', include: ['*.jar'])\n implementation 'com.android.support:appcompat-v7:28.0.0'\n implementation 'com.android.support:design:28.0.0'\n implementation 'com.android.support.constraint:constraint-layout:1.1.3'\n implementation 'com.android.support:cardview-v7:28.0.0'\n implementation 'com.android.support:recyclerview-v7:28.0.0'\n testImplementation 'junit:junit:4.12'\n androidTestImplementation 'com.android.support.test:runner:1.0.2'\n androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'\n}"
},
{
"code": null,
"e": 2827,
"s": 2762,
"text": "Step 3 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 3937,
"s": 2827,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.design.widget.CoordinatorLayout\n xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n app:layout_behavior = \"@string/appbar_scrolling_view_behavior\"\n tools:showIn = \"@layout/activity_main\"\n android:fitsSystemWindows = \"true\"\n tools:context = \".MainActivity\">\n <android.support.v7.widget.RecyclerView\n android:id = \"@+id/recycler_view\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:scrollbars = \"horizontal\" />\n <android.support.design.widget.FloatingActionButton\n android:id = \"@+id/top\"\n app:backgroundTint = \"#FFFF00\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:layout_gravity = \"bottom|end\"\n android:src = \"@android:drawable/arrow_up_float\" />\n</android.support.design.widget.CoordinatorLayout >"
},
{
"code": null,
"e": 4229,
"s": 3937,
"text": "In the above code we have added recycler view to window manger as relative parent layout and add FloatingActionButton. FloatingActionButton supports CoordinatorLayout. So we have used parent layout is CoordinatorLayout. When you click on FloatingActionButton, it will scroll to top position."
},
{
"code": null,
"e": 4286,
"s": 4229,
"text": "Step 4 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 6976,
"s": 4286,
"text": "package com.example.andy.tutorialspoint;\n\nimport android.annotation.TargetApi;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.design.widget.FloatingActionButton;\nimport android.support.v7.app.AppCompatActivity;\nimport android.support.v7.widget.DividerItemDecoration;\nimport android.support.v7.widget.GridLayoutManager;\nimport android.support.v7.widget.LinearLayoutManager;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.LinearLayout;\nimport android.widget.Toast;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.List;\n\npublic class MainActivity extends AppCompatActivity {\n private RecyclerView recyclerView;\n private StudentAdapter studentAdapter;\n private List studentDataList = new ArrayList<>();\n @TargetApi(Build.VERSION_CODES.O)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n FloatingActionButton moveTop = findViewById(R.id.top);\n recyclerView = findViewById(R.id.recycler_view);\n studentAdapter = new StudentAdapter(studentDataList,MainActivity.this);\n RecyclerView.LayoutManager manager = new LinearLayoutManager(this);\n recyclerView.setLayoutManager(manager);\n recyclerView.setAdapter(studentAdapter);\n StudentDataPrepare();\n moveTop.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n recyclerView.smoothScrollToPosition(0);\n }\n });\n }\n @RequiresApi(api = Build.VERSION_CODES.N)\n private void StudentDataPrepare() {\n studentData data = new studentData(\"sai\", 25);\n studentDataList.add(data);\n data = new studentData(\"sai raj\", 25);\n studentDataList.add(data);\n data = new studentData(\"raghu\", 20);\n studentDataList.add(data);\n data = new studentData(\"raj\", 28);\n studentDataList.add(data);\n data = new studentData(\"amar\", 15);\n studentDataList.add(data);\n data = new studentData(\"bapu\", 19);\n studentDataList.add(data);\n data = new studentData(\"chandra\", 52);\n studentDataList.add(data);\n data = new studentData(\"deraj\", 30);\n studentDataList.add(data);\n data = new studentData(\"eshanth\", 28);\n studentDataList.add(data);\n Collections.sort(studentDataList, new Comparator() {\n @Override\n public int compare(studentData o1, studentData o2) {\n return o1.name.compareTo(o2.name);\n }\n });\n }\n}"
},
{
"code": null,
"e": 7170,
"s": 6976,
"text": "In the above code we have added recycler view and studentAdapter. In that student adapter we have passed studentDatalist as arraylist. In Student data list contains name of the student and age."
},
{
"code": null,
"e": 7363,
"s": 7170,
"text": "We have using smoothScrollToPosition() to scroll 0 th position, we can assign any position according to our requirement. In this example, it going to scroll zero(top) position as shown below -"
},
{
"code": null,
"e": 7520,
"s": 7363,
"text": "moveTop.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n recyclerView.smoothScrollToPosition(0);\n }\n});"
},
{
"code": null,
"e": 7642,
"s": 7520,
"text": "Step 5 − Following is the content of the modified file src/ StudentAdapter.java. package com.example.andy.tutorialspoint;"
},
{
"code": null,
"e": 9319,
"s": 7642,
"text": "package com.example.andy.tutorialspoint;\nimport android.graphics.Color;\nimport android.support.annotation.NonNull;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.LinearLayout;\nimport android.widget.TextView;\n\nimport java.util.List;\nimport java.util.Random;\n\nclass StudentAdapter extends RecyclerView.Adapter {\n List studentDataList;\n public StudentAdapter(List studentDataList) {\n this.studentDataList = studentDataList;\n }\n @NonNull\n @Override\n public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {\n View itemView = LayoutInflater.from(viewGroup.getContext())\n .inflate(R.layout.student_list_row, viewGroup, false);\n return new MyViewHolder(itemView);\n }\n @Override\n public void onBindViewHolder(MyViewHolder viewHolder, int i) {\n studentData data = studentDataList.get(i);\n Random rnd = new Random();\n int currentColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));\n viewHolder.parent.setBackgroundColor(currentColor);\n viewHolder.name.setText(data.name);\n viewHolder.age.setText(String.valueOf(data.age));\n }\n @Override\n public int getItemCount() {\n return studentDataList.size();\n }\n class MyViewHolder extends RecyclerView.ViewHolder {\n TextView name,age;\n LinearLayout parent;\n public MyViewHolder(View itemView) {\n super(itemView);\n parent = itemView.findViewById(R.id.parent);\n name = itemView.findViewById(R.id.name);\n age = itemView.findViewById(R.id.age);\n }\n }\n}"
},
{
"code": null,
"e": 9378,
"s": 9319,
"text": "In the adapter class we have four methods as shown below -"
},
{
"code": null,
"e": 9460,
"s": 9378,
"text": "onCreateViewHolder() :- It is used to create a view holder and it returns a view."
},
{
"code": null,
"e": 9542,
"s": 9460,
"text": "onCreateViewHolder() :- It is used to create a view holder and it returns a view."
},
{
"code": null,
"e": 9606,
"s": 9542,
"text": "onBindViewHolder() - it going to bind with created view holder."
},
{
"code": null,
"e": 9670,
"s": 9606,
"text": "onBindViewHolder() - it going to bind with created view holder."
},
{
"code": null,
"e": 9713,
"s": 9670,
"text": "getItemCount() - it contains size of list."
},
{
"code": null,
"e": 9756,
"s": 9713,
"text": "getItemCount() - it contains size of list."
},
{
"code": null,
"e": 9851,
"s": 9756,
"text": "MyViewHolder class- it is view holder inner class which is extended by RecyclerView.ViewHolder"
},
{
"code": null,
"e": 9946,
"s": 9851,
"text": "MyViewHolder class- it is view holder inner class which is extended by RecyclerView.ViewHolder"
},
{
"code": null,
"e": 10141,
"s": 9946,
"text": "To set random background for recycler view items, we have generated random colors using random class(which is predefined class in Android) and added color to parent of view item as shown below -"
},
{
"code": null,
"e": 10310,
"s": 10141,
"text": "Random rnd = new Random();\nint currentColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));\nviewHolder.parent.setBackgroundColor(currentColor);"
},
{
"code": null,
"e": 10397,
"s": 10310,
"text": "Step 6 − Following is the modified content of the xml res/layout/student_list_row.xml."
},
{
"code": null,
"e": 11558,
"s": 10397,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.v7.widget.CardView xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:card_view = \"http://schemas.android.com/apk/res-auto\"\n android:layout_width = \"match_parent\"\n card_view:cardCornerRadius = \"4dp\"\n android:id = \"@+id/card_view\"\n android:layout_margin = \"10dp\"\n android:layout_height = \"200dp\">\n <LinearLayout\n android:id = \"@+id/parent\"\n android:layout_gravity = \"center\"\n android:layout_width = \"match_parent\"\n android:orientation = \"vertical\"\n android:gravity = \"center\"\n android:layout_height = \"match_parent\">\n <TextView\n android:id = \"@+id/name\"\n android:layout_width = \"wrap_content\"\n android:gravity = \"center\"\n android:textSize = \"25sp\"\n android:textColor = \"#FFF\"\n android:layout_height = \"wrap_content\" />\n <TextView\n android:id = \"@+id/age\"\n android:layout_width = \"wrap_content\"\n android:gravity = \"center\"\n android:textSize = \"25sp\"\n android:textColor = \"#FFF\"\n android:layout_height = \"wrap_content\" />\n </LinearLayout>\n</android.support.v7.widget.CardView>"
},
{
"code": null,
"e": 11767,
"s": 11558,
"text": "In the above list item view we have created two text views for name and age inside the cardview. Card view contains pre defined corner radius and shadow property. So we have used corner radius with card view."
},
{
"code": null,
"e": 11886,
"s": 11767,
"text": "Step 7 − Following is the content of the modified file src/ studentData.java. package com.example.andy.tutorialspoint;"
},
{
"code": null,
"e": 12035,
"s": 11886,
"text": "class studentData { \n String name;\n int age;\n public studentData(String name, int age) {\n this.name = name;\n this.age = age;\n }\n}"
},
{
"code": null,
"e": 12435,
"s": 12035,
"text": "In the above code informs about student data object. 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": 12531,
"s": 12435,
"text": "Now clock yellow button scroll to top of recyclerview, it will show the result as shown below -"
}
] |
Chef - Libraries
|
Libraries in Chef provides a place to encapsulate compiled logic so that the cookbook recipes remain neat and clean.
Step 1 − Create a helper method in cookbook’s library.
vipin@laptop:~/chef-repo $ subl cookbooks/my_cookbook/libraries/ipaddress.rb
class Chef::Recipe
def netmask(ipaddress)
IPAddress(ipaddress).netmask
end
end
Step 2 − Use the helper method.
vipin@laptop:~/chef-repo $ subl cookbooks/my_cookbook/recipes/default.rb
ip = '10.10.0.0/24'
mask = netmask(ip) # here we use the library method
Chef::Log.info("Netmask of #{ip}: #{mask}")
Step 3 − Upload the modified cookbook to the Chef Server.
vipin@laptop:~/chef-repo $ knife cookbook upload my_cookbook
Uploading my_cookbook [0.1.0]
user@server $ sudo chef-client
...TRUNCATED OUTPUT...
[2013-01-18T14:38:26+00:00] INFO: Netmask of 10.10.0.0/24:
255.255.255.0
...TRUNCATED OUTPUT...
Chef library code can open the chef::Recipe class and add new methods as done in Step 1. This step is not the cleanest but the simplest way of doing it.
class Chef::Recipe
def netmask(ipaddress)
...
end
end
Once we open the chef::recipe class, there are changes that it gets polluted. As a best practice, it is always a better way to introduce a new sub class inside the library and define a method as class method. This avoids pulling the chef::recipe namespace.
vipin@laptop:~/chef-repo $ subl cookbooks/my_cookbook/libraries/ipaddress.rb
class Chef::Recipe::IPAddress
def self.netmask(ipaddress)
IPAddress(ipaddress).netmask
end
end
We can use the method inside the recipe like
IPAddress.netmask(ip)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2497,
"s": 2380,
"text": "Libraries in Chef provides a place to encapsulate compiled logic so that the cookbook recipes remain neat and clean."
},
{
"code": null,
"e": 2552,
"s": 2497,
"text": "Step 1 − Create a helper method in cookbook’s library."
},
{
"code": null,
"e": 2713,
"s": 2552,
"text": "vipin@laptop:~/chef-repo $ subl cookbooks/my_cookbook/libraries/ipaddress.rb \nclass Chef::Recipe \ndef netmask(ipaddress) \nIPAddress(ipaddress).netmask \nend \nend"
},
{
"code": null,
"e": 2745,
"s": 2713,
"text": "Step 2 − Use the helper method."
},
{
"code": null,
"e": 2938,
"s": 2745,
"text": "vipin@laptop:~/chef-repo $ subl cookbooks/my_cookbook/recipes/default.rb \nip = '10.10.0.0/24' \nmask = netmask(ip) # here we use the library method \nChef::Log.info(\"Netmask of #{ip}: #{mask}\") "
},
{
"code": null,
"e": 2996,
"s": 2938,
"text": "Step 3 − Upload the modified cookbook to the Chef Server."
},
{
"code": null,
"e": 3090,
"s": 2996,
"text": "vipin@laptop:~/chef-repo $ knife cookbook upload my_cookbook \nUploading my_cookbook [0.1.0] \n"
},
{
"code": null,
"e": 3246,
"s": 3090,
"text": "user@server $ sudo chef-client \n...TRUNCATED OUTPUT... \n[2013-01-18T14:38:26+00:00] INFO: Netmask of 10.10.0.0/24: \n255.255.255.0 \n...TRUNCATED OUTPUT... \n"
},
{
"code": null,
"e": 3399,
"s": 3246,
"text": "Chef library code can open the chef::Recipe class and add new methods as done in Step 1. This step is not the cleanest but the simplest way of doing it."
},
{
"code": null,
"e": 3458,
"s": 3399,
"text": "class Chef::Recipe \ndef netmask(ipaddress) \n... \nend \nend\n"
},
{
"code": null,
"e": 3715,
"s": 3458,
"text": "Once we open the chef::recipe class, there are changes that it gets polluted. As a best practice, it is always a better way to introduce a new sub class inside the library and define a method as class method. This avoids pulling the chef::recipe namespace."
},
{
"code": null,
"e": 3893,
"s": 3715,
"text": "vipin@laptop:~/chef-repo $ subl cookbooks/my_cookbook/libraries/ipaddress.rb \nclass Chef::Recipe::IPAddress \ndef self.netmask(ipaddress) \nIPAddress(ipaddress).netmask \nend \nend "
},
{
"code": null,
"e": 3938,
"s": 3893,
"text": "We can use the method inside the recipe like"
},
{
"code": null,
"e": 3962,
"s": 3938,
"text": "IPAddress.netmask(ip) \n"
},
{
"code": null,
"e": 3969,
"s": 3962,
"text": " Print"
},
{
"code": null,
"e": 3980,
"s": 3969,
"text": " Add Notes"
}
] |
How to make a class JSON Serializable in Python?
|
Serialisation is the process of transforming objects of complex data types to native data types so that they can then be easily converted to JSON notation.
If you have a JSON string, you can convert it into a JSON string by using the json.dumps() method.
Python pickle module is used for serialising and deserialising a Python object structure. Any object in Python can be pickled so that it can be saved on disk. What pickle does is that it “serialises” the object first before writing it to file. Pickling is a way to convert a python object (i.e) list, dict, etc... into a character stream.
import json
x = {
"name": "Archana",
"age": 30,
"city": "Hyderabad"
}
# convert into JSON String by using json.dumps():
y = json.dumps(x)
print(y)
{"name": "Archana", "age": 30, "city": "Hyderabad"}
import json
Emp = {1:"Archana",
2:"Krishna",
3:"Vineeth",
4:"Ramesh"}
jsonString = json.dumps(Emp)
print(jsonString)
Empid = [71,72,73,74]
jsonString = json.dumps(Empid)
print(jsonString)
{"1": "Archana", "2": "Krishna", "3": "Vineeth", "4": "Ramesh"}
[71, 72, 73, 74]
|
[
{
"code": null,
"e": 1219,
"s": 1062,
"text": "Serialisation is the process of transforming objects of complex data types to native data types so that they can then be easily converted to JSON notation. "
},
{
"code": null,
"e": 1318,
"s": 1219,
"text": "If you have a JSON string, you can convert it into a JSON string by using the json.dumps() method."
},
{
"code": null,
"e": 1658,
"s": 1318,
"text": "Python pickle module is used for serialising and deserialising a Python object structure. Any object in Python can be pickled so that it can be saved on disk. What pickle does is that it “serialises” the object first before writing it to file. Pickling is a way to convert a python object (i.e) list, dict, etc... into a character stream. "
},
{
"code": null,
"e": 1817,
"s": 1658,
"text": "import json\nx = {\n \"name\": \"Archana\",\n \"age\": 30,\n \"city\": \"Hyderabad\"\n }\n# convert into JSON String by using json.dumps():\ny = json.dumps(x)\nprint(y)"
},
{
"code": null,
"e": 1869,
"s": 1817,
"text": "{\"name\": \"Archana\", \"age\": 30, \"city\": \"Hyderabad\"}"
},
{
"code": null,
"e": 2078,
"s": 1869,
"text": "import json\nEmp = {1:\"Archana\",\n 2:\"Krishna\",\n 3:\"Vineeth\",\n 4:\"Ramesh\"}\njsonString = json.dumps(Emp)\nprint(jsonString)\nEmpid = [71,72,73,74]\njsonString = json.dumps(Empid)\nprint(jsonString)"
},
{
"code": null,
"e": 2159,
"s": 2078,
"text": "{\"1\": \"Archana\", \"2\": \"Krishna\", \"3\": \"Vineeth\", \"4\": \"Ramesh\"}\n[71, 72, 73, 74]"
}
] |
Rearrange array such that even positioned are greater than odd - GeeksforGeeks
|
20 Apr, 2021
Given an array A of n elements, sort the array according to the following relations :
, if i is even.
, if i is odd. Print the resultant array.Examples :
Input : A[] = {1, 2, 2, 1}
Output : 1 2 1 2
Explanation :
For 1st element, 1 1, i = 2 is even.
3rd element, 1 1, i = 4 is even.
Input : A[] = {1, 3, 2}
Output : 1 3 2
Explanation :
Here, the array is also sorted as per the conditions.
1 1 and 2 < 3.
Method 1 – Observe that array consists of [n/2] even positioned elements. If we assign the largest [n/2] elements to the even positions and the rest of the elements to the odd positions, our problem is solved. Because element at the odd position will always be less than the element at the even position as it is the maximum element and vice versa. Sort the array and assign the first [n/2] elements at even positions.Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to rearrange the elements// in array such that even positioned are// greater than odd positioned elements#include <bits/stdc++.h>using namespace std; void assign(int a[], int n){ // Sort the array sort(a, a + n); int ans[n]; int p = 0, q = n - 1; for (int i = 0; i < n; i++) { // Assign even indexes with maximum elements if ((i + 1) % 2 == 0) ans[i] = a[q--]; // Assign odd indexes with remaining elements else ans[i] = a[p++]; } // Print result for (int i = 0; i < n; i++) cout << ans[i] << " ";} // Driver Codeint main(){ int A[] = { 1, 3, 2, 2, 5 }; int n = sizeof(A) / sizeof(A[0]); assign(A, n); return 0;}
// Java program to rearrange the elements// in array such that even positioned are// greater than odd positioned elementsimport java.io.*;import java.util.*; class GFG { static void assign(int a[], int n) { // Sort the array Arrays.sort(a); int ans[] = new int[n]; int p = 0, q = n - 1; for (int i = 0; i < n; i++) { // Assign even indexes with maximum elements if ((i + 1) % 2 == 0) ans[i] = a[q--]; // Assign odd indexes with remaining elements else ans[i] = a[p++]; } // Print result for (int i = 0; i < n; i++) System.out.print(ans[i] + " "); } // Driver code public static void main(String args[]) { int A[] = { 1, 3, 2, 2, 5 }; int n = A.length; assign(A, n); }} // This code is contributed by Nikita Tiwari.
# Python3 code to rearrange the# elements in array such that# even positioned are greater# than odd positioned elements def assign(a, n): # Sort the array a.sort() ans = [0] * n p = 0 q = n - 1 for i in range(n): # Assign even indexes with # maximum elements if (i + 1) % 2 == 0: ans[i] = a[q] q = q - 1 # Assign odd indexes with # remaining elements else: ans[i] = a[p] p = p + 1 # Print result for i in range(n): print(ans[i], end = " ") # Driver CodeA = [ 1, 3, 2, 2, 5 ]n = len(A)assign(A, n) # This code is contributed by "Sharad_Bhardwaj".
// C# program to rearrange the elements// in array such that even positioned are// greater than odd positioned elementsusing System; class GFG { static void assign(int[] a, int n) { // Sort the array Array.Sort(a); int[] ans = new int[n]; int p = 0, q = n - 1; for (int i = 0; i < n; i++) { // Assign even indexes with maximum elements if ((i + 1) % 2 == 0) ans[i] = a[q--]; // Assign odd indexes with remaining elements else ans[i] = a[p++]; } // Print result for (int i = 0; i < n; i++) Console.Write(ans[i] + " "); } // Driver code public static void Main() { int[] A = { 1, 3, 2, 2, 5 }; int n = A.Length; assign(A, n); }} // This code is contributed by vt_m.
<?php// PHP program to rearrange// the elements in array such// that even positioned are// greater than odd positioned// elements function assign($a, $n){ // Sort the array sort($a); $p = 0; $q = $n - 1; for ($i = 0; $i < $n; $i++) { // Assign even indexes // with maximum elements if (($i + 1) % 2 == 0) $ans[$i] = $a[$q--]; // Assign odd indexes // with remaining elements else $ans[$i] = $a[$p++]; } // Print result for ($i = 0; $i < $n; $i++) echo($ans[$i] . " ");} // Driver Code$A = array( 1, 3, 2, 2, 5 );$n = sizeof($A);assign($A, $n); // This code is contributed by Ajit.?>
<script> // JavaScript program to rearrange the elements// in array such that even positioned are// greater than odd positioned elements function assign(a, n) { // Sort the array a.sort(); let ans = []; let p = 0, q = n - 1; for (let i = 0; i < n; i++) { // Assign even indexes with maximum elements if ((i + 1) % 2 == 0) ans[i] = a[q--]; // Assign odd indexes with remaining elements else ans[i] = a[p++]; } // Print result for (let i = 0; i < n; i++) document.write(ans[i] + " "); } // Driver code let A = [ 1, 3, 2, 2, 5 ]; let n = A.length; assign(A, n); </script>
Output:
1 5 2 3 2
Time Complexity: O(n * log n)
Auxiliary Space: O(n) Method 2 – One other approach is to traverse the array from the second element and swap the element with the previous one if the condition is not satisfied. This is implemented as follows:
C++
Java
Python3
C#
Javascript
// C++ program to rearrange the elements// in the array such that even positioned are// greater than odd positioned elements#include <bits/stdc++.h>using namespace std; // swap two elementsvoid swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp;} void rearrange(int arr[], int n){ for (int i = 1; i < n; i++) { // if index is even if (i % 2 == 0) { if (arr[i] > arr[i - 1]) swap(&arr[i - 1], &arr[i]); } // if index is odd else { if (arr[i] < arr[i - 1]) swap(&arr[i - 1], &arr[i]); } }} int main(){ int n = 5; int arr[] = { 1, 3, 2, 2, 5 }; rearrange(arr, n); for (int i = 0; i < n; i++) cout << arr[i] << " "; cout << "\n"; return 0;}
// Java program to rearrange the elements// in the array such that even positioned are// greater than odd positioned elementsclass GFG{ public static void rearrange(int[] arr, int n) { for(int i = 1; i < n; i++) { // if index is even if(i % 2 == 0) { if(arr[i] > arr[i - 1]) { // swap two elements int temp = arr[i]; arr[i] = arr[i - 1]; arr[i - 1] = temp; } } // if index is odd else { if (arr[i] < arr[i - 1]) { // swap two elements int temp = arr[i]; arr[i] = arr[i - 1]; arr[i - 1] = temp; } } } for (int i = 0; i < n; i++) { System.out.print(arr[i] + " "); } } // Driver code public static void main(String []args) { int n = 5; int arr[] = {1, 3, 2, 2, 5}; rearrange(arr, n); }} // This code is contributed by avanitrachhadiya2155
# Python3 program to rearrange# the elements in the array# such that even positioned are# greater than odd positioned elementsdef rearrange(arr, n): for i in range (1, n): # if index is even if (i % 2 == 0): if (arr[i] > arr[i - 1]): arr[i - 1], arr[i] = arr[i], arr[i - 1] # if index is odd else: if (arr[i] < arr[i - 1]): arr[i - 1], arr[i] = arr[i] , arr[i - 1] if __name__ == "__main__": n = 5 arr = [1, 3, 2, 2, 5] rearrange(arr, n); for i in range (n): print (arr[i], end = " ") print () # This code is contributed by Chitranayal
// C# program to rearrange the elements// in the array such that even positioned are// greater than odd positioned elementsusing System;class GFG{public static void rearrange(int[] arr, int n){ for(int i = 1; i < n; i++) { // if index is even if(i % 2 == 0) { if(arr[i] > arr[i - 1]) { // swap two elements int temp = arr[i]; arr[i] = arr[i - 1]; arr[i - 1] = temp; } } // if index is odd else { if (arr[i] < arr[i - 1]) { // swap two elements int temp = arr[i]; arr[i] = arr[i - 1]; arr[i - 1] = temp; } } } for (int i = 0; i < n; i++) { Console.Write(arr[i] + " "); }} // Driver codepublic static void Main(String []args){ int n = 5; int []arr = {1, 3, 2, 2, 5}; rearrange(arr, n);}} // This code is contributed by shivanisinghss2110
<script> // JavaScript program to rearrange the elements// in the array such that even positioned are// greater than odd positioned elements function rearrange(arr, n) { for(let i = 1; i < n; i++) { // if index is even if(i % 2 == 0) { if(arr[i] > arr[i - 1]) { // swap two elements let temp = arr[i]; arr[i] = arr[i - 1]; arr[i - 1] = temp; } } // if index is odd else { if (arr[i] < arr[i - 1]) { // swap two elements let temp = arr[i]; arr[i] = arr[i - 1]; arr[i - 1] = temp; } } } for (let i = 0; i < n; i++) { document.write(arr[i] + " "); } } // Driver code let n = 5; let arr = [1, 3, 2, 2, 5]; rearrange(arr, n); </script>
Output:
1 3 2 5 2
Time Complexity: O(n)
Auxiliary Space: O(1)
jit_t
mohdmohtashimnawaz
ukasp
avanitrachhadiya2155
shivanisinghss2110
subham348
splevel62
susmitakundugoaldanga
array-rearrange
Arrays
Sorting
Arrays
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction to Arrays
Python | Using 2D arrays/lists the right way
Queue | Set 1 (Introduction and Array Implementation)
Linked List vs Array
Subset Sum Problem | DP-25
|
[
{
"code": null,
"e": 25436,
"s": 25408,
"text": "\n20 Apr, 2021"
},
{
"code": null,
"e": 25524,
"s": 25436,
"text": "Given an array A of n elements, sort the array according to the following relations : "
},
{
"code": null,
"e": 25544,
"s": 25526,
"text": ", if i is even. "
},
{
"code": null,
"e": 25600,
"s": 25546,
"text": ", if i is odd. Print the resultant array.Examples : "
},
{
"code": null,
"e": 25860,
"s": 25602,
"text": "Input : A[] = {1, 2, 2, 1}\nOutput : 1 2 1 2\nExplanation : \nFor 1st element, 1 1, i = 2 is even.\n3rd element, 1 1, i = 4 is even.\n\nInput : A[] = {1, 3, 2}\nOutput : 1 3 2\nExplanation : \nHere, the array is also sorted as per the conditions. \n1 1 and 2 < 3."
},
{
"code": null,
"e": 26333,
"s": 25862,
"text": "Method 1 – Observe that array consists of [n/2] even positioned elements. If we assign the largest [n/2] elements to the even positions and the rest of the elements to the odd positions, our problem is solved. Because element at the odd position will always be less than the element at the even position as it is the maximum element and vice versa. Sort the array and assign the first [n/2] elements at even positions.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26339,
"s": 26335,
"text": "C++"
},
{
"code": null,
"e": 26344,
"s": 26339,
"text": "Java"
},
{
"code": null,
"e": 26352,
"s": 26344,
"text": "Python3"
},
{
"code": null,
"e": 26355,
"s": 26352,
"text": "C#"
},
{
"code": null,
"e": 26359,
"s": 26355,
"text": "PHP"
},
{
"code": null,
"e": 26370,
"s": 26359,
"text": "Javascript"
},
{
"code": "// C++ program to rearrange the elements// in array such that even positioned are// greater than odd positioned elements#include <bits/stdc++.h>using namespace std; void assign(int a[], int n){ // Sort the array sort(a, a + n); int ans[n]; int p = 0, q = n - 1; for (int i = 0; i < n; i++) { // Assign even indexes with maximum elements if ((i + 1) % 2 == 0) ans[i] = a[q--]; // Assign odd indexes with remaining elements else ans[i] = a[p++]; } // Print result for (int i = 0; i < n; i++) cout << ans[i] << \" \";} // Driver Codeint main(){ int A[] = { 1, 3, 2, 2, 5 }; int n = sizeof(A) / sizeof(A[0]); assign(A, n); return 0;}",
"e": 27094,
"s": 26370,
"text": null
},
{
"code": "// Java program to rearrange the elements// in array such that even positioned are// greater than odd positioned elementsimport java.io.*;import java.util.*; class GFG { static void assign(int a[], int n) { // Sort the array Arrays.sort(a); int ans[] = new int[n]; int p = 0, q = n - 1; for (int i = 0; i < n; i++) { // Assign even indexes with maximum elements if ((i + 1) % 2 == 0) ans[i] = a[q--]; // Assign odd indexes with remaining elements else ans[i] = a[p++]; } // Print result for (int i = 0; i < n; i++) System.out.print(ans[i] + \" \"); } // Driver code public static void main(String args[]) { int A[] = { 1, 3, 2, 2, 5 }; int n = A.length; assign(A, n); }} // This code is contributed by Nikita Tiwari.",
"e": 27999,
"s": 27094,
"text": null
},
{
"code": "# Python3 code to rearrange the# elements in array such that# even positioned are greater# than odd positioned elements def assign(a, n): # Sort the array a.sort() ans = [0] * n p = 0 q = n - 1 for i in range(n): # Assign even indexes with # maximum elements if (i + 1) % 2 == 0: ans[i] = a[q] q = q - 1 # Assign odd indexes with # remaining elements else: ans[i] = a[p] p = p + 1 # Print result for i in range(n): print(ans[i], end = \" \") # Driver CodeA = [ 1, 3, 2, 2, 5 ]n = len(A)assign(A, n) # This code is contributed by \"Sharad_Bhardwaj\".",
"e": 28703,
"s": 27999,
"text": null
},
{
"code": "// C# program to rearrange the elements// in array such that even positioned are// greater than odd positioned elementsusing System; class GFG { static void assign(int[] a, int n) { // Sort the array Array.Sort(a); int[] ans = new int[n]; int p = 0, q = n - 1; for (int i = 0; i < n; i++) { // Assign even indexes with maximum elements if ((i + 1) % 2 == 0) ans[i] = a[q--]; // Assign odd indexes with remaining elements else ans[i] = a[p++]; } // Print result for (int i = 0; i < n; i++) Console.Write(ans[i] + \" \"); } // Driver code public static void Main() { int[] A = { 1, 3, 2, 2, 5 }; int n = A.Length; assign(A, n); }} // This code is contributed by vt_m.",
"e": 29556,
"s": 28703,
"text": null
},
{
"code": "<?php// PHP program to rearrange// the elements in array such// that even positioned are// greater than odd positioned// elements function assign($a, $n){ // Sort the array sort($a); $p = 0; $q = $n - 1; for ($i = 0; $i < $n; $i++) { // Assign even indexes // with maximum elements if (($i + 1) % 2 == 0) $ans[$i] = $a[$q--]; // Assign odd indexes // with remaining elements else $ans[$i] = $a[$p++]; } // Print result for ($i = 0; $i < $n; $i++) echo($ans[$i] . \" \");} // Driver Code$A = array( 1, 3, 2, 2, 5 );$n = sizeof($A);assign($A, $n); // This code is contributed by Ajit.?>",
"e": 30251,
"s": 29556,
"text": null
},
{
"code": "<script> // JavaScript program to rearrange the elements// in array such that even positioned are// greater than odd positioned elements function assign(a, n) { // Sort the array a.sort(); let ans = []; let p = 0, q = n - 1; for (let i = 0; i < n; i++) { // Assign even indexes with maximum elements if ((i + 1) % 2 == 0) ans[i] = a[q--]; // Assign odd indexes with remaining elements else ans[i] = a[p++]; } // Print result for (let i = 0; i < n; i++) document.write(ans[i] + \" \"); } // Driver code let A = [ 1, 3, 2, 2, 5 ]; let n = A.length; assign(A, n); </script>",
"e": 31031,
"s": 30251,
"text": null
},
{
"code": null,
"e": 31040,
"s": 31031,
"text": "Output: "
},
{
"code": null,
"e": 31050,
"s": 31040,
"text": "1 5 2 3 2"
},
{
"code": null,
"e": 31080,
"s": 31050,
"text": "Time Complexity: O(n * log n)"
},
{
"code": null,
"e": 31293,
"s": 31080,
"text": "Auxiliary Space: O(n) Method 2 – One other approach is to traverse the array from the second element and swap the element with the previous one if the condition is not satisfied. This is implemented as follows: "
},
{
"code": null,
"e": 31297,
"s": 31293,
"text": "C++"
},
{
"code": null,
"e": 31302,
"s": 31297,
"text": "Java"
},
{
"code": null,
"e": 31310,
"s": 31302,
"text": "Python3"
},
{
"code": null,
"e": 31313,
"s": 31310,
"text": "C#"
},
{
"code": null,
"e": 31324,
"s": 31313,
"text": "Javascript"
},
{
"code": "// C++ program to rearrange the elements// in the array such that even positioned are// greater than odd positioned elements#include <bits/stdc++.h>using namespace std; // swap two elementsvoid swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp;} void rearrange(int arr[], int n){ for (int i = 1; i < n; i++) { // if index is even if (i % 2 == 0) { if (arr[i] > arr[i - 1]) swap(&arr[i - 1], &arr[i]); } // if index is odd else { if (arr[i] < arr[i - 1]) swap(&arr[i - 1], &arr[i]); } }} int main(){ int n = 5; int arr[] = { 1, 3, 2, 2, 5 }; rearrange(arr, n); for (int i = 0; i < n; i++) cout << arr[i] << \" \"; cout << \"\\n\"; return 0;}",
"e": 32100,
"s": 31324,
"text": null
},
{
"code": "// Java program to rearrange the elements// in the array such that even positioned are// greater than odd positioned elementsclass GFG{ public static void rearrange(int[] arr, int n) { for(int i = 1; i < n; i++) { // if index is even if(i % 2 == 0) { if(arr[i] > arr[i - 1]) { // swap two elements int temp = arr[i]; arr[i] = arr[i - 1]; arr[i - 1] = temp; } } // if index is odd else { if (arr[i] < arr[i - 1]) { // swap two elements int temp = arr[i]; arr[i] = arr[i - 1]; arr[i - 1] = temp; } } } for (int i = 0; i < n; i++) { System.out.print(arr[i] + \" \"); } } // Driver code public static void main(String []args) { int n = 5; int arr[] = {1, 3, 2, 2, 5}; rearrange(arr, n); }} // This code is contributed by avanitrachhadiya2155",
"e": 33035,
"s": 32100,
"text": null
},
{
"code": "# Python3 program to rearrange# the elements in the array# such that even positioned are# greater than odd positioned elementsdef rearrange(arr, n): for i in range (1, n): # if index is even if (i % 2 == 0): if (arr[i] > arr[i - 1]): arr[i - 1], arr[i] = arr[i], arr[i - 1] # if index is odd else: if (arr[i] < arr[i - 1]): arr[i - 1], arr[i] = arr[i] , arr[i - 1] if __name__ == \"__main__\": n = 5 arr = [1, 3, 2, 2, 5] rearrange(arr, n); for i in range (n): print (arr[i], end = \" \") print () # This code is contributed by Chitranayal",
"e": 33705,
"s": 33035,
"text": null
},
{
"code": "// C# program to rearrange the elements// in the array such that even positioned are// greater than odd positioned elementsusing System;class GFG{public static void rearrange(int[] arr, int n){ for(int i = 1; i < n; i++) { // if index is even if(i % 2 == 0) { if(arr[i] > arr[i - 1]) { // swap two elements int temp = arr[i]; arr[i] = arr[i - 1]; arr[i - 1] = temp; } } // if index is odd else { if (arr[i] < arr[i - 1]) { // swap two elements int temp = arr[i]; arr[i] = arr[i - 1]; arr[i - 1] = temp; } } } for (int i = 0; i < n; i++) { Console.Write(arr[i] + \" \"); }} // Driver codepublic static void Main(String []args){ int n = 5; int []arr = {1, 3, 2, 2, 5}; rearrange(arr, n);}} // This code is contributed by shivanisinghss2110",
"e": 34644,
"s": 33705,
"text": null
},
{
"code": "<script> // JavaScript program to rearrange the elements// in the array such that even positioned are// greater than odd positioned elements function rearrange(arr, n) { for(let i = 1; i < n; i++) { // if index is even if(i % 2 == 0) { if(arr[i] > arr[i - 1]) { // swap two elements let temp = arr[i]; arr[i] = arr[i - 1]; arr[i - 1] = temp; } } // if index is odd else { if (arr[i] < arr[i - 1]) { // swap two elements let temp = arr[i]; arr[i] = arr[i - 1]; arr[i - 1] = temp; } } } for (let i = 0; i < n; i++) { document.write(arr[i] + \" \"); } } // Driver code let n = 5; let arr = [1, 3, 2, 2, 5]; rearrange(arr, n); </script>",
"e": 35508,
"s": 34644,
"text": null
},
{
"code": null,
"e": 35517,
"s": 35508,
"text": "Output: "
},
{
"code": null,
"e": 35527,
"s": 35517,
"text": "1 3 2 5 2"
},
{
"code": null,
"e": 35549,
"s": 35527,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 35572,
"s": 35549,
"text": "Auxiliary Space: O(1) "
},
{
"code": null,
"e": 35578,
"s": 35572,
"text": "jit_t"
},
{
"code": null,
"e": 35597,
"s": 35578,
"text": "mohdmohtashimnawaz"
},
{
"code": null,
"e": 35603,
"s": 35597,
"text": "ukasp"
},
{
"code": null,
"e": 35624,
"s": 35603,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 35643,
"s": 35624,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 35653,
"s": 35643,
"text": "subham348"
},
{
"code": null,
"e": 35663,
"s": 35653,
"text": "splevel62"
},
{
"code": null,
"e": 35685,
"s": 35663,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 35701,
"s": 35685,
"text": "array-rearrange"
},
{
"code": null,
"e": 35708,
"s": 35701,
"text": "Arrays"
},
{
"code": null,
"e": 35716,
"s": 35708,
"text": "Sorting"
},
{
"code": null,
"e": 35723,
"s": 35716,
"text": "Arrays"
},
{
"code": null,
"e": 35731,
"s": 35723,
"text": "Sorting"
},
{
"code": null,
"e": 35829,
"s": 35731,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35838,
"s": 35829,
"text": "Comments"
},
{
"code": null,
"e": 35851,
"s": 35838,
"text": "Old Comments"
},
{
"code": null,
"e": 35874,
"s": 35851,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 35919,
"s": 35874,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 35973,
"s": 35919,
"text": "Queue | Set 1 (Introduction and Array Implementation)"
},
{
"code": null,
"e": 35994,
"s": 35973,
"text": "Linked List vs Array"
}
] |
Get or set the element at the specified index in ArrayList in C#
|
To get or set the element at the specified index in ArrayList, the code is as follows −
Live Demo
using System;
using System.Collections;
public class Demo {
public static void Main() {
ArrayList arrList = new ArrayList();
arrList.Add("Laptop");
arrList.Add("Desktop");
arrList.Add("Notebook");
arrList.Add("Ultrabook");
arrList.Add("Tablet");
arrList.Add("Headphone");
arrList.Add("Speaker");
Console.WriteLine("Elements in ArrayList...");
foreach(string str in arrList) {
Console.WriteLine(str);
}
Console.WriteLine("Element at index 5 = " + arrList[5]);
}
}
This will produce the following output −
Elements in ArrayList...
Laptop
Desktop
Notebook
Ultrabook
Tablet
Headphone
Speaker
Element at index 5 = Headphone
Let us see another example −
Live Demo
using System;
using System.Collections;
public class Demo {
public static void Main() {
ArrayList arrList = new ArrayList();
arrList.Add("Laptop");
arrList.Add("Desktop");
arrList.Add("Notebook");
arrList.Add("Ultrabook");
arrList.Add("Tablet");
arrList.Add("Headphone");
arrList.Add("Speaker");
Console.WriteLine("Elements in ArrayList...");
foreach(string str in arrList) {
Console.WriteLine(str);
}
Console.WriteLine("Element at index 5 = " + arrList[5]);
arrList[5] = "SSD";
Console.WriteLine("Element at index 5 (Updated) = " + arrList[5]);
}
}
This will produce the following output −
Elements in ArrayList...
Laptop
Desktop
Notebook
Ultrabook
Tablet
Headphone
Speaker
Element at index 5 = Headphone
Element at index 5 (Updated) = SSD
|
[
{
"code": null,
"e": 1150,
"s": 1062,
"text": "To get or set the element at the specified index in ArrayList, the code is as follows −"
},
{
"code": null,
"e": 1161,
"s": 1150,
"text": " Live Demo"
},
{
"code": null,
"e": 1711,
"s": 1161,
"text": "using System;\nusing System.Collections;\npublic class Demo {\n public static void Main() {\n ArrayList arrList = new ArrayList();\n arrList.Add(\"Laptop\");\n arrList.Add(\"Desktop\");\n arrList.Add(\"Notebook\");\n arrList.Add(\"Ultrabook\");\n arrList.Add(\"Tablet\");\n arrList.Add(\"Headphone\");\n arrList.Add(\"Speaker\");\n Console.WriteLine(\"Elements in ArrayList...\");\n foreach(string str in arrList) {\n Console.WriteLine(str);\n }\n Console.WriteLine(\"Element at index 5 = \" + arrList[5]);\n }\n}"
},
{
"code": null,
"e": 1752,
"s": 1711,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1867,
"s": 1752,
"text": "Elements in ArrayList...\nLaptop\nDesktop\nNotebook\nUltrabook\nTablet\nHeadphone\nSpeaker\nElement at index 5 = Headphone"
},
{
"code": null,
"e": 1896,
"s": 1867,
"text": "Let us see another example −"
},
{
"code": null,
"e": 1907,
"s": 1896,
"text": " Live Demo"
},
{
"code": null,
"e": 2556,
"s": 1907,
"text": "using System;\nusing System.Collections;\npublic class Demo {\n public static void Main() {\n ArrayList arrList = new ArrayList();\n arrList.Add(\"Laptop\");\n arrList.Add(\"Desktop\");\n arrList.Add(\"Notebook\");\n arrList.Add(\"Ultrabook\");\n arrList.Add(\"Tablet\");\n arrList.Add(\"Headphone\");\n arrList.Add(\"Speaker\");\n Console.WriteLine(\"Elements in ArrayList...\");\n foreach(string str in arrList) {\n Console.WriteLine(str);\n }\n Console.WriteLine(\"Element at index 5 = \" + arrList[5]);\n arrList[5] = \"SSD\";\n Console.WriteLine(\"Element at index 5 (Updated) = \" + arrList[5]);\n }\n}"
},
{
"code": null,
"e": 2597,
"s": 2556,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2747,
"s": 2597,
"text": "Elements in ArrayList...\nLaptop\nDesktop\nNotebook\nUltrabook\nTablet\nHeadphone\nSpeaker\nElement at index 5 = Headphone\nElement at index 5 (Updated) = SSD"
}
] |
Java Program to Calculate Power of a Number - GeeksforGeeks
|
31 Oct, 2019
Given a number N and a power P, the task is to find the exponent of this number raised to the given power, i.e. NP.
Examples:
Input: N = 5, P = 2
Output: 25
Input: N = 2, P = 5
Output: 32
Below are the various ways to find NP:
Method 1: Using Recursion// Java program to find the power of a number// using Recursion class GFG { // Function to calculate N raised to the power P static int power(int N, int P) { if (P == 0) return 1; else return N * power(N, P - 1); } // Driver code public static void main(String[] args) { int N = 2; int P = 3; System.out.println(power(N, P)); }}Output:8
// Java program to find the power of a number// using Recursion class GFG { // Function to calculate N raised to the power P static int power(int N, int P) { if (P == 0) return 1; else return N * power(N, P - 1); } // Driver code public static void main(String[] args) { int N = 2; int P = 3; System.out.println(power(N, P)); }}
8
Method 2: With the help of Loop// Java program to find the power of a number// with the help of loop class GFG { // Function to calculate N raised to the power P static int power(int N, int P) { int pow = 1; for (int i = 1; i <= P; i++) pow *= N; return pow; } // Driver code public static void main(String[] args) { int N = 2; int P = 3; System.out.println(power(N, P)); }}Output:8
// Java program to find the power of a number// with the help of loop class GFG { // Function to calculate N raised to the power P static int power(int N, int P) { int pow = 1; for (int i = 1; i <= P; i++) pow *= N; return pow; } // Driver code public static void main(String[] args) { int N = 2; int P = 3; System.out.println(power(N, P)); }}
8
Method 3: Using Math.pow() method// Java program to find the power of a number// using Math.pow() method import java.lang.Math; class GFG { // Function to calculate N raised to the power P static double power(int N, int P) { return Math.pow(N, P); } // Driver code public static void main(String[] args) { int N = 2; int P = 3; System.out.println(power(N, P)); }}Output:8.0
// Java program to find the power of a number// using Math.pow() method import java.lang.Math; class GFG { // Function to calculate N raised to the power P static double power(int N, int P) { return Math.pow(N, P); } // Driver code public static void main(String[] args) { int N = 2; int P = 3; System.out.println(power(N, P)); }}
8.0
Java
Mathematical
Recursion
Mathematical
Recursion
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Interfaces in Java
Initialize an ArrayList in Java
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": 24104,
"s": 24076,
"text": "\n31 Oct, 2019"
},
{
"code": null,
"e": 24220,
"s": 24104,
"text": "Given a number N and a power P, the task is to find the exponent of this number raised to the given power, i.e. NP."
},
{
"code": null,
"e": 24230,
"s": 24220,
"text": "Examples:"
},
{
"code": null,
"e": 24294,
"s": 24230,
"text": "Input: N = 5, P = 2\nOutput: 25\n\nInput: N = 2, P = 5\nOutput: 32\n"
},
{
"code": null,
"e": 24333,
"s": 24294,
"text": "Below are the various ways to find NP:"
},
{
"code": null,
"e": 24784,
"s": 24333,
"text": "Method 1: Using Recursion// Java program to find the power of a number// using Recursion class GFG { // Function to calculate N raised to the power P static int power(int N, int P) { if (P == 0) return 1; else return N * power(N, P - 1); } // Driver code public static void main(String[] args) { int N = 2; int P = 3; System.out.println(power(N, P)); }}Output:8\n"
},
{
"code": "// Java program to find the power of a number// using Recursion class GFG { // Function to calculate N raised to the power P static int power(int N, int P) { if (P == 0) return 1; else return N * power(N, P - 1); } // Driver code public static void main(String[] args) { int N = 2; int P = 3; System.out.println(power(N, P)); }}",
"e": 25201,
"s": 24784,
"text": null
},
{
"code": null,
"e": 25204,
"s": 25201,
"text": "8\n"
},
{
"code": null,
"e": 25672,
"s": 25204,
"text": "Method 2: With the help of Loop// Java program to find the power of a number// with the help of loop class GFG { // Function to calculate N raised to the power P static int power(int N, int P) { int pow = 1; for (int i = 1; i <= P; i++) pow *= N; return pow; } // Driver code public static void main(String[] args) { int N = 2; int P = 3; System.out.println(power(N, P)); }}Output:8\n"
},
{
"code": "// Java program to find the power of a number// with the help of loop class GFG { // Function to calculate N raised to the power P static int power(int N, int P) { int pow = 1; for (int i = 1; i <= P; i++) pow *= N; return pow; } // Driver code public static void main(String[] args) { int N = 2; int P = 3; System.out.println(power(N, P)); }}",
"e": 26100,
"s": 25672,
"text": null
},
{
"code": null,
"e": 26103,
"s": 26100,
"text": "8\n"
},
{
"code": null,
"e": 26538,
"s": 26103,
"text": "Method 3: Using Math.pow() method// Java program to find the power of a number// using Math.pow() method import java.lang.Math; class GFG { // Function to calculate N raised to the power P static double power(int N, int P) { return Math.pow(N, P); } // Driver code public static void main(String[] args) { int N = 2; int P = 3; System.out.println(power(N, P)); }}Output:8.0\n"
},
{
"code": "// Java program to find the power of a number// using Math.pow() method import java.lang.Math; class GFG { // Function to calculate N raised to the power P static double power(int N, int P) { return Math.pow(N, P); } // Driver code public static void main(String[] args) { int N = 2; int P = 3; System.out.println(power(N, P)); }}",
"e": 26929,
"s": 26538,
"text": null
},
{
"code": null,
"e": 26934,
"s": 26929,
"text": "8.0\n"
},
{
"code": null,
"e": 26939,
"s": 26934,
"text": "Java"
},
{
"code": null,
"e": 26952,
"s": 26939,
"text": "Mathematical"
},
{
"code": null,
"e": 26962,
"s": 26952,
"text": "Recursion"
},
{
"code": null,
"e": 26975,
"s": 26962,
"text": "Mathematical"
},
{
"code": null,
"e": 26985,
"s": 26975,
"text": "Recursion"
},
{
"code": null,
"e": 26990,
"s": 26985,
"text": "Java"
},
{
"code": null,
"e": 27088,
"s": 26990,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27097,
"s": 27088,
"text": "Comments"
},
{
"code": null,
"e": 27110,
"s": 27097,
"text": "Old Comments"
},
{
"code": null,
"e": 27161,
"s": 27110,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 27191,
"s": 27161,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 27222,
"s": 27191,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 27241,
"s": 27222,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 27273,
"s": 27241,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 27303,
"s": 27273,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 27363,
"s": 27303,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 27378,
"s": 27363,
"text": "C++ Data Types"
},
{
"code": null,
"e": 27421,
"s": 27378,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
JSON - Schema
|
JSON Schema is a specification for JSON based format for defining the structure of JSON data. It was written under IETF draft which expired in 2011. JSON Schema −
Describes your existing data format.
Clear, human- and machine-readable documentation.
Complete structural validation, useful for automated testing.
Complete structural validation, validating client-submitted data.
There are several validators currently available for different programming languages. Currently the most complete and compliant JSON Schema validator available is JSV.
Given below is a basic JSON schema, which covers a classical product catalog description −
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Product",
"description": "A product from Acme's catalog",
"type": "object",
"properties": {
"id": {
"description": "The unique identifier for a product",
"type": "integer"
},
"name": {
"description": "Name of the product",
"type": "string"
},
"price": {
"type": "number",
"minimum": 0,
"exclusiveMinimum": true
}
},
"required": ["id", "name", "price"]
}
Let's the check various important keywords that can be used in this schema −
$schema
The $schema keyword states that this schema is written according to the draft v4 specification.
title
You will use this to give a title to your schema.
description
A little description of the schema.
type
The type keyword defines the first constraint on our JSON data: it has to be a JSON Object.
properties
Defines various keys and their value types, minimum and maximum values to be used in JSON file.
required
This keeps a list of required properties.
minimum
This is the constraint to be put on the value and represents minimum acceptable value.
exclusiveMinimum
If "exclusiveMinimum" is present and has boolean value true, the instance is valid if it is strictly greater than the value of "minimum".
maximum
This is the constraint to be put on the value and represents maximum acceptable value.
exclusiveMaximum
If "exclusiveMaximum" is present and has boolean value true, the instance is valid if it is strictly lower than the value of "maximum".
multipleOf
A numeric instance is valid against "multipleOf" if the result of the division of the instance by this keyword's value is an integer.
maxLength
The length of a string instance is defined as the maximum number of its characters.
minLength
The length of a string instance is defined as the minimum number of its characters.
pattern
A string instance is considered valid if the regular expression matches the instance successfully.
You can check a http://json-schema.org for the complete list of keywords that can be used in defining a JSON schema. The above schema can be used to test the validity of the following JSON code −
[
{
"id": 2,
"name": "An ice sculpture",
"price": 12.50,
},
{
"id": 3,
"name": "A blue mouse",
"price": 25.50,
}
]
20 Lectures
1 hours
Laurence Svekis
16 Lectures
1 hours
Laurence Svekis
10 Lectures
1 hours
Laurence Svekis
23 Lectures
2.5 hours
Laurence Svekis
9 Lectures
48 mins
Nilay Mehta
18 Lectures
2.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1943,
"s": 1780,
"text": "JSON Schema is a specification for JSON based format for defining the structure of JSON data. It was written under IETF draft which expired in 2011. JSON Schema −"
},
{
"code": null,
"e": 1980,
"s": 1943,
"text": "Describes your existing data format."
},
{
"code": null,
"e": 2030,
"s": 1980,
"text": "Clear, human- and machine-readable documentation."
},
{
"code": null,
"e": 2092,
"s": 2030,
"text": "Complete structural validation, useful for automated testing."
},
{
"code": null,
"e": 2158,
"s": 2092,
"text": "Complete structural validation, validating client-submitted data."
},
{
"code": null,
"e": 2326,
"s": 2158,
"text": "There are several validators currently available for different programming languages. Currently the most complete and compliant JSON Schema validator available is JSV."
},
{
"code": null,
"e": 2417,
"s": 2326,
"text": "Given below is a basic JSON schema, which covers a classical product catalog description −"
},
{
"code": null,
"e": 2969,
"s": 2417,
"text": "{\n \"$schema\": \"http://json-schema.org/draft-04/schema#\",\n \"title\": \"Product\",\n \"description\": \"A product from Acme's catalog\",\n \"type\": \"object\",\n\t\n \"properties\": {\n\t\n \"id\": {\n \"description\": \"The unique identifier for a product\",\n \"type\": \"integer\"\n },\n\t\t\n \"name\": {\n \"description\": \"Name of the product\",\n \"type\": \"string\"\n },\n\t\t\n \"price\": {\n \"type\": \"number\",\n \"minimum\": 0,\n \"exclusiveMinimum\": true\n }\n },\n\t\n \"required\": [\"id\", \"name\", \"price\"]\n}"
},
{
"code": null,
"e": 3046,
"s": 2969,
"text": "Let's the check various important keywords that can be used in this schema −"
},
{
"code": null,
"e": 3054,
"s": 3046,
"text": "$schema"
},
{
"code": null,
"e": 3150,
"s": 3054,
"text": "The $schema keyword states that this schema is written according to the draft v4 specification."
},
{
"code": null,
"e": 3156,
"s": 3150,
"text": "title"
},
{
"code": null,
"e": 3206,
"s": 3156,
"text": "You will use this to give a title to your schema."
},
{
"code": null,
"e": 3218,
"s": 3206,
"text": "description"
},
{
"code": null,
"e": 3254,
"s": 3218,
"text": "A little description of the schema."
},
{
"code": null,
"e": 3259,
"s": 3254,
"text": "type"
},
{
"code": null,
"e": 3351,
"s": 3259,
"text": "The type keyword defines the first constraint on our JSON data: it has to be a JSON Object."
},
{
"code": null,
"e": 3362,
"s": 3351,
"text": "properties"
},
{
"code": null,
"e": 3458,
"s": 3362,
"text": "Defines various keys and their value types, minimum and maximum values to be used in JSON file."
},
{
"code": null,
"e": 3467,
"s": 3458,
"text": "required"
},
{
"code": null,
"e": 3509,
"s": 3467,
"text": "This keeps a list of required properties."
},
{
"code": null,
"e": 3517,
"s": 3509,
"text": "minimum"
},
{
"code": null,
"e": 3604,
"s": 3517,
"text": "This is the constraint to be put on the value and represents minimum acceptable value."
},
{
"code": null,
"e": 3621,
"s": 3604,
"text": "exclusiveMinimum"
},
{
"code": null,
"e": 3759,
"s": 3621,
"text": "If \"exclusiveMinimum\" is present and has boolean value true, the instance is valid if it is strictly greater than the value of \"minimum\"."
},
{
"code": null,
"e": 3767,
"s": 3759,
"text": "maximum"
},
{
"code": null,
"e": 3854,
"s": 3767,
"text": "This is the constraint to be put on the value and represents maximum acceptable value."
},
{
"code": null,
"e": 3871,
"s": 3854,
"text": "exclusiveMaximum"
},
{
"code": null,
"e": 4007,
"s": 3871,
"text": "If \"exclusiveMaximum\" is present and has boolean value true, the instance is valid if it is strictly lower than the value of \"maximum\"."
},
{
"code": null,
"e": 4018,
"s": 4007,
"text": "multipleOf"
},
{
"code": null,
"e": 4152,
"s": 4018,
"text": "A numeric instance is valid against \"multipleOf\" if the result of the division of the instance by this keyword's value is an integer."
},
{
"code": null,
"e": 4162,
"s": 4152,
"text": "maxLength"
},
{
"code": null,
"e": 4246,
"s": 4162,
"text": "The length of a string instance is defined as the maximum number of its characters."
},
{
"code": null,
"e": 4256,
"s": 4246,
"text": "minLength"
},
{
"code": null,
"e": 4340,
"s": 4256,
"text": "The length of a string instance is defined as the minimum number of its characters."
},
{
"code": null,
"e": 4348,
"s": 4340,
"text": "pattern"
},
{
"code": null,
"e": 4447,
"s": 4348,
"text": "A string instance is considered valid if the regular expression matches the instance successfully."
},
{
"code": null,
"e": 4643,
"s": 4447,
"text": "You can check a http://json-schema.org for the complete list of keywords that can be used in defining a JSON schema. The above schema can be used to test the validity of the following JSON code −"
},
{
"code": null,
"e": 4808,
"s": 4643,
"text": "[\n {\n \"id\": 2,\n \"name\": \"An ice sculpture\",\n \"price\": 12.50,\n },\n\t\n {\n \"id\": 3,\n \"name\": \"A blue mouse\",\n \"price\": 25.50,\n }\n]"
},
{
"code": null,
"e": 4841,
"s": 4808,
"text": "\n 20 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4858,
"s": 4841,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 4891,
"s": 4858,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4908,
"s": 4891,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 4941,
"s": 4908,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4958,
"s": 4941,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 4993,
"s": 4958,
"text": "\n 23 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5010,
"s": 4993,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 5041,
"s": 5010,
"text": "\n 9 Lectures \n 48 mins\n"
},
{
"code": null,
"e": 5054,
"s": 5041,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 5089,
"s": 5054,
"text": "\n 18 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5112,
"s": 5089,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 5119,
"s": 5112,
"text": " Print"
},
{
"code": null,
"e": 5130,
"s": 5119,
"text": " Add Notes"
}
] |
How to open External Programs using Tkinter? - GeeksforGeeks
|
24 Jan, 2021
Prerequisite: Tkinter, os
Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. In this article, we will learn how to open an external program using Tkinter. Here we will use the system() method in the os module.
Approach:
First, we will import the required library
Then we create an object, which will ask for a file that you want to open
To open that file we will use the system() method from the os Module.
Syntax:
os.system(‘”%s”‘ % File Path)
Below is the Implementation:
Python3
# Import Libraryfrom tkinter import *import osfrom tkinter.filedialog import askopenfilename # Create Object root = Tk() # Set geometryroot.geometry('200x200') def open_file(): file = askopenfilename() os.system('"%s"' % file) Button(root, text ='Open', command = open_file).pack(side = TOP, pady = 10) # Execute Tkinterroot.mainloop()
Output:
Python Tkinter-exercises
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
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": 25108,
"s": 25080,
"text": "\n24 Jan, 2021"
},
{
"code": null,
"e": 25134,
"s": 25108,
"text": "Prerequisite: Tkinter, os"
},
{
"code": null,
"e": 25574,
"s": 25134,
"text": "Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. In this article, we will learn how to open an external program using Tkinter. Here we will use the system() method in the os module."
},
{
"code": null,
"e": 25584,
"s": 25574,
"text": "Approach:"
},
{
"code": null,
"e": 25627,
"s": 25584,
"text": "First, we will import the required library"
},
{
"code": null,
"e": 25701,
"s": 25627,
"text": "Then we create an object, which will ask for a file that you want to open"
},
{
"code": null,
"e": 25771,
"s": 25701,
"text": "To open that file we will use the system() method from the os Module."
},
{
"code": null,
"e": 25779,
"s": 25771,
"text": "Syntax:"
},
{
"code": null,
"e": 25809,
"s": 25779,
"text": "os.system(‘”%s”‘ % File Path)"
},
{
"code": null,
"e": 25838,
"s": 25809,
"text": "Below is the Implementation:"
},
{
"code": null,
"e": 25846,
"s": 25838,
"text": "Python3"
},
{
"code": "# Import Libraryfrom tkinter import *import osfrom tkinter.filedialog import askopenfilename # Create Object root = Tk() # Set geometryroot.geometry('200x200') def open_file(): file = askopenfilename() os.system('\"%s\"' % file) Button(root, text ='Open', command = open_file).pack(side = TOP, pady = 10) # Execute Tkinterroot.mainloop()",
"e": 26238,
"s": 25846,
"text": null
},
{
"code": null,
"e": 26246,
"s": 26238,
"text": "Output:"
},
{
"code": null,
"e": 26271,
"s": 26246,
"text": "Python Tkinter-exercises"
},
{
"code": null,
"e": 26286,
"s": 26271,
"text": "Python-tkinter"
},
{
"code": null,
"e": 26293,
"s": 26286,
"text": "Python"
},
{
"code": null,
"e": 26391,
"s": 26293,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26409,
"s": 26391,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26444,
"s": 26409,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26466,
"s": 26444,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26498,
"s": 26466,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26528,
"s": 26498,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26570,
"s": 26528,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26596,
"s": 26570,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26633,
"s": 26596,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26676,
"s": 26633,
"text": "Python program to convert a list to string"
}
] |
Reverse a String (Recursive) C++
|
Recursion is simply the way toward rehashing things in a self-comparative way. In programming dialects, if a program enables you to call a capacity inside a similar capacity, at that point, it is known as a recursive call of the capacity. You can switch a string utilizing the recursive capacity as appeared in the accompanying project.
Live Demo
#include <bits/stdc++.h>
using namespace std;
void reverse(string str){
if(str.size() == 0){
return;
}
reverse(str.substr(1));
cout << str[0];
}
int main(){
string a = "Arnold";
cout<<"recursive reverse (Arnold) ::";
reverse(a);
return 0;
}
The above C++ program accepts a string "Arnold" as an input then it yields results as "dlonrA" by applying recursion as;
Recursive reverse (Arnold):: dlonrA
|
[
{
"code": null,
"e": 1399,
"s": 1062,
"text": "Recursion is simply the way toward rehashing things in a self-comparative way. In programming dialects, if a program enables you to call a capacity inside a similar capacity, at that point, it is known as a recursive call of the capacity. You can switch a string utilizing the recursive capacity as appeared in the accompanying project."
},
{
"code": null,
"e": 1410,
"s": 1399,
"text": " Live Demo"
},
{
"code": null,
"e": 1681,
"s": 1410,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nvoid reverse(string str){\n if(str.size() == 0){\n return;\n }\n reverse(str.substr(1));\n cout << str[0];\n}\nint main(){\n string a = \"Arnold\";\n cout<<\"recursive reverse (Arnold) ::\";\n reverse(a);\n return 0;\n}"
},
{
"code": null,
"e": 1802,
"s": 1681,
"text": "The above C++ program accepts a string \"Arnold\" as an input then it yields results as \"dlonrA\" by applying recursion as;"
},
{
"code": null,
"e": 1838,
"s": 1802,
"text": "Recursive reverse (Arnold):: dlonrA"
}
] |
Fortran - Arithmetic Operators
|
Following table shows all the arithmetic operators supported by Fortran. Assume variable A holds 5 and variable B holds 3 then −
Try the following example to understand all the arithmetic operators available in Fortran −
program arithmeticOp
! this program performs arithmetic calculation
implicit none
! variable declaration
integer :: a, b, c
! assigning values
a = 5
b = 3
! Exponentiation
c = a ** b
! output
print *, "c = ", c
! Multiplication
c = a * b
! output
print *, "c = ", c
! Division
c = a / b
! output
print *, "c = ", c
! Addition
c = a + b
! output
print *, "c = ", c
! Subtraction
c = a - b
! output
print *, "c = ", c
end program arithmeticOp
When you compile and execute the above program, it produces the following result −
c = 125
c = 15
c = 1
c = 8
c = 2
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2275,
"s": 2146,
"text": "Following table shows all the arithmetic operators supported by Fortran. Assume variable A holds 5 and variable B holds 3 then −"
},
{
"code": null,
"e": 2367,
"s": 2275,
"text": "Try the following example to understand all the arithmetic operators available in Fortran −"
},
{
"code": null,
"e": 2957,
"s": 2367,
"text": "program arithmeticOp\n\n! this program performs arithmetic calculation\nimplicit none \n\n ! variable declaration\n integer :: a, b, c\n \n ! assigning values \n a = 5 \n b = 3 \n \n ! Exponentiation \n c = a ** b \n \n ! output \n print *, \"c = \", c\n \n ! Multiplication \n c = a * b \n \n ! output \n print *, \"c = \", c\n \n ! Division \n c = a / b \n \n ! output \n print *, \"c = \", c\n \n ! Addition\n c = a + b \n \n ! output \n print *, \"c = \", c\n \n ! Subtraction \n c = a - b \n \n ! output \n print *, \"c = \", c\n \nend program arithmeticOp"
},
{
"code": null,
"e": 3040,
"s": 2957,
"text": "When you compile and execute the above program, it produces the following result −"
},
{
"code": null,
"e": 3074,
"s": 3040,
"text": "c = 125\nc = 15\nc = 1\nc = 8\nc = 2\n"
},
{
"code": null,
"e": 3081,
"s": 3074,
"text": " Print"
},
{
"code": null,
"e": 3092,
"s": 3081,
"text": " Add Notes"
}
] |
How to get current Wi-Fi mac address in android?
|
This example demonstrate about How to get current Wi-Fi mac address in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:gravity = "center"
android:layout_height = "match_parent"
tools:context = ".MainActivity">
<TextView
android:id = "@+id/text"
android:textSize = "30sp"
android:layout_width = "match_parent"
android:layout_height = "match_parent" />
</LinearLayout>
In the above code, we have taken text view to show WIFI mac address.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
WifiManager wifiMgr = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
textView.setText("" + wifiInfo.getMacAddress());
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onResume() {
super.onResume();
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
package = "com.example.myapplication">
<uses-permission android:name = "android.permission.ACCESS_WIFI_STATE" />
<application
android:allowBackup = "true"
android:icon = "@mipmap/ic_launcher"
android:label = "@string/app_name"
android:roundIcon = "@mipmap/ic_launcher_round"
android:supportsRtl = "true"
android:theme = "@style/AppTheme">
<activity android:name = ".MainActivity">
<intent-filter>
<action android:name = "android.intent.action.MAIN" />
<action android:name = "android.net.conn.CONNECTIVITY_CHANGE" />
<category android:name = "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code
|
[
{
"code": null,
"e": 1142,
"s": 1062,
"text": "This example demonstrate about How to get current Wi-Fi mac address in android."
},
{
"code": null,
"e": 1271,
"s": 1142,
"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": 1336,
"s": 1271,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1896,
"s": 1336,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:gravity = \"center\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\">\n <TextView\n android:id = \"@+id/text\"\n android:textSize = \"30sp\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\" />\n</LinearLayout>"
},
{
"code": null,
"e": 1965,
"s": 1896,
"text": "In the above code, we have taken text view to show WIFI mac address."
},
{
"code": null,
"e": 2022,
"s": 1965,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2984,
"s": 2022,
"text": "package com.example.myapplication;\nimport android.net.wifi.WifiInfo;\nimport android.net.wifi.WifiManager;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n @RequiresApi(api = Build.VERSION_CODES.N)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.text);\n WifiManager wifiMgr = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);\n WifiInfo wifiInfo = wifiMgr.getConnectionInfo();\n textView.setText(\"\" + wifiInfo.getMacAddress());\n }\n @Override\n protected void onStop() {\n super.onStop();\n }\n @Override\n protected void onResume() {\n super.onResume();\n }\n}"
},
{
"code": null,
"e": 3039,
"s": 2984,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3903,
"s": 3039,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.myapplication\">\n <uses-permission android:name = \"android.permission.ACCESS_WIFI_STATE\" />\n <application\n android:allowBackup = \"true\"\n android:icon = \"@mipmap/ic_launcher\"\n android:label = \"@string/app_name\"\n android:roundIcon = \"@mipmap/ic_launcher_round\"\n android:supportsRtl = \"true\"\n android:theme = \"@style/AppTheme\">\n <activity android:name = \".MainActivity\">\n <intent-filter>\n <action android:name = \"android.intent.action.MAIN\" />\n <action android:name = \"android.net.conn.CONNECTIVITY_CHANGE\" />\n <category android:name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4250,
"s": 3903,
"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": 4290,
"s": 4250,
"text": "Click here to download the project code"
}
] |
How to Add and Remove multiple classes in jQuery ? - GeeksforGeeks
|
03 Aug, 2021
Given an HTML element and the task is to add and remove multiple classes from it using JQuery.
Approach:
First select the element to which multiple classes will be added.
Then use addClass() method to add multiple classes to the element and removeClass() method to remove multiple classes.
Example 1: This example add two classes color and fontWeight to the selected element using addClass() method.
<!DOCTYPE HTML> <html> <head> <title> How to Add and Remove multiple classes </title> <script src ="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <style> .color { color: red; } .fontWeight { font-weight: bold; } </style> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 19px;"> </p> <button onClick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "color: green; font-size: 24px; font-weight: bold;"> </p> <script> $('#GFG_UP').text("Click on button to add multiple" + " classes to this element"); function GFG_Fun() { $("#GFG_UP").addClass("color fontWeight"); $('#GFG_DOWN').text("color and fontWeight," + " Both classes added"); } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Example 2: This example remove two classes color and fontWeight from the selected element using removeClass() method.
<!DOCTYPE HTML> <html> <head> <title> How to Add and Remove multiple classes </title> <script src ="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <style> .color { color: red; } .fontWeight { font-weight: bold; } </style> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" class = "color fontWeight" style = "font-size: 19px;"> </p> <button onClick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "color: green; font-size: 24px; font-weight: bold;"> </p> <script> $('#GFG_UP').text("Click on button to remove" + " multiple classes to this element"); function GFG_Fun() { $("#GFG_UP").removeClass("color fontWeight"); $('#GFG_DOWN').text("color and fontWeight," + " Both classes removed"); } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on 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
JavaScript
JQuery
Web Technologies
Web technologies Questions
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 ?
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to change the background color after clicking the button in JavaScript ?
How to Dynamically Add/Remove Table Rows using jQuery ?
|
[
{
"code": null,
"e": 25015,
"s": 24987,
"text": "\n03 Aug, 2021"
},
{
"code": null,
"e": 25110,
"s": 25015,
"text": "Given an HTML element and the task is to add and remove multiple classes from it using JQuery."
},
{
"code": null,
"e": 25120,
"s": 25110,
"text": "Approach:"
},
{
"code": null,
"e": 25186,
"s": 25120,
"text": "First select the element to which multiple classes will be added."
},
{
"code": null,
"e": 25305,
"s": 25186,
"text": "Then use addClass() method to add multiple classes to the element and removeClass() method to remove multiple classes."
},
{
"code": null,
"e": 25415,
"s": 25305,
"text": "Example 1: This example add two classes color and fontWeight to the selected element using addClass() method."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> How to Add and Remove multiple classes </title> <script src =\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> <style> .color { color: red; } .fontWeight { font-weight: bold; } </style> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 19px;\"> </p> <button onClick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color: green; font-size: 24px; font-weight: bold;\"> </p> <script> $('#GFG_UP').text(\"Click on button to add multiple\" + \" classes to this element\"); function GFG_Fun() { $(\"#GFG_UP\").addClass(\"color fontWeight\"); $('#GFG_DOWN').text(\"color and fontWeight,\" + \" Both classes added\"); } </script> </body> </html> ",
"e": 26663,
"s": 25415,
"text": null
},
{
"code": null,
"e": 26671,
"s": 26663,
"text": "Output:"
},
{
"code": null,
"e": 26702,
"s": 26671,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 26732,
"s": 26702,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 26850,
"s": 26732,
"text": "Example 2: This example remove two classes color and fontWeight from the selected element using removeClass() method."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> How to Add and Remove multiple classes </title> <script src =\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> <style> .color { color: red; } .fontWeight { font-weight: bold; } </style> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" class = \"color fontWeight\" style = \"font-size: 19px;\"> </p> <button onClick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color: green; font-size: 24px; font-weight: bold;\"> </p> <script> $('#GFG_UP').text(\"Click on button to remove\" + \" multiple classes to this element\"); function GFG_Fun() { $(\"#GFG_UP\").removeClass(\"color fontWeight\"); $('#GFG_DOWN').text(\"color and fontWeight,\" + \" Both classes removed\"); } </script> </body> </html> ",
"e": 28147,
"s": 26850,
"text": null
},
{
"code": null,
"e": 28155,
"s": 28147,
"text": "Output:"
},
{
"code": null,
"e": 28186,
"s": 28155,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 28216,
"s": 28186,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 28484,
"s": 28216,
"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": 28496,
"s": 28484,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 28507,
"s": 28496,
"text": "JavaScript"
},
{
"code": null,
"e": 28514,
"s": 28507,
"text": "JQuery"
},
{
"code": null,
"e": 28531,
"s": 28514,
"text": "Web Technologies"
},
{
"code": null,
"e": 28558,
"s": 28531,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 28656,
"s": 28558,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28701,
"s": 28656,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28762,
"s": 28701,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28834,
"s": 28762,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 28886,
"s": 28834,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 28932,
"s": 28886,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 28978,
"s": 28932,
"text": "JQuery | Set the value of an input text field"
},
{
"code": null,
"e": 29007,
"s": 28978,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 29070,
"s": 29007,
"text": "How to change selected value of a drop-down list using jQuery?"
},
{
"code": null,
"e": 29147,
"s": 29070,
"text": "How to change the background color after clicking the button in JavaScript ?"
}
] |
MySQL query to select all entries from a particular month
|
To select all entries from a particular month in MySQL, use the monthname() or month() function.
The syntax is as follows.
select *from yourTableName where monthname(yourColumnName)='yourMonthName';
To understand the above syntax, let us create a table. The query to create a table is as follows
mysql> create table selectAllEntriesDemo
-> (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> ShippingDate datetime
-> );
Query OK, 0 rows affected (0.63 sec)
Insert some records in the table using insert command.
The query is as follows
mysql> insert into selectAllEntriesDemo(ShippingDate) values('2019-01-21');
Query OK, 1 row affected (0.24 sec)
mysql> insert into selectAllEntriesDemo(ShippingDate) values('2018-02-24');
Query OK, 1 row affected (0.15 sec)
mysql> insert into selectAllEntriesDemo(ShippingDate) values('2010-10-22');
Query OK, 1 row affected (0.20 sec)
mysql> insert into selectAllEntriesDemo(ShippingDate) values('2011-04-12');
Query OK, 1 row affected (0.12 sec)
mysql> insert into selectAllEntriesDemo(ShippingDate) values('2013-02-10');
Query OK, 1 row affected (0.18 sec)
mysql> insert into selectAllEntriesDemo(ShippingDate) values('2014-02-15');
Query OK, 1 row affected (0.16 sec)
mysql> insert into selectAllEntriesDemo(ShippingDate) values('2016-06-14');
Query OK, 1 row affected (0.18 sec)
mysql> insert into selectAllEntriesDemo(ShippingDate) values('2017-02-14');
Query OK, 1 row affected (0.51 sec)
mysql> insert into selectAllEntriesDemo(ShippingDate) values('2015-03-29');
Query OK, 1 row affected (0.19 sec)
Display all records from the table using select statement.
The query is as follows.
mysql> select *from selectAllEntriesDemo;
The following is the output.
+----+---------------------+
| Id | ShippingDate |
+----+---------------------+
| 1 | 2019-01-21 00:00:00 |
| 2 | 2018-02-24 00:00:00 |
| 3 | 2010-10-22 00:00:00 |
| 4 | 2011-04-12 00:00:00 |
| 5 | 2013-02-10 00:00:00 |
| 6 | 2014-02-15 00:00:00 |
| 7 | 2016-06-14 00:00:00 |
| 8 | 2017-02-14 00:00:00 |
| 9 | 2015-03-29 00:00:00 |
+----+---------------------+
9 rows in set (0.00 sec)
The following is the query to select all entries from a particular month:
mysql> select *from selectAllEntriesDemo where monthname(ShippingDate)='February';
Here is the output.
+----+---------------------+
| Id | ShippingDate |
+----+---------------------+
| 2 | 2018-02-24 00:00:00 |
| 5 | 2013-02-10 00:00:00 |
| 6 | 2014-02-15 00:00:00 |
| 8 | 2017-02-14 00:00:00 |
+----+---------------------+
4 rows in set (0.00 sec)
Here is an alternate query.
mysql> select *from selectAllEntriesDemo where month(ShippingDate)=2;
The following is the output.
+----+---------------------+
| Id | ShippingDate |
+----+---------------------+
| 2 | 2018-02-24 00:00:00 |
| 5 | 2013-02-10 00:00:00 |
| 6 | 2014-02-15 00:00:00 |
| 8 | 2017-02-14 00:00:00 |
+----+---------------------+
4 rows in set (0.04 sec)
|
[
{
"code": null,
"e": 1159,
"s": 1062,
"text": "To select all entries from a particular month in MySQL, use the monthname() or month() function."
},
{
"code": null,
"e": 1185,
"s": 1159,
"text": "The syntax is as follows."
},
{
"code": null,
"e": 1261,
"s": 1185,
"text": "select *from yourTableName where monthname(yourColumnName)='yourMonthName';"
},
{
"code": null,
"e": 1358,
"s": 1261,
"text": "To understand the above syntax, let us create a table. The query to create a table is as follows"
},
{
"code": null,
"e": 1531,
"s": 1358,
"text": "mysql> create table selectAllEntriesDemo\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> ShippingDate datetime\n -> );\nQuery OK, 0 rows affected (0.63 sec)"
},
{
"code": null,
"e": 1586,
"s": 1531,
"text": "Insert some records in the table using insert command."
},
{
"code": null,
"e": 1610,
"s": 1586,
"text": "The query is as follows"
},
{
"code": null,
"e": 2618,
"s": 1610,
"text": "mysql> insert into selectAllEntriesDemo(ShippingDate) values('2019-01-21');\nQuery OK, 1 row affected (0.24 sec)\nmysql> insert into selectAllEntriesDemo(ShippingDate) values('2018-02-24');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into selectAllEntriesDemo(ShippingDate) values('2010-10-22');\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into selectAllEntriesDemo(ShippingDate) values('2011-04-12');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into selectAllEntriesDemo(ShippingDate) values('2013-02-10');\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into selectAllEntriesDemo(ShippingDate) values('2014-02-15');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into selectAllEntriesDemo(ShippingDate) values('2016-06-14');\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into selectAllEntriesDemo(ShippingDate) values('2017-02-14');\nQuery OK, 1 row affected (0.51 sec)\nmysql> insert into selectAllEntriesDemo(ShippingDate) values('2015-03-29');\nQuery OK, 1 row affected (0.19 sec)"
},
{
"code": null,
"e": 2677,
"s": 2618,
"text": "Display all records from the table using select statement."
},
{
"code": null,
"e": 2702,
"s": 2677,
"text": "The query is as follows."
},
{
"code": null,
"e": 2744,
"s": 2702,
"text": "mysql> select *from selectAllEntriesDemo;"
},
{
"code": null,
"e": 2773,
"s": 2744,
"text": "The following is the output."
},
{
"code": null,
"e": 3175,
"s": 2773,
"text": "+----+---------------------+\n| Id | ShippingDate |\n+----+---------------------+\n| 1 | 2019-01-21 00:00:00 |\n| 2 | 2018-02-24 00:00:00 |\n| 3 | 2010-10-22 00:00:00 |\n| 4 | 2011-04-12 00:00:00 |\n| 5 | 2013-02-10 00:00:00 |\n| 6 | 2014-02-15 00:00:00 |\n| 7 | 2016-06-14 00:00:00 |\n| 8 | 2017-02-14 00:00:00 |\n| 9 | 2015-03-29 00:00:00 |\n+----+---------------------+\n9 rows in set (0.00 sec)"
},
{
"code": null,
"e": 3249,
"s": 3175,
"text": "The following is the query to select all entries from a particular month:"
},
{
"code": null,
"e": 3332,
"s": 3249,
"text": "mysql> select *from selectAllEntriesDemo where monthname(ShippingDate)='February';"
},
{
"code": null,
"e": 3352,
"s": 3332,
"text": "Here is the output."
},
{
"code": null,
"e": 3609,
"s": 3352,
"text": "+----+---------------------+\n| Id | ShippingDate |\n+----+---------------------+\n| 2 | 2018-02-24 00:00:00 |\n| 5 | 2013-02-10 00:00:00 |\n| 6 | 2014-02-15 00:00:00 |\n| 8 | 2017-02-14 00:00:00 |\n+----+---------------------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 3637,
"s": 3609,
"text": "Here is an alternate query."
},
{
"code": null,
"e": 3707,
"s": 3637,
"text": "mysql> select *from selectAllEntriesDemo where month(ShippingDate)=2;"
},
{
"code": null,
"e": 3736,
"s": 3707,
"text": "The following is the output."
},
{
"code": null,
"e": 3993,
"s": 3736,
"text": "+----+---------------------+\n| Id | ShippingDate |\n+----+---------------------+\n| 2 | 2018-02-24 00:00:00 |\n| 5 | 2013-02-10 00:00:00 |\n| 6 | 2014-02-15 00:00:00 |\n| 8 | 2017-02-14 00:00:00 |\n+----+---------------------+\n4 rows in set (0.04 sec)"
}
] |
Difference Between CrudRepository and JPARepository in Java
|
CrudRepository and JPA repository both are the interface of the spring data repository library. Spring data repository reduces the boilerplate code by providing some predefined finders to access the data layer for various persistence layers.
JPA repository extends CrudRepository and PagingAndSorting repository. It inherits some finders from crud repository such as findOne, gets and removes an entity. It also provides some extra methods related to JPA such as delete records in batch, flushing data directly to a database base and methods related to pagination and sorting.
We need to extend this repository in our application and then we can access all methods which are available in these repositories. We can also add new methods using named or native queries based on business requirements.
@Repository
public interface BookDAO extends JpaRepository {
Book findByAuthor(@Param("id") Integer id);
}
@Repository
public interface BookDAO extends CrudRepository {
Book Event findById(@Param("id") Integer id);
}
|
[
{
"code": null,
"e": 1304,
"s": 1062,
"text": "CrudRepository and JPA repository both are the interface of the spring data repository library. Spring data repository reduces the boilerplate code by providing some predefined finders to access the data layer for various persistence layers."
},
{
"code": null,
"e": 1639,
"s": 1304,
"text": "JPA repository extends CrudRepository and PagingAndSorting repository. It inherits some finders from crud repository such as findOne, gets and removes an entity. It also provides some extra methods related to JPA such as delete records in batch, flushing data directly to a database base and methods related to pagination and sorting."
},
{
"code": null,
"e": 1860,
"s": 1639,
"text": "We need to extend this repository in our application and then we can access all methods which are available in these repositories. We can also add new methods using named or native queries based on business requirements."
},
{
"code": null,
"e": 1970,
"s": 1860,
"text": "@Repository\npublic interface BookDAO extends JpaRepository {\n Book findByAuthor(@Param(\"id\") Integer id);\n}"
},
{
"code": null,
"e": 2083,
"s": 1970,
"text": "@Repository\npublic interface BookDAO extends CrudRepository {\n Book Event findById(@Param(\"id\") Integer id);\n}"
}
] |
Read ERA5 Directly into Memory with Python | by Luke Gloege, Ph.D. | Towards Data Science
|
ERA5 is the fifth generation climate reanalysis produced by the European Centre for Medium-Range Weather Forecasts (ECMWF). The product provides hourly output for many atmospheric, land-surface, and ocean-state parameters together with estimates of uncertainty. However, unless you are working in the cloud, storing raw hourly output can take up a lot of space.
This post outlines how to install the climate data store (CDS) API to read and analyze ERA5 output in Python.
The CDS API allows access to the ERA5 family of datasets, which includes ERA5 and, the land-only complement, ERA5-land. There are four main sub-sets to ERA5: hourly and monthly products each on pressure levels (including upper-air fields) and single levels (atmospheric, ocean, and land surface quantities). ERA5-land only includes single levels.
The four ERA5 subsets
ERA5 hourly data on single levels
ERA5 monthly averaged data on single levels
ERA5 hourly data on pressure levels
ERA5 monthly averaged data on pressure levels
The two ERA5-land subsets
ERA5-land hourly data
ERA5-land monthly data
The ERA5 reanalysis is described at length in this manuscript.
To begin using the CDS API the first thing you need to do is create an account with Copernicus and store your unique API key in a dot file. Here are the steps to do this:
Create an account with Copernicus by signing up here.Once you have an account, sign in to your Copercius account here and note the UID and API key at the bottom of the page.Paste the code snippet below into your terminal, replacing <UID> and <API key> with those from step 2:
Create an account with Copernicus by signing up here.
Once you have an account, sign in to your Copercius account here and note the UID and API key at the bottom of the page.
Paste the code snippet below into your terminal, replacing <UID> and <API key> with those from step 2:
{ echo 'url: https://cds.climate.copernicus.eu/api/v2' echo 'key: UID:API_KEY' echo 'verify: 0'} > ~/.cdsapirc
The above command creates the file ~/.cdsapirc with your API key, which is necessary to use the CDS API. As a sanity check, use more ~/.cdsapirc to ensure everything appears correct. A correct file will look similar to this:
url: https://cds.climate.copernicus.eu/api/v2key: 12345:a99b9c9d-9e99-9999-9999-fg99h9i99j9kverify: 0
Do not copy the above into your ~/.cdsapirc file, this is just for illustration.
Once you have your API key in ~/.cdsapirc you can install the cdsapi client via conda or pip:
pip install cdsapiorconda install cdsapi
Once installed, make sure you can import and start the client in a Python script without any errors.
import cdsapicds = cdsapi.Client()
The code below shows how to request monthly mean temperatures on a specified pressure level over a range of dates. Output is stored in memory as an xarray dataset, ds. The code below also allows the output to be saved to disk, this action can be toggled on or off using the download_flag:
import cdsapiimport xarray as xrfrom urllib.request import urlopen# start the clientcds = cdsapi.Client()# dataset you want to readdataset = "reanalysis-era5-pressure-levels-monthly-means"# flag to download datadownload_flag = False# api parameters params = { "format": "netcdf", "product_type": "monthly_averaged_reanalysis", "variable": "temperature", "pressure_level": '1000', 'year':['2019','2020'], 'month':['01','02','03'], "time": "00:00", "grid": [1.0, 1.0], "area": [90, -180, -90, 180], }# retrieves the path to the filefl = cds.retrieve(dataset, params)# download the file if download_flag: fl.download("./output.nc")# load into memorywith urlopen(fl.location) as f: ds = xr.open_dataset(f.read())
Here is an example of a more involved request where I am requesting January, February, and March for 2020. In addition, I am requesting the first day for each month at noon, 12:00. I am requesting data on a quarter degree grid and just area around the continental United States: [49.38, -124.67, 25.84, -66.95. Note that the area parameter specifies a bounding box with coordinates: [north, west, south, east].
import cdsapiimport xarray as xrfrom urllib.request import urlopenc = cdsapi.Client()# dataset to readdataset = 'reanalysis-era5-pressure-levels'# flag to download datadownload_flag = False# api parameters params = { 'format': 'netcdf', 'product_type': 'reanalysis', 'variable': 'temperature', 'pressure_level':'1000', 'year':['2020'], 'month':['01','02','03'], 'day': ['01'], 'time': ['12:00'], 'grid': [0.25, 0.25], 'area': [49.38, -124.67, 25.84, -66.95], }# retrieves the path to the filefl = c.retrieve(dataset, params)# download the file if download_flag: fl.download("./output.nc")# load into memorywith urlopen(fl.location) as f: ds = xr.open_dataset(f.read())
In place of the year, month, day, and time parameters, you could alternatively specify a list of dates:
'date':['2020-01-01 12:00', '2020-02-01 12:00', '2020-03-01 12:00'],
or you could specify a date and time like this:
'date':['2020-01-01', '2020-02-01', '2020-03-01'],'time: '12:00',
The above snippets each result in the same request, illustrating how flexible the API is. These requests are very specific and most of the time you will want to request a continuous range.
There are a few ways to do this. The easiest is to separate the dates you want by a slash, which specifies the start and end date for the requested range:
'date':'2020-01-01 12:00/2020-03-01 12:00'
Another option is to use pandas date_range. However, note that the input to the API has to be a list of strings. Here is an example using pandas:
‘date’: list(pd.date_range(‘2020–01–01 12:00',’2020–03–01 12:00', freq=’M’).strftime(‘%Y-%m-%d %H:%M’)),
Unfortunately, you can not use the date parameter when requesting monthly averages, it only works for the high temporal resolution data. For monthly averaged data you will have to use the year and month parameters, which also accept the slash notation:start/end.
The cdsapi is great for complex requests and is very flexible, but sometimes you get an error message that can be hard to diagnose.
no data is available within your requested subset. Request returned no data is a common error message, and it isn’t very helpful. This usually indicates that a keyword value is outside the available range. For example, only a specific set of pressure levels can be requested. Also, the time parameter has to be to the nearest hour using a 24-hour clock. Here are the common errors I see and how to fix them:
Pressure level must be contained in: [1, 2, 3, 5, 7, 10, 20, 30, 50, 70, range(100, 1000, 25)], where range(100,1000,25) indicates 100 to 1000 by increments of 25. If you get an error, check that the pressure you are requesting is contained in this list.
Time must be to the nearest hour on a 24-hour clock: 00:00, 01:00, ..., 23:00. If you get an error, check that the time is to the nearest hour. If you are requesting monthly means, make sure the time parameter is set to ‘00:00’.
I am unaware of any documentation for the CDS API, which can make it difficult to use since the allowable keywords and variable names vary depending on the dataset. The following links will be helpful:
Allowable keyword parameters for each dataset are here.
Variables available are listed in tables here. You supply what is listed in thevariable name in CDS column.
You could also look at the example script in the table here.
Another option is to use the web interface to make a selection and look at “show API request” at the bottom. Here is the form for “monthly averaged on pressure levels.” Other datasets can be found here. Click on the dataset you want to access and then the “Download data” tab to make your selection.
Once you understand how it works, you realize the CDS API is not very intimidating and is very powerful. I wrote a function to abstract away some of the nuances I described. This function is open source, so feel free to copy and modify it as you see fit.
Here is an example using the get_era5() function to create the image below:
Hats off to the ECMWF team for releasing the cdsapi and making the ERA5 reanalysis products easily accessible. The API has clear syntax and the ability to re-grid the output on the server-side is a godsend. ECMWF is also working on a package that aims to simplify access to these datasets even more so we can focus more on science and less on coding. At the time of writing it is still under development, but I encourage you to keep an eye on climetlab. However, climetlab does download the data behind the scenes. Hopefully, the ability to read output into memory without downloading it will be a feature in climetlab. Nevertheless, we can always revert to using the CDS API to achieve this.
Hopefully, this post helps you analyze ERA5 output and streamlines your data pipelines. Happy coding!
medium.com
medium.com
medium.com
Thank you for taking the time to read my post. This function started from conversations with my colleague, Jashvina Devadoss, who was working on a similar function.
Please comment below if you have questions, suggestions, or found this post useful.
Thank you for reading and supporting Medium writers
|
[
{
"code": null,
"e": 534,
"s": 172,
"text": "ERA5 is the fifth generation climate reanalysis produced by the European Centre for Medium-Range Weather Forecasts (ECMWF). The product provides hourly output for many atmospheric, land-surface, and ocean-state parameters together with estimates of uncertainty. However, unless you are working in the cloud, storing raw hourly output can take up a lot of space."
},
{
"code": null,
"e": 644,
"s": 534,
"text": "This post outlines how to install the climate data store (CDS) API to read and analyze ERA5 output in Python."
},
{
"code": null,
"e": 991,
"s": 644,
"text": "The CDS API allows access to the ERA5 family of datasets, which includes ERA5 and, the land-only complement, ERA5-land. There are four main sub-sets to ERA5: hourly and monthly products each on pressure levels (including upper-air fields) and single levels (atmospheric, ocean, and land surface quantities). ERA5-land only includes single levels."
},
{
"code": null,
"e": 1013,
"s": 991,
"text": "The four ERA5 subsets"
},
{
"code": null,
"e": 1047,
"s": 1013,
"text": "ERA5 hourly data on single levels"
},
{
"code": null,
"e": 1091,
"s": 1047,
"text": "ERA5 monthly averaged data on single levels"
},
{
"code": null,
"e": 1127,
"s": 1091,
"text": "ERA5 hourly data on pressure levels"
},
{
"code": null,
"e": 1173,
"s": 1127,
"text": "ERA5 monthly averaged data on pressure levels"
},
{
"code": null,
"e": 1199,
"s": 1173,
"text": "The two ERA5-land subsets"
},
{
"code": null,
"e": 1221,
"s": 1199,
"text": "ERA5-land hourly data"
},
{
"code": null,
"e": 1244,
"s": 1221,
"text": "ERA5-land monthly data"
},
{
"code": null,
"e": 1307,
"s": 1244,
"text": "The ERA5 reanalysis is described at length in this manuscript."
},
{
"code": null,
"e": 1478,
"s": 1307,
"text": "To begin using the CDS API the first thing you need to do is create an account with Copernicus and store your unique API key in a dot file. Here are the steps to do this:"
},
{
"code": null,
"e": 1754,
"s": 1478,
"text": "Create an account with Copernicus by signing up here.Once you have an account, sign in to your Copercius account here and note the UID and API key at the bottom of the page.Paste the code snippet below into your terminal, replacing <UID> and <API key> with those from step 2:"
},
{
"code": null,
"e": 1808,
"s": 1754,
"text": "Create an account with Copernicus by signing up here."
},
{
"code": null,
"e": 1929,
"s": 1808,
"text": "Once you have an account, sign in to your Copercius account here and note the UID and API key at the bottom of the page."
},
{
"code": null,
"e": 2032,
"s": 1929,
"text": "Paste the code snippet below into your terminal, replacing <UID> and <API key> with those from step 2:"
},
{
"code": null,
"e": 2146,
"s": 2032,
"text": "{ echo 'url: https://cds.climate.copernicus.eu/api/v2' echo 'key: UID:API_KEY' echo 'verify: 0'} > ~/.cdsapirc"
},
{
"code": null,
"e": 2371,
"s": 2146,
"text": "The above command creates the file ~/.cdsapirc with your API key, which is necessary to use the CDS API. As a sanity check, use more ~/.cdsapirc to ensure everything appears correct. A correct file will look similar to this:"
},
{
"code": null,
"e": 2473,
"s": 2371,
"text": "url: https://cds.climate.copernicus.eu/api/v2key: 12345:a99b9c9d-9e99-9999-9999-fg99h9i99j9kverify: 0"
},
{
"code": null,
"e": 2554,
"s": 2473,
"text": "Do not copy the above into your ~/.cdsapirc file, this is just for illustration."
},
{
"code": null,
"e": 2648,
"s": 2554,
"text": "Once you have your API key in ~/.cdsapirc you can install the cdsapi client via conda or pip:"
},
{
"code": null,
"e": 2689,
"s": 2648,
"text": "pip install cdsapiorconda install cdsapi"
},
{
"code": null,
"e": 2790,
"s": 2689,
"text": "Once installed, make sure you can import and start the client in a Python script without any errors."
},
{
"code": null,
"e": 2825,
"s": 2790,
"text": "import cdsapicds = cdsapi.Client()"
},
{
"code": null,
"e": 3114,
"s": 2825,
"text": "The code below shows how to request monthly mean temperatures on a specified pressure level over a range of dates. Output is stored in memory as an xarray dataset, ds. The code below also allows the output to be saved to disk, this action can be toggled on or off using the download_flag:"
},
{
"code": null,
"e": 3860,
"s": 3114,
"text": "import cdsapiimport xarray as xrfrom urllib.request import urlopen# start the clientcds = cdsapi.Client()# dataset you want to readdataset = \"reanalysis-era5-pressure-levels-monthly-means\"# flag to download datadownload_flag = False# api parameters params = { \"format\": \"netcdf\", \"product_type\": \"monthly_averaged_reanalysis\", \"variable\": \"temperature\", \"pressure_level\": '1000', 'year':['2019','2020'], 'month':['01','02','03'], \"time\": \"00:00\", \"grid\": [1.0, 1.0], \"area\": [90, -180, -90, 180], }# retrieves the path to the filefl = cds.retrieve(dataset, params)# download the file if download_flag: fl.download(\"./output.nc\")# load into memorywith urlopen(fl.location) as f: ds = xr.open_dataset(f.read())"
},
{
"code": null,
"e": 4271,
"s": 3860,
"text": "Here is an example of a more involved request where I am requesting January, February, and March for 2020. In addition, I am requesting the first day for each month at noon, 12:00. I am requesting data on a quarter degree grid and just area around the continental United States: [49.38, -124.67, 25.84, -66.95. Note that the area parameter specifies a bounding box with coordinates: [north, west, south, east]."
},
{
"code": null,
"e": 4979,
"s": 4271,
"text": "import cdsapiimport xarray as xrfrom urllib.request import urlopenc = cdsapi.Client()# dataset to readdataset = 'reanalysis-era5-pressure-levels'# flag to download datadownload_flag = False# api parameters params = { 'format': 'netcdf', 'product_type': 'reanalysis', 'variable': 'temperature', 'pressure_level':'1000', 'year':['2020'], 'month':['01','02','03'], 'day': ['01'], 'time': ['12:00'], 'grid': [0.25, 0.25], 'area': [49.38, -124.67, 25.84, -66.95], }# retrieves the path to the filefl = c.retrieve(dataset, params)# download the file if download_flag: fl.download(\"./output.nc\")# load into memorywith urlopen(fl.location) as f: ds = xr.open_dataset(f.read())"
},
{
"code": null,
"e": 5083,
"s": 4979,
"text": "In place of the year, month, day, and time parameters, you could alternatively specify a list of dates:"
},
{
"code": null,
"e": 5152,
"s": 5083,
"text": "'date':['2020-01-01 12:00', '2020-02-01 12:00', '2020-03-01 12:00'],"
},
{
"code": null,
"e": 5200,
"s": 5152,
"text": "or you could specify a date and time like this:"
},
{
"code": null,
"e": 5266,
"s": 5200,
"text": "'date':['2020-01-01', '2020-02-01', '2020-03-01'],'time: '12:00',"
},
{
"code": null,
"e": 5455,
"s": 5266,
"text": "The above snippets each result in the same request, illustrating how flexible the API is. These requests are very specific and most of the time you will want to request a continuous range."
},
{
"code": null,
"e": 5610,
"s": 5455,
"text": "There are a few ways to do this. The easiest is to separate the dates you want by a slash, which specifies the start and end date for the requested range:"
},
{
"code": null,
"e": 5653,
"s": 5610,
"text": "'date':'2020-01-01 12:00/2020-03-01 12:00'"
},
{
"code": null,
"e": 5799,
"s": 5653,
"text": "Another option is to use pandas date_range. However, note that the input to the API has to be a list of strings. Here is an example using pandas:"
},
{
"code": null,
"e": 5904,
"s": 5799,
"text": "‘date’: list(pd.date_range(‘2020–01–01 12:00',’2020–03–01 12:00', freq=’M’).strftime(‘%Y-%m-%d %H:%M’)),"
},
{
"code": null,
"e": 6167,
"s": 5904,
"text": "Unfortunately, you can not use the date parameter when requesting monthly averages, it only works for the high temporal resolution data. For monthly averaged data you will have to use the year and month parameters, which also accept the slash notation:start/end."
},
{
"code": null,
"e": 6299,
"s": 6167,
"text": "The cdsapi is great for complex requests and is very flexible, but sometimes you get an error message that can be hard to diagnose."
},
{
"code": null,
"e": 6707,
"s": 6299,
"text": "no data is available within your requested subset. Request returned no data is a common error message, and it isn’t very helpful. This usually indicates that a keyword value is outside the available range. For example, only a specific set of pressure levels can be requested. Also, the time parameter has to be to the nearest hour using a 24-hour clock. Here are the common errors I see and how to fix them:"
},
{
"code": null,
"e": 6962,
"s": 6707,
"text": "Pressure level must be contained in: [1, 2, 3, 5, 7, 10, 20, 30, 50, 70, range(100, 1000, 25)], where range(100,1000,25) indicates 100 to 1000 by increments of 25. If you get an error, check that the pressure you are requesting is contained in this list."
},
{
"code": null,
"e": 7191,
"s": 6962,
"text": "Time must be to the nearest hour on a 24-hour clock: 00:00, 01:00, ..., 23:00. If you get an error, check that the time is to the nearest hour. If you are requesting monthly means, make sure the time parameter is set to ‘00:00’."
},
{
"code": null,
"e": 7393,
"s": 7191,
"text": "I am unaware of any documentation for the CDS API, which can make it difficult to use since the allowable keywords and variable names vary depending on the dataset. The following links will be helpful:"
},
{
"code": null,
"e": 7449,
"s": 7393,
"text": "Allowable keyword parameters for each dataset are here."
},
{
"code": null,
"e": 7557,
"s": 7449,
"text": "Variables available are listed in tables here. You supply what is listed in thevariable name in CDS column."
},
{
"code": null,
"e": 7618,
"s": 7557,
"text": "You could also look at the example script in the table here."
},
{
"code": null,
"e": 7918,
"s": 7618,
"text": "Another option is to use the web interface to make a selection and look at “show API request” at the bottom. Here is the form for “monthly averaged on pressure levels.” Other datasets can be found here. Click on the dataset you want to access and then the “Download data” tab to make your selection."
},
{
"code": null,
"e": 8173,
"s": 7918,
"text": "Once you understand how it works, you realize the CDS API is not very intimidating and is very powerful. I wrote a function to abstract away some of the nuances I described. This function is open source, so feel free to copy and modify it as you see fit."
},
{
"code": null,
"e": 8249,
"s": 8173,
"text": "Here is an example using the get_era5() function to create the image below:"
},
{
"code": null,
"e": 8942,
"s": 8249,
"text": "Hats off to the ECMWF team for releasing the cdsapi and making the ERA5 reanalysis products easily accessible. The API has clear syntax and the ability to re-grid the output on the server-side is a godsend. ECMWF is also working on a package that aims to simplify access to these datasets even more so we can focus more on science and less on coding. At the time of writing it is still under development, but I encourage you to keep an eye on climetlab. However, climetlab does download the data behind the scenes. Hopefully, the ability to read output into memory without downloading it will be a feature in climetlab. Nevertheless, we can always revert to using the CDS API to achieve this."
},
{
"code": null,
"e": 9044,
"s": 8942,
"text": "Hopefully, this post helps you analyze ERA5 output and streamlines your data pipelines. Happy coding!"
},
{
"code": null,
"e": 9055,
"s": 9044,
"text": "medium.com"
},
{
"code": null,
"e": 9066,
"s": 9055,
"text": "medium.com"
},
{
"code": null,
"e": 9077,
"s": 9066,
"text": "medium.com"
},
{
"code": null,
"e": 9242,
"s": 9077,
"text": "Thank you for taking the time to read my post. This function started from conversations with my colleague, Jashvina Devadoss, who was working on a similar function."
},
{
"code": null,
"e": 9326,
"s": 9242,
"text": "Please comment below if you have questions, suggestions, or found this post useful."
}
] |
Getting hash of a file using CMD - GeeksforGeeks
|
23 Oct, 2020
A cryptographic hash is a fixed size string (or text) that is used as an identifier/fingerprint of some data. These are particularly useful in determining the integrity of files after they are transferred over a communication channel. Hashes are even utilized by certain OS-level processes for their working. The command processor of Windows OS (cmd.exe) provides the user with the ability to compute hashes on files/Directories via an utility command named Certutil. In this article we would learn about computing hashes on command prompt (cmd).
Description of command :The command Certutil is primarily used for working with digital certificates and not hashes. The ability to hash files is due to the presence of a -hashfile switch in it.
> Certutil -hashfile
-hashfile -- Generate and display cryptographic hash over a file
Where certutil is the command, and -hashfile is a switch provided to it.Syntax :The -hashfile switch takes in two arguments. Firstly, the path to the file in which we are interested in getting the hash. And then the hash algorithm that we are interested in.
Creating a syntax :
Certutil -hashfile (Path_to_file) [HashAlgo]
Where Path_to_file is mandatory(should be provided) argument and HashAlgo is optional argument (If not provided, defaults to SHA1). If HashAlgo is provided it should either be from SHA (Secure Hash Algorithms) or from MD (Message Digest) Cryptographic Hash families. Some of the hash algorithms allowed in the command are MD4, MD5, SHA1, SHA256, SHA512.
Usage of the command :To demonstrate the usage of the command, we would be running the command on a file. Our example file will be at the location “C:\Users\Public\spars.txt” .
That contains some text data. So to get the MD5 (Message Digest 5) hash of the file, we would have to execute the command.
certutil -hashfile "C:\Users\Public\spars.txt" MD5
The command upon execution would produce an output similar to this.
MD5 hash of spars.txt:
cb21e6741817a2d3020e02bb94301ae4
CertUtil: -hashfile command completed successfully.
To get SHA512 hash of the above file the command and the output would appear as following :
Hash
Operating Systems
Operating Systems
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Memory Management in Operating System
Difference between Internal and External fragmentation
Program for Least Recently Used (LRU) Page Replacement algorithm
Mutex lock for Linux Thread Synchronization
Logical and Physical Address in Operating System
File Allocation Methods
States of a Process in Operating Systems
Shortest Remaining Time First (Preemptive SJF) Scheduling Algorithm
Dining Philosopher Problem Using Semaphores
Producer Consumer Problem using Semaphores | Set 1
|
[
{
"code": null,
"e": 24492,
"s": 24464,
"text": "\n23 Oct, 2020"
},
{
"code": null,
"e": 25039,
"s": 24492,
"text": "A cryptographic hash is a fixed size string (or text) that is used as an identifier/fingerprint of some data. These are particularly useful in determining the integrity of files after they are transferred over a communication channel. Hashes are even utilized by certain OS-level processes for their working. The command processor of Windows OS (cmd.exe) provides the user with the ability to compute hashes on files/Directories via an utility command named Certutil. In this article we would learn about computing hashes on command prompt (cmd)."
},
{
"code": null,
"e": 25234,
"s": 25039,
"text": "Description of command :The command Certutil is primarily used for working with digital certificates and not hashes. The ability to hash files is due to the presence of a -hashfile switch in it."
},
{
"code": null,
"e": 25322,
"s": 25234,
"text": "> Certutil -hashfile\n-hashfile -- Generate and display cryptographic hash over a file\n"
},
{
"code": null,
"e": 25580,
"s": 25322,
"text": "Where certutil is the command, and -hashfile is a switch provided to it.Syntax :The -hashfile switch takes in two arguments. Firstly, the path to the file in which we are interested in getting the hash. And then the hash algorithm that we are interested in."
},
{
"code": null,
"e": 25600,
"s": 25580,
"text": "Creating a syntax :"
},
{
"code": null,
"e": 25646,
"s": 25600,
"text": "Certutil -hashfile (Path_to_file) [HashAlgo]\n"
},
{
"code": null,
"e": 26000,
"s": 25646,
"text": "Where Path_to_file is mandatory(should be provided) argument and HashAlgo is optional argument (If not provided, defaults to SHA1). If HashAlgo is provided it should either be from SHA (Secure Hash Algorithms) or from MD (Message Digest) Cryptographic Hash families. Some of the hash algorithms allowed in the command are MD4, MD5, SHA1, SHA256, SHA512."
},
{
"code": null,
"e": 26177,
"s": 26000,
"text": "Usage of the command :To demonstrate the usage of the command, we would be running the command on a file. Our example file will be at the location “C:\\Users\\Public\\spars.txt” ."
},
{
"code": null,
"e": 26300,
"s": 26177,
"text": "That contains some text data. So to get the MD5 (Message Digest 5) hash of the file, we would have to execute the command."
},
{
"code": null,
"e": 26351,
"s": 26300,
"text": "certutil -hashfile \"C:\\Users\\Public\\spars.txt\" MD5"
},
{
"code": null,
"e": 26419,
"s": 26351,
"text": "The command upon execution would produce an output similar to this."
},
{
"code": null,
"e": 26528,
"s": 26419,
"text": "MD5 hash of spars.txt:\ncb21e6741817a2d3020e02bb94301ae4\nCertUtil: -hashfile command completed successfully.\n"
},
{
"code": null,
"e": 26620,
"s": 26528,
"text": "To get SHA512 hash of the above file the command and the output would appear as following :"
},
{
"code": null,
"e": 26625,
"s": 26620,
"text": "Hash"
},
{
"code": null,
"e": 26643,
"s": 26625,
"text": "Operating Systems"
},
{
"code": null,
"e": 26661,
"s": 26643,
"text": "Operating Systems"
},
{
"code": null,
"e": 26666,
"s": 26661,
"text": "Hash"
},
{
"code": null,
"e": 26764,
"s": 26666,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26802,
"s": 26764,
"text": "Memory Management in Operating System"
},
{
"code": null,
"e": 26857,
"s": 26802,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 26922,
"s": 26857,
"text": "Program for Least Recently Used (LRU) Page Replacement algorithm"
},
{
"code": null,
"e": 26966,
"s": 26922,
"text": "Mutex lock for Linux Thread Synchronization"
},
{
"code": null,
"e": 27015,
"s": 26966,
"text": "Logical and Physical Address in Operating System"
},
{
"code": null,
"e": 27039,
"s": 27015,
"text": "File Allocation Methods"
},
{
"code": null,
"e": 27080,
"s": 27039,
"text": "States of a Process in Operating Systems"
},
{
"code": null,
"e": 27148,
"s": 27080,
"text": "Shortest Remaining Time First (Preemptive SJF) Scheduling Algorithm"
},
{
"code": null,
"e": 27192,
"s": 27148,
"text": "Dining Philosopher Problem Using Semaphores"
}
] |
How to select a radio button by default in JavaScript?
|
To select a radio button by default we have to check it as true. If it is checked as true then by default it will be autofocused.
In the following example, we have only radio buttons and none of them is autofocused.
Live Demo
<html>
<form id="radiobuttons" name="radiobutton">
<input id="rad1" value="a" type="radio" name="check"/>male
<input id="rad2" value="b" type="radio" name="check"/>female
<input id="rad3" value="c" type="radio" name="check"/>other
</form>
<body>
</body>
</html>
When the above code is executed we will get radio buttons and none of them is autofocused as shown in the following image.
To autofocus any of the above buttons we have to check them initially. This can be done by using pure javascript as shown in the following example.
Live Demo
<html>
<form id="radiobuttons" name="radiobutton">
<input id="rad1" value="a" type="radio" name="check"/>male
<input id="rad2" value="b" type="radio" name="check"/>female
<input id="rad3" value="c" type="radio" name="check"/>other
</form>
<body>
<script>
radiobtn = document.getElementById("rad1");
radiobtn.checked = true;
</script>
</body>
</html>
After executing the above code, we will get the following output.
|
[
{
"code": null,
"e": 1193,
"s": 1062,
"text": "To select a radio button by default we have to check it as true. If it is checked as true then by default it will be autofocused. "
},
{
"code": null,
"e": 1279,
"s": 1193,
"text": "In the following example, we have only radio buttons and none of them is autofocused."
},
{
"code": null,
"e": 1289,
"s": 1279,
"text": "Live Demo"
},
{
"code": null,
"e": 1575,
"s": 1289,
"text": "<html>\n <form id=\"radiobuttons\" name=\"radiobutton\">\n <input id=\"rad1\" value=\"a\" type=\"radio\" name=\"check\"/>male\n <input id=\"rad2\" value=\"b\" type=\"radio\" name=\"check\"/>female\n <input id=\"rad3\" value=\"c\" type=\"radio\" name=\"check\"/>other\n </form>\n<body>\n</body>\n</html>"
},
{
"code": null,
"e": 1698,
"s": 1575,
"text": "When the above code is executed we will get radio buttons and none of them is autofocused as shown in the following image."
},
{
"code": null,
"e": 1846,
"s": 1698,
"text": "To autofocus any of the above buttons we have to check them initially. This can be done by using pure javascript as shown in the following example."
},
{
"code": null,
"e": 1856,
"s": 1846,
"text": "Live Demo"
},
{
"code": null,
"e": 2236,
"s": 1856,
"text": "<html>\n <form id=\"radiobuttons\" name=\"radiobutton\">\n <input id=\"rad1\" value=\"a\" type=\"radio\" name=\"check\"/>male\n <input id=\"rad2\" value=\"b\" type=\"radio\" name=\"check\"/>female\n <input id=\"rad3\" value=\"c\" type=\"radio\" name=\"check\"/>other\n </form>\n<body>\n<script>\n radiobtn = document.getElementById(\"rad1\");\n radiobtn.checked = true;\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2302,
"s": 2236,
"text": "After executing the above code, we will get the following output."
}
] |
How to check if a column is categorical in R data frame?
|
To check if a column is categorical in R data frame, we can follow the below steps −
First of all, create a data frame.
Use class function to check the class of the column.
Let's create a data frame as shown below −
Live Demo
x<-rpois(25,2)
y<-sample(LETTERS[1:4],25,replace=TRUE)
z<-factor(sample(c("Low","Medium","High"),25,replace=TRUE))
df<-data.frame(x,y,z)
df
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
x y z
1 4 D High
2 1 B High
3 1 C High
4 2 A Medium
5 3 B High
6 2 D Medium
7 2 C Low
8 1 A Low
9 5 D Medium
10 3 D Low
11 1 B Medium
12 3 B High
13 5 C Medium
14 4 C Medium
15 1 B High
16 1 C Low
17 3 A Medium
18 1 D Low
19 1 B High
20 1 D Medium
21 3 B High
22 4 A Low
23 2 C High
24 2 A Medium
25 5 B High
Use class function to find whether column x is categorical or not −
Live Demo
x<-rpois(25,2)
y<-sample(LETTERS[1:4],25,replace=TRUE)
z<-factor(sample(c("Low","Medium","High"),25,replace=TRUE))
df<-data.frame(x,y,z)
class(df$x)
[1] "integer"
Use class function to find whether column y is categorical or not −
Live Demo
x<-rpois(25,2)
y<-sample(LETTERS[1:4],25,replace=TRUE)
z<-factor(sample(c("Low","Medium","High"),25,replace=TRUE))
df<-data.frame(x,y,z)
class(df$y)
[1] "character"
Use class function to find whether column z is categorical or not −
Live Demo
x<-rpois(25,2)
y<-sample(LETTERS[1:4],25,replace=TRUE)
z<-factor(sample(c("Low","Medium","High"),25,replace=TRUE))
df<-data.frame(x,y,z)
class(df$z)
[1] "factor"
|
[
{
"code": null,
"e": 1147,
"s": 1062,
"text": "To check if a column is categorical in R data frame, we can follow the below steps −"
},
{
"code": null,
"e": 1182,
"s": 1147,
"text": "First of all, create a data frame."
},
{
"code": null,
"e": 1235,
"s": 1182,
"text": "Use class function to check the class of the column."
},
{
"code": null,
"e": 1278,
"s": 1235,
"text": "Let's create a data frame as shown below −"
},
{
"code": null,
"e": 1289,
"s": 1278,
"text": " Live Demo"
},
{
"code": null,
"e": 1429,
"s": 1289,
"text": "x<-rpois(25,2)\ny<-sample(LETTERS[1:4],25,replace=TRUE)\nz<-factor(sample(c(\"Low\",\"Medium\",\"High\"),25,replace=TRUE))\ndf<-data.frame(x,y,z)\ndf"
},
{
"code": null,
"e": 1548,
"s": 1429,
"text": "On executing, the above script generates the below output(this output will vary on your system due to randomization) −"
},
{
"code": null,
"e": 1870,
"s": 1548,
"text": " x y z\n1 4 D High\n2 1 B High\n3 1 C High\n4 2 A Medium\n5 3 B High\n6 2 D Medium\n7 2 C Low\n8 1 A Low\n9 5 D Medium\n10 3 D Low\n11 1 B Medium\n12 3 B High\n13 5 C Medium\n14 4 C Medium\n15 1 B High\n16 1 C Low\n17 3 A Medium\n18 1 D Low\n19 1 B High\n20 1 D Medium\n21 3 B High\n22 4 A Low\n23 2 C High\n24 2 A Medium\n25 5 B High"
},
{
"code": null,
"e": 1938,
"s": 1870,
"text": "Use class function to find whether column x is categorical or not −"
},
{
"code": null,
"e": 1949,
"s": 1938,
"text": " Live Demo"
},
{
"code": null,
"e": 2098,
"s": 1949,
"text": "x<-rpois(25,2)\ny<-sample(LETTERS[1:4],25,replace=TRUE)\nz<-factor(sample(c(\"Low\",\"Medium\",\"High\"),25,replace=TRUE))\ndf<-data.frame(x,y,z)\nclass(df$x)"
},
{
"code": null,
"e": 2112,
"s": 2098,
"text": "[1] \"integer\""
},
{
"code": null,
"e": 2180,
"s": 2112,
"text": "Use class function to find whether column y is categorical or not −"
},
{
"code": null,
"e": 2191,
"s": 2180,
"text": " Live Demo"
},
{
"code": null,
"e": 2340,
"s": 2191,
"text": "x<-rpois(25,2)\ny<-sample(LETTERS[1:4],25,replace=TRUE)\nz<-factor(sample(c(\"Low\",\"Medium\",\"High\"),25,replace=TRUE))\ndf<-data.frame(x,y,z)\nclass(df$y)"
},
{
"code": null,
"e": 2356,
"s": 2340,
"text": "[1] \"character\""
},
{
"code": null,
"e": 2424,
"s": 2356,
"text": "Use class function to find whether column z is categorical or not −"
},
{
"code": null,
"e": 2435,
"s": 2424,
"text": " Live Demo"
},
{
"code": null,
"e": 2584,
"s": 2435,
"text": "x<-rpois(25,2)\ny<-sample(LETTERS[1:4],25,replace=TRUE)\nz<-factor(sample(c(\"Low\",\"Medium\",\"High\"),25,replace=TRUE))\ndf<-data.frame(x,y,z)\nclass(df$z)"
},
{
"code": null,
"e": 2597,
"s": 2584,
"text": "[1] \"factor\""
}
] |
C++ Program to Remove all Characters in a String Except Alphabets
|
A string is a one-dimensional character array that is terminated by a null character. It may contain characters, digits, special symbols etc.
A program to remove all characters in a string except alphabets is given as follows.
#include <iostream>
using namespace std;
int main() {
char str[100] = "String@123!!";
int i, j;
cout<<"String before modification: "<<str<<endl;
for(i = 0; str[i] != '\0'; ++i) {
while(!( (str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z') || str[i] == '\0') {
for(j = i; str[j] != '\0'; ++j) {
str[j] = str[j+1];
}
}
}
cout<<"String after modification: "<<str;
return 0;
}
String before modification: String@123!!
String after modification: String
In the above program, the string modification is done in a for loop. If the character in the string is not an alphabet or null, then all the characters to the right of that character are shifted towards the left by 1. This is done using j in the inner for loop. This leads to the removal of the non alphabetic character. A code snippet that demonstrates this is as follows −
for(i = 0; str[i] != '\0'; ++i) {
while(!( (str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z') || str[i] == '\0') ) {
for(j = i; str[j] != '\0'; ++j) {
str[j] = str[j+1];
}
}
}
After modification, the string is displayed. This is shown below −
cout<<"String after modification: "<<str;
|
[
{
"code": null,
"e": 1204,
"s": 1062,
"text": "A string is a one-dimensional character array that is terminated by a null character. It may contain characters, digits, special symbols etc."
},
{
"code": null,
"e": 1289,
"s": 1204,
"text": "A program to remove all characters in a string except alphabets is given as follows."
},
{
"code": null,
"e": 1752,
"s": 1289,
"text": "#include <iostream>\nusing namespace std;\nint main() {\n char str[100] = \"String@123!!\";\n int i, j;\n cout<<\"String before modification: \"<<str<<endl;\n for(i = 0; str[i] != '\\0'; ++i) {\n while(!( (str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z') || str[i] == '\\0') {\n for(j = i; str[j] != '\\0'; ++j) {\n str[j] = str[j+1];\n }\n }\n }\n cout<<\"String after modification: \"<<str;\n return 0;\n}"
},
{
"code": null,
"e": 1827,
"s": 1752,
"text": "String before modification: String@123!!\nString after modification: String"
},
{
"code": null,
"e": 2202,
"s": 1827,
"text": "In the above program, the string modification is done in a for loop. If the character in the string is not an alphabet or null, then all the characters to the right of that character are shifted towards the left by 1. This is done using j in the inner for loop. This leads to the removal of the non alphabetic character. A code snippet that demonstrates this is as follows −"
},
{
"code": null,
"e": 2426,
"s": 2202,
"text": "for(i = 0; str[i] != '\\0'; ++i) {\n while(!( (str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z') || str[i] == '\\0') ) {\n for(j = i; str[j] != '\\0'; ++j) {\n str[j] = str[j+1];\n }\n }\n}"
},
{
"code": null,
"e": 2493,
"s": 2426,
"text": "After modification, the string is displayed. This is shown below −"
},
{
"code": null,
"e": 2535,
"s": 2493,
"text": "cout<<\"String after modification: \"<<str;"
}
] |
MongoDB query for exact match
|
For exact match, you can use $exists that checks for a match. Let us create a collection with documents −
> db.demo290.insertOne({"ListOfName":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e4c0c9e5d93261e4bc9ea2d")
}
> db.demo290.insertOne({"ListOfName":["Chris","David"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e4c0cb05d93261e4bc9ea2e")
}
Display all documents from a collection with the help of find() method −
> db.demo290.find();
This will produce the following output −
{ "_id" : ObjectId("5e4c0c9e5d93261e4bc9ea2d"), "ListOfName" : "Chris" }
{ "_id" : ObjectId("5e4c0cb05d93261e4bc9ea2e"), "ListOfName" : [ "Chris", "David" ] }
Here is the query for exact match of a value −
> db.demo290.find({$and: [{'ListOfName.0': {$exists: false}}, {"ListOfName": 'Chris'}]});
This will produce the following output −
{ "_id" : ObjectId("5e4c0c9e5d93261e4bc9ea2d"), "ListOfName" : "Chris" }
|
[
{
"code": null,
"e": 1168,
"s": 1062,
"text": "For exact match, you can use $exists that checks for a match. Let us create a collection with documents −"
},
{
"code": null,
"e": 1444,
"s": 1168,
"text": "> db.demo290.insertOne({\"ListOfName\":\"Chris\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e4c0c9e5d93261e4bc9ea2d\")\n}\n> db.demo290.insertOne({\"ListOfName\":[\"Chris\",\"David\"]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e4c0cb05d93261e4bc9ea2e\")\n}"
},
{
"code": null,
"e": 1517,
"s": 1444,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1538,
"s": 1517,
"text": "> db.demo290.find();"
},
{
"code": null,
"e": 1579,
"s": 1538,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1738,
"s": 1579,
"text": "{ \"_id\" : ObjectId(\"5e4c0c9e5d93261e4bc9ea2d\"), \"ListOfName\" : \"Chris\" }\n{ \"_id\" : ObjectId(\"5e4c0cb05d93261e4bc9ea2e\"), \"ListOfName\" : [ \"Chris\", \"David\" ] }"
},
{
"code": null,
"e": 1785,
"s": 1738,
"text": "Here is the query for exact match of a value −"
},
{
"code": null,
"e": 1875,
"s": 1785,
"text": "> db.demo290.find({$and: [{'ListOfName.0': {$exists: false}}, {\"ListOfName\": 'Chris'}]});"
},
{
"code": null,
"e": 1916,
"s": 1875,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1989,
"s": 1916,
"text": "{ \"_id\" : ObjectId(\"5e4c0c9e5d93261e4bc9ea2d\"), \"ListOfName\" : \"Chris\" }"
}
] |
Binary Classification with Logistic Regression | by Dirk Hornung | Towards Data Science
|
In performance marketing, an important Key Performance Indicator (KPI) is given by the Click Through Rate (CTR). The CTR is the ratio of users who click on a specific link to the number of total users who view a page, email, or advertisement (ad).
Estimating the CTR is a binary classification problem. When a user views an ad he either clicks (y=1)or does not click (y=0). Having solely two possible results let us use logistic regression as our model. Logistic regression is applied to estimate any number of discrete classes in contrary to linear regression, which is used to infer continuous variables. I have given a simple visualization, which gives the right model to three of the major Data Science problems:
In this story, I want to guide you first through the technical details of logistic regression before applying everything learned to a “Click-Through Rate Prediction” challenge of Kaggle1.
Logistic regression is characterized by a logistic function to model the conditional probability of the label Y variables X
In our case Y takes the state clicked or not clicked and X will be an observable of features we want to select (e.g. device type).
We will work with m observations, each containing n features. For each of them, we will have m row vectors xi of dimension n+1. Our labels Y can only be zero or one. The parameters will be given in a column vector Θ of dimension n+1.
The conditional probability of a user who clicks given an observation X can then be modeled as the sigmoid function.
The core of logistic regression is the sigmoid function. The sigmoid function maps a continuous variable to a closed set [0, 1], which then can be interpreted as a probability. Every data point on the right-hand side gets interpreted as y=1 and every data point on the left-hand side gets inferred as y=0.
The sigmoid function appears naturally when deriving the conditional probability. We can express P(Y|X) with Bayes’ theorem
From a Bayesian interpretation we have
P(Y|X) as the posterior,
P(Y) as the prior,
and P(X) as a normalization factor.
We will fit the posterior and the prior to our data and have to get rid of the unknown probability P(X). This can be done by using the complement conditional probability.
When dividing the posterior by the complement conditional probability and taking the logarithm we get the log-odds (logit)
Here we assumed that the logit is a linear function in X! Now we just have to undo the logarithm and solve for the posterior to derive the sigmoid function
So far we have modeled the posterior with a set of parameters Θ. How do we determine the best choice of Θ? The conditional probability of a user who clicked is equal to the sigmoid function. The sum over the probability of all cases has to add up to one. As we do have solely two cases we can find an elegant way to express both probabilities within a single expression:
The right-hand side is referred to as the probability mass function (PMF) of the Bernoulli distribution. The Bernoulli distribution describes a random variable that can take one of two outcomes like our labels clicked or not clicked. Now to determine our parameters Θ we need to maximize the probability of reproducing the distribution of our population, while only be given a sample. This method is called maximum likelihood estimation (MLE). We principally join all the probabilities of every single event in our sample. This joint probability is called the likelihood, which has much in common with a probability but is focused on the parameters
We could maximize the above function, but for convenience (to obtain prettier derivatives) we apply the logarithm to the likelihood. We can do so as the logarithm is a monotonically increasing and thus conserving the position of the maximum. By applying the logarithm the product turns into a sum
To maximize the log-likelihood we can use calculus. The derivative of an extreme point has to be equal to zero
In the last result, we have used the derivative with respect to Θ of the sigmoid function. The derivation is as follows
To perform MLE we have to find the root of the first derivative of the log-likelihood. We can use the Newton-Raphson3 root-finding algorithm for this task. Newton-Raphson is the standard method to maximize the log-likelihood. It needs the second derivative to be calculated. In our case, we can analytically determine it. In other cases, where the second derivative is computationally expensive, we could use gradient descent (ascent) for the optimization. The second derivative is given by
and the Newton-Raphson method then tells us how to update the parameters for each iteration.
In the second part of this story, we want to code our own logistic regression implementation. The Jupyter notebook I build has been published as Gist. We will work with data from the “Click-Through Rate Prediction” Kaggle competition1. After downloading the data we unpack it and prepare a sample of 10000 rows before training on the complete set.
unzip avazu-ctr-prediction.zipgunzip train.gzhead -n10000 train > train_sample.csv
We then load the CSV into a panda data frame and split it into a training and a test set
df = pd.read_csv('train_sample.csv')msk = np.random.rand(len(df)) < 0.8train = df[msk]test = df[~msk]
Now you should focus on feature exploration, but to keep things simple I selected the columns device_type, C1, C15 and C16 as feature columns. I then can prepare my feature matrix X and use the click column as label
m = len(train)X_train = np.ones((m, 5))X_train[:,1] = train.device_type.to_numpy()X_train[:,2] = train.C1.to_numpy()X_train[:,3] = train.C15.to_numpy()X_train[:,4] = train.C16.to_numpy()y_train = train.click.to_numpy()
For our algorithm to work we need the previously derived first and second derivative of the log-likelihood, which can be coded as follows
def DLogLikelihood(X, y, theta): res = np.zeros(theta.shape[0]) for i in range(0, X.shape[0]): x_i = X[i] y_i = y[i] res += x_i * (y_i - sigmoid(np.dot(theta, x_i)) ) return resdef DDLogLikelihood(X, theta): res = np.zeros((theta.shape[0], theta.shape[0])) for i in range(0, X.shape[0]): x_i = X[i] sigma = sigmoid(np.dot(theta, x_i)) res += np.outer(x_i, x_i) * sigma * ( 1 - sigma ) return -res
The iterative Netwon-Raphons steps and our logistic regression algorithm are then
def NewtonRaphsonTheta(X, y, theta): return theta - np.dot( np.linalg.inv(DDLogLikelihood(X, theta)), DLogLikelihood(X, y, theta))def logisticRegression(X, y, epochs=100): theta = np.zeros(X.shape[1]) for i in range(epochs): theta = NewtonRaphsonTheta(X, y, theta) return theta
By calling logisticRegression(X, y) we will iteratively calculate the parameters Θ, which then can be used to make a prediction of the click probability of a user
def predict(X, theta): res = np.zeros(X.shape[0]) for i in range(len(res)): x = X[i] res[i] = sigmoid(np.dot(theta, x)) return res
For a test run, we get the following probabilities
theta = logisticRegression(X_train, y_train, epochs=100)y_pred = predict(X_test, theta)print(y_pred)[0.18827126 0.16229901 ... 0.16229901 0.16229901 0.16229901]
To evaluate the model I compared predictions from the test set to their actual value, which showed that the model is rather poor. To improve we could spend more time on the feature selection and train on more data, while constantly measure the model performance with evaluation metrics like the logarithmic loss or the ROC curve.
Logistic regression is used in multi-classification problems
Binary logistic regression is used if we have only two classes
P(Y|X) is modeled by the sigmoid function, which maps from (-∞, ∞) to (0, 1)
We assumed that the logit can be modeled as a linear function
To estimate the parameters Θ we maximize the log-likelihood
The Bernoulli distribution is a discrete distribution having two possible outcomes, which is used in binary classification
We use Newton-Raphson as a root finder because we can easily compute the second derivative of the log-likelihood
[1]: Kaggle, Click-Through Rate Prediction https://www.kaggle.com/c/avazu-ctr-prediction
[2]: The Elements of Statistical Learning, T. Hastie, R. Tibshirani, J. Friedman https://web.stanford.edu/~hastie/ElemStatLearn/
[3]: Newton-Raphson Method https://en.wikipedia.org/wiki/Newton%27s_method
|
[
{
"code": null,
"e": 420,
"s": 172,
"text": "In performance marketing, an important Key Performance Indicator (KPI) is given by the Click Through Rate (CTR). The CTR is the ratio of users who click on a specific link to the number of total users who view a page, email, or advertisement (ad)."
},
{
"code": null,
"e": 889,
"s": 420,
"text": "Estimating the CTR is a binary classification problem. When a user views an ad he either clicks (y=1)or does not click (y=0). Having solely two possible results let us use logistic regression as our model. Logistic regression is applied to estimate any number of discrete classes in contrary to linear regression, which is used to infer continuous variables. I have given a simple visualization, which gives the right model to three of the major Data Science problems:"
},
{
"code": null,
"e": 1077,
"s": 889,
"text": "In this story, I want to guide you first through the technical details of logistic regression before applying everything learned to a “Click-Through Rate Prediction” challenge of Kaggle1."
},
{
"code": null,
"e": 1201,
"s": 1077,
"text": "Logistic regression is characterized by a logistic function to model the conditional probability of the label Y variables X"
},
{
"code": null,
"e": 1332,
"s": 1201,
"text": "In our case Y takes the state clicked or not clicked and X will be an observable of features we want to select (e.g. device type)."
},
{
"code": null,
"e": 1566,
"s": 1332,
"text": "We will work with m observations, each containing n features. For each of them, we will have m row vectors xi of dimension n+1. Our labels Y can only be zero or one. The parameters will be given in a column vector Θ of dimension n+1."
},
{
"code": null,
"e": 1683,
"s": 1566,
"text": "The conditional probability of a user who clicks given an observation X can then be modeled as the sigmoid function."
},
{
"code": null,
"e": 1989,
"s": 1683,
"text": "The core of logistic regression is the sigmoid function. The sigmoid function maps a continuous variable to a closed set [0, 1], which then can be interpreted as a probability. Every data point on the right-hand side gets interpreted as y=1 and every data point on the left-hand side gets inferred as y=0."
},
{
"code": null,
"e": 2113,
"s": 1989,
"text": "The sigmoid function appears naturally when deriving the conditional probability. We can express P(Y|X) with Bayes’ theorem"
},
{
"code": null,
"e": 2152,
"s": 2113,
"text": "From a Bayesian interpretation we have"
},
{
"code": null,
"e": 2177,
"s": 2152,
"text": "P(Y|X) as the posterior,"
},
{
"code": null,
"e": 2196,
"s": 2177,
"text": "P(Y) as the prior,"
},
{
"code": null,
"e": 2232,
"s": 2196,
"text": "and P(X) as a normalization factor."
},
{
"code": null,
"e": 2403,
"s": 2232,
"text": "We will fit the posterior and the prior to our data and have to get rid of the unknown probability P(X). This can be done by using the complement conditional probability."
},
{
"code": null,
"e": 2526,
"s": 2403,
"text": "When dividing the posterior by the complement conditional probability and taking the logarithm we get the log-odds (logit)"
},
{
"code": null,
"e": 2682,
"s": 2526,
"text": "Here we assumed that the logit is a linear function in X! Now we just have to undo the logarithm and solve for the posterior to derive the sigmoid function"
},
{
"code": null,
"e": 3053,
"s": 2682,
"text": "So far we have modeled the posterior with a set of parameters Θ. How do we determine the best choice of Θ? The conditional probability of a user who clicked is equal to the sigmoid function. The sum over the probability of all cases has to add up to one. As we do have solely two cases we can find an elegant way to express both probabilities within a single expression:"
},
{
"code": null,
"e": 3702,
"s": 3053,
"text": "The right-hand side is referred to as the probability mass function (PMF) of the Bernoulli distribution. The Bernoulli distribution describes a random variable that can take one of two outcomes like our labels clicked or not clicked. Now to determine our parameters Θ we need to maximize the probability of reproducing the distribution of our population, while only be given a sample. This method is called maximum likelihood estimation (MLE). We principally join all the probabilities of every single event in our sample. This joint probability is called the likelihood, which has much in common with a probability but is focused on the parameters"
},
{
"code": null,
"e": 3999,
"s": 3702,
"text": "We could maximize the above function, but for convenience (to obtain prettier derivatives) we apply the logarithm to the likelihood. We can do so as the logarithm is a monotonically increasing and thus conserving the position of the maximum. By applying the logarithm the product turns into a sum"
},
{
"code": null,
"e": 4110,
"s": 3999,
"text": "To maximize the log-likelihood we can use calculus. The derivative of an extreme point has to be equal to zero"
},
{
"code": null,
"e": 4230,
"s": 4110,
"text": "In the last result, we have used the derivative with respect to Θ of the sigmoid function. The derivation is as follows"
},
{
"code": null,
"e": 4721,
"s": 4230,
"text": "To perform MLE we have to find the root of the first derivative of the log-likelihood. We can use the Newton-Raphson3 root-finding algorithm for this task. Newton-Raphson is the standard method to maximize the log-likelihood. It needs the second derivative to be calculated. In our case, we can analytically determine it. In other cases, where the second derivative is computationally expensive, we could use gradient descent (ascent) for the optimization. The second derivative is given by"
},
{
"code": null,
"e": 4814,
"s": 4721,
"text": "and the Newton-Raphson method then tells us how to update the parameters for each iteration."
},
{
"code": null,
"e": 5162,
"s": 4814,
"text": "In the second part of this story, we want to code our own logistic regression implementation. The Jupyter notebook I build has been published as Gist. We will work with data from the “Click-Through Rate Prediction” Kaggle competition1. After downloading the data we unpack it and prepare a sample of 10000 rows before training on the complete set."
},
{
"code": null,
"e": 5245,
"s": 5162,
"text": "unzip avazu-ctr-prediction.zipgunzip train.gzhead -n10000 train > train_sample.csv"
},
{
"code": null,
"e": 5334,
"s": 5245,
"text": "We then load the CSV into a panda data frame and split it into a training and a test set"
},
{
"code": null,
"e": 5436,
"s": 5334,
"text": "df = pd.read_csv('train_sample.csv')msk = np.random.rand(len(df)) < 0.8train = df[msk]test = df[~msk]"
},
{
"code": null,
"e": 5652,
"s": 5436,
"text": "Now you should focus on feature exploration, but to keep things simple I selected the columns device_type, C1, C15 and C16 as feature columns. I then can prepare my feature matrix X and use the click column as label"
},
{
"code": null,
"e": 5871,
"s": 5652,
"text": "m = len(train)X_train = np.ones((m, 5))X_train[:,1] = train.device_type.to_numpy()X_train[:,2] = train.C1.to_numpy()X_train[:,3] = train.C15.to_numpy()X_train[:,4] = train.C16.to_numpy()y_train = train.click.to_numpy()"
},
{
"code": null,
"e": 6009,
"s": 5871,
"text": "For our algorithm to work we need the previously derived first and second derivative of the log-likelihood, which can be coded as follows"
},
{
"code": null,
"e": 6467,
"s": 6009,
"text": "def DLogLikelihood(X, y, theta): res = np.zeros(theta.shape[0]) for i in range(0, X.shape[0]): x_i = X[i] y_i = y[i] res += x_i * (y_i - sigmoid(np.dot(theta, x_i)) ) return resdef DDLogLikelihood(X, theta): res = np.zeros((theta.shape[0], theta.shape[0])) for i in range(0, X.shape[0]): x_i = X[i] sigma = sigmoid(np.dot(theta, x_i)) res += np.outer(x_i, x_i) * sigma * ( 1 - sigma ) return -res"
},
{
"code": null,
"e": 6549,
"s": 6467,
"text": "The iterative Netwon-Raphons steps and our logistic regression algorithm are then"
},
{
"code": null,
"e": 6860,
"s": 6549,
"text": "def NewtonRaphsonTheta(X, y, theta): return theta - np.dot( np.linalg.inv(DDLogLikelihood(X, theta)), DLogLikelihood(X, y, theta))def logisticRegression(X, y, epochs=100): theta = np.zeros(X.shape[1]) for i in range(epochs): theta = NewtonRaphsonTheta(X, y, theta) return theta"
},
{
"code": null,
"e": 7023,
"s": 6860,
"text": "By calling logisticRegression(X, y) we will iteratively calculate the parameters Θ, which then can be used to make a prediction of the click probability of a user"
},
{
"code": null,
"e": 7177,
"s": 7023,
"text": "def predict(X, theta): res = np.zeros(X.shape[0]) for i in range(len(res)): x = X[i] res[i] = sigmoid(np.dot(theta, x)) return res"
},
{
"code": null,
"e": 7228,
"s": 7177,
"text": "For a test run, we get the following probabilities"
},
{
"code": null,
"e": 7389,
"s": 7228,
"text": "theta = logisticRegression(X_train, y_train, epochs=100)y_pred = predict(X_test, theta)print(y_pred)[0.18827126 0.16229901 ... 0.16229901 0.16229901 0.16229901]"
},
{
"code": null,
"e": 7719,
"s": 7389,
"text": "To evaluate the model I compared predictions from the test set to their actual value, which showed that the model is rather poor. To improve we could spend more time on the feature selection and train on more data, while constantly measure the model performance with evaluation metrics like the logarithmic loss or the ROC curve."
},
{
"code": null,
"e": 7780,
"s": 7719,
"text": "Logistic regression is used in multi-classification problems"
},
{
"code": null,
"e": 7843,
"s": 7780,
"text": "Binary logistic regression is used if we have only two classes"
},
{
"code": null,
"e": 7920,
"s": 7843,
"text": "P(Y|X) is modeled by the sigmoid function, which maps from (-∞, ∞) to (0, 1)"
},
{
"code": null,
"e": 7982,
"s": 7920,
"text": "We assumed that the logit can be modeled as a linear function"
},
{
"code": null,
"e": 8042,
"s": 7982,
"text": "To estimate the parameters Θ we maximize the log-likelihood"
},
{
"code": null,
"e": 8165,
"s": 8042,
"text": "The Bernoulli distribution is a discrete distribution having two possible outcomes, which is used in binary classification"
},
{
"code": null,
"e": 8278,
"s": 8165,
"text": "We use Newton-Raphson as a root finder because we can easily compute the second derivative of the log-likelihood"
},
{
"code": null,
"e": 8367,
"s": 8278,
"text": "[1]: Kaggle, Click-Through Rate Prediction https://www.kaggle.com/c/avazu-ctr-prediction"
},
{
"code": null,
"e": 8496,
"s": 8367,
"text": "[2]: The Elements of Statistical Learning, T. Hastie, R. Tibshirani, J. Friedman https://web.stanford.edu/~hastie/ElemStatLearn/"
}
] |
React-Bootstrap Button Component
|
17 Jun, 2021
Introduction: React-Bootstrap is a front-end framework that was designed keeping react in mind. Bootstrap was re-built and revamped for React, hence it is known as React-Bootstrap. Buttons are used to perform actions on the website and they play a crucial role in the front-end part.
Buttons props:
variant: It is used to add different themes and visual styles for badges.
bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS.
disabled: It is used to disable buttons.
active: It is used to manually set the button inactive state.
size: It is used to specify the size of the button.
as: Used as a custom element for the descriptive purpose for this composite.
type: Used to define the functionality of the button.
name: It is used to name each button.
value: It is used to give specific values to each button.
onChange: The callback function is fired when a button is pressed depending on the type of button type.
ToggleButtonGroup props:
name : It is used to name each button.
onChange: The callback function is fired when a button is pressed depending on the type of button type.
size: It is used to specify the size of the button.
type: Used to define the functionality of the button like radio or checkbox.
value: It is used to give specific values to each button.
vertical: It is used to style the buttons in a vertical way.
ToggleButton props:
disabled: It is used to disable both label and input.
inputRef: A ref is added to <input> element.
type: Used to define the functionality of the button like radio or checkbox.
checked: It determines the checked state of the input element which is managed by <ToggleButtonGroup>.
onChange: The callback function is fired when a button is pressed depending on the type of button type.
name: It is used to determine the name of each button.
value: It is used to give specific values to each button which should be unique for its siblings.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command.npx create-react-app foldername
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Step 3: After creating the ReactJS application, Install the required modules using the following command.npm install react-bootstrap bootstrap
Step 3: After creating the ReactJS application, Install the required modules using the following command.
npm install react-bootstrap bootstrap
Step 4: Add the below line in index.js file.import 'bootstrap/dist/css/bootstrap.css';
Step 4: Add the below line in index.js file.
import 'bootstrap/dist/css/bootstrap.css';
Project Structure: It will look like the following.
Approach:
First, install the react-bootstrap using the above-mentioned command.
Now in the file app.js write the code following the below instructions.
After completing the installation, Import ‘ButtonGroup’ from ‘react-bootstrap/Button-Group’ in that file.
ButtonGroup is used to group multiple buttons and in order to change the colors of the buttons we can use the “variant” property. Like primary, secondary, and danger.
Example: Now use the below code snippet in that file and export that component so that we can import in index.js for rendering.
App.js
import React from "react";import ButtonGroup from "react-bootstrap/ButtonGroup";import Button from "react-bootstrap/Button"; export default function ButtonGrouping() { return ( <> <h3>Normal Buttons</h3> <ButtonGroup aria-label="Basic example"> <Button variant="primary"> Primary variant Button </Button> <Button variant="secondary"> Secondary variant Button </Button> <Button variant="danger"> Danger variant Button </Button> <Button variant="warning"> Warning variant Button </Button> <Button variant="info"> Info variant Button </Button> <Button variant="success"> Success variant Button </Button> <Button variant="light"> Light variant Button </Button> <Button variant="dark"> Dark variant Button </Button> </ButtonGroup> <br /> <br /> <br /> <h3>Outline Variant Buttons</h3> <ButtonGroup> <Button variant="outline-primary"> Primary variant outline Button </Button> <Button variant="outline-secondary"> Secondary outline Button </Button> <Button variant="outline-success"> Success outline Button </Button> <Button variant="outline-warning"> Warning outline Button </Button> <Button variant="outline-danger"> Danger outline Button </Button> <Button variant="outline-info"> Info outline Button </Button> <Button variant="outline-dark"> Dark outline Button </Button> </ButtonGroup> <br /> <br /> <br /> <h3>Size Variant Buttons</h3> <ButtonGroup> <Button variant="primary" size="lg"> Large variant primary Button </Button> <Button variant="secondary" size="sm"> Small variant secondary Button </Button> </ButtonGroup> <br /> <br /> <h3>Disabled Variant Buttons</h3> <ButtonGroup> <Button variant="primary" size="lg" disabled> Disabled Large variant primary Button </Button> <Button variant="secondary" size="sm" disabled> Disabled Small variant secondary Button </Button> </ButtonGroup> </> );}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.
Reference: https://react-bootstrap.netlify.app/components/buttons/#buttons
Picked
React-Bootstrap
ReactJS
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": "\n17 Jun, 2021"
},
{
"code": null,
"e": 312,
"s": 28,
"text": "Introduction: React-Bootstrap is a front-end framework that was designed keeping react in mind. Bootstrap was re-built and revamped for React, hence it is known as React-Bootstrap. Buttons are used to perform actions on the website and they play a crucial role in the front-end part."
},
{
"code": null,
"e": 327,
"s": 312,
"text": "Buttons props:"
},
{
"code": null,
"e": 401,
"s": 327,
"text": "variant: It is used to add different themes and visual styles for badges."
},
{
"code": null,
"e": 485,
"s": 401,
"text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS."
},
{
"code": null,
"e": 526,
"s": 485,
"text": "disabled: It is used to disable buttons."
},
{
"code": null,
"e": 588,
"s": 526,
"text": "active: It is used to manually set the button inactive state."
},
{
"code": null,
"e": 640,
"s": 588,
"text": "size: It is used to specify the size of the button."
},
{
"code": null,
"e": 717,
"s": 640,
"text": "as: Used as a custom element for the descriptive purpose for this composite."
},
{
"code": null,
"e": 771,
"s": 717,
"text": "type: Used to define the functionality of the button."
},
{
"code": null,
"e": 809,
"s": 771,
"text": "name: It is used to name each button."
},
{
"code": null,
"e": 867,
"s": 809,
"text": "value: It is used to give specific values to each button."
},
{
"code": null,
"e": 972,
"s": 867,
"text": "onChange: The callback function is fired when a button is pressed depending on the type of button type. "
},
{
"code": null,
"e": 997,
"s": 972,
"text": "ToggleButtonGroup props:"
},
{
"code": null,
"e": 1037,
"s": 997,
"text": "name : It is used to name each button."
},
{
"code": null,
"e": 1142,
"s": 1037,
"text": "onChange: The callback function is fired when a button is pressed depending on the type of button type. "
},
{
"code": null,
"e": 1194,
"s": 1142,
"text": "size: It is used to specify the size of the button."
},
{
"code": null,
"e": 1271,
"s": 1194,
"text": "type: Used to define the functionality of the button like radio or checkbox."
},
{
"code": null,
"e": 1329,
"s": 1271,
"text": "value: It is used to give specific values to each button."
},
{
"code": null,
"e": 1390,
"s": 1329,
"text": "vertical: It is used to style the buttons in a vertical way."
},
{
"code": null,
"e": 1410,
"s": 1390,
"text": "ToggleButton props:"
},
{
"code": null,
"e": 1464,
"s": 1410,
"text": "disabled: It is used to disable both label and input."
},
{
"code": null,
"e": 1509,
"s": 1464,
"text": "inputRef: A ref is added to <input> element."
},
{
"code": null,
"e": 1586,
"s": 1509,
"text": "type: Used to define the functionality of the button like radio or checkbox."
},
{
"code": null,
"e": 1689,
"s": 1586,
"text": "checked: It determines the checked state of the input element which is managed by <ToggleButtonGroup>."
},
{
"code": null,
"e": 1794,
"s": 1689,
"text": "onChange: The callback function is fired when a button is pressed depending on the type of button type. "
},
{
"code": null,
"e": 1849,
"s": 1794,
"text": "name: It is used to determine the name of each button."
},
{
"code": null,
"e": 1947,
"s": 1849,
"text": "value: It is used to give specific values to each button which should be unique for its siblings."
},
{
"code": null,
"e": 1997,
"s": 1947,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 2092,
"s": 1997,
"text": "Step 1: Create a React application using the following command.npx create-react-app foldername"
},
{
"code": null,
"e": 2156,
"s": 2092,
"text": "Step 1: Create a React application using the following command."
},
{
"code": null,
"e": 2188,
"s": 2156,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 2301,
"s": 2188,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername"
},
{
"code": null,
"e": 2401,
"s": 2301,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command."
},
{
"code": null,
"e": 2415,
"s": 2401,
"text": "cd foldername"
},
{
"code": null,
"e": 2558,
"s": 2415,
"text": "Step 3: After creating the ReactJS application, Install the required modules using the following command.npm install react-bootstrap bootstrap"
},
{
"code": null,
"e": 2664,
"s": 2558,
"text": "Step 3: After creating the ReactJS application, Install the required modules using the following command."
},
{
"code": null,
"e": 2702,
"s": 2664,
"text": "npm install react-bootstrap bootstrap"
},
{
"code": null,
"e": 2789,
"s": 2702,
"text": "Step 4: Add the below line in index.js file.import 'bootstrap/dist/css/bootstrap.css';"
},
{
"code": null,
"e": 2834,
"s": 2789,
"text": "Step 4: Add the below line in index.js file."
},
{
"code": null,
"e": 2877,
"s": 2834,
"text": "import 'bootstrap/dist/css/bootstrap.css';"
},
{
"code": null,
"e": 2929,
"s": 2877,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 2939,
"s": 2929,
"text": "Approach:"
},
{
"code": null,
"e": 3009,
"s": 2939,
"text": "First, install the react-bootstrap using the above-mentioned command."
},
{
"code": null,
"e": 3081,
"s": 3009,
"text": "Now in the file app.js write the code following the below instructions."
},
{
"code": null,
"e": 3187,
"s": 3081,
"text": "After completing the installation, Import ‘ButtonGroup’ from ‘react-bootstrap/Button-Group’ in that file."
},
{
"code": null,
"e": 3354,
"s": 3187,
"text": "ButtonGroup is used to group multiple buttons and in order to change the colors of the buttons we can use the “variant” property. Like primary, secondary, and danger."
},
{
"code": null,
"e": 3482,
"s": 3354,
"text": "Example: Now use the below code snippet in that file and export that component so that we can import in index.js for rendering."
},
{
"code": null,
"e": 3489,
"s": 3482,
"text": "App.js"
},
{
"code": "import React from \"react\";import ButtonGroup from \"react-bootstrap/ButtonGroup\";import Button from \"react-bootstrap/Button\"; export default function ButtonGrouping() { return ( <> <h3>Normal Buttons</h3> <ButtonGroup aria-label=\"Basic example\"> <Button variant=\"primary\"> Primary variant Button </Button> <Button variant=\"secondary\"> Secondary variant Button </Button> <Button variant=\"danger\"> Danger variant Button </Button> <Button variant=\"warning\"> Warning variant Button </Button> <Button variant=\"info\"> Info variant Button </Button> <Button variant=\"success\"> Success variant Button </Button> <Button variant=\"light\"> Light variant Button </Button> <Button variant=\"dark\"> Dark variant Button </Button> </ButtonGroup> <br /> <br /> <br /> <h3>Outline Variant Buttons</h3> <ButtonGroup> <Button variant=\"outline-primary\"> Primary variant outline Button </Button> <Button variant=\"outline-secondary\"> Secondary outline Button </Button> <Button variant=\"outline-success\"> Success outline Button </Button> <Button variant=\"outline-warning\"> Warning outline Button </Button> <Button variant=\"outline-danger\"> Danger outline Button </Button> <Button variant=\"outline-info\"> Info outline Button </Button> <Button variant=\"outline-dark\"> Dark outline Button </Button> </ButtonGroup> <br /> <br /> <br /> <h3>Size Variant Buttons</h3> <ButtonGroup> <Button variant=\"primary\" size=\"lg\"> Large variant primary Button </Button> <Button variant=\"secondary\" size=\"sm\"> Small variant secondary Button </Button> </ButtonGroup> <br /> <br /> <h3>Disabled Variant Buttons</h3> <ButtonGroup> <Button variant=\"primary\" size=\"lg\" disabled> Disabled Large variant primary Button </Button> <Button variant=\"secondary\" size=\"sm\" disabled> Disabled Small variant secondary Button </Button> </ButtonGroup> </> );}",
"e": 5877,
"s": 3489,
"text": null
},
{
"code": null,
"e": 5990,
"s": 5877,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 6000,
"s": 5990,
"text": "npm start"
},
{
"code": null,
"e": 6099,
"s": 6000,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output."
},
{
"code": null,
"e": 6174,
"s": 6099,
"text": "Reference: https://react-bootstrap.netlify.app/components/buttons/#buttons"
},
{
"code": null,
"e": 6181,
"s": 6174,
"text": "Picked"
},
{
"code": null,
"e": 6197,
"s": 6181,
"text": "React-Bootstrap"
},
{
"code": null,
"e": 6205,
"s": 6197,
"text": "ReactJS"
},
{
"code": null,
"e": 6222,
"s": 6205,
"text": "Web Technologies"
}
] |
HTML | size Attribute
|
09 Dec, 2021
The size attribute in HTML is used to specify the initial width for the input field and a number of visible rows for the select element.The size attribute can be used with the following elements:
<input>
<hr>
<select>
<font>
Attribute Values: It contains a numeric value that specify the number of visible options in the drop-down list. It has a default value which is 4.
<input> size Attribute: This attribute specifies the visible width of input element.Syntax:
<input size = "value">
Example:
html
<!DOCTYPE html><html> <head> <title>HTML size Attribute</title> <style> h1, h2 { text-align: center; } </style></head> <body> <center> <h1 style="color: green;"> GeeksforGeeks </h1> <h2> HTML size Attribute </h2> <!-- It is the default size --> Name: <input type="text"> <br> <br> <!-- It's user specified size with value 50 --> Email-id: <input type="text" size="50"> </center></body> </html>
Output:
<select> size Attribute: This attribute specifies the number of visible options in a drop-down list. Syntax:
<select size = "value"> option values...</select>
Example:
html
<!DOCTYPE html><html> <head> <title>HTML size Attribute</title> <style> h1, h2 { text-align: center; } </style> </head> <body> <h1 style = "color: green;"> GeeksforGeeks </h1> <h2> HTML size Attribute </h2> <p>Sorting Algorithms</p> <select size="3"> <option value="merge"> merge sort </option> <option value="bubble"> bubble sort </option> <option value="selection"> selection sort</option> <option value="quick">quick sort</option> <option value="insertion">insertion sort</option> </select> </body></html>
Output:
<hr> size Attribute: This attribute specifies the height of the horizontal line. Syntax:
<hr size = "value">
Example:
html
<!DOCTYPE html><html> <head> <title>HTML size Attribute</title> <style> h1, h2 { text-align: center; } hr { background: green; } </style> </head> <body> <h1 style = "color: green;"> GeeksforGeeks </h1> <h2> HTML size Attribute </h2> <hr size = "26"> </body></html>
Output:
Supported Browsers: The browsers supported by size attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
nidhi_biet
ManasChhabra2
HTML-Attributes
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n09 Dec, 2021"
},
{
"code": null,
"e": 251,
"s": 53,
"text": "The size attribute in HTML is used to specify the initial width for the input field and a number of visible rows for the select element.The size attribute can be used with the following elements: "
},
{
"code": null,
"e": 259,
"s": 251,
"text": "<input>"
},
{
"code": null,
"e": 264,
"s": 259,
"text": "<hr>"
},
{
"code": null,
"e": 273,
"s": 264,
"text": "<select>"
},
{
"code": null,
"e": 281,
"s": 273,
"text": "<font> "
},
{
"code": null,
"e": 428,
"s": 281,
"text": "Attribute Values: It contains a numeric value that specify the number of visible options in the drop-down list. It has a default value which is 4."
},
{
"code": null,
"e": 522,
"s": 428,
"text": "<input> size Attribute: This attribute specifies the visible width of input element.Syntax: "
},
{
"code": null,
"e": 545,
"s": 522,
"text": "<input size = \"value\">"
},
{
"code": null,
"e": 556,
"s": 545,
"text": "Example: "
},
{
"code": null,
"e": 561,
"s": 556,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>HTML size Attribute</title> <style> h1, h2 { text-align: center; } </style></head> <body> <center> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h2> HTML size Attribute </h2> <!-- It is the default size --> Name: <input type=\"text\"> <br> <br> <!-- It's user specified size with value 50 --> Email-id: <input type=\"text\" size=\"50\"> </center></body> </html>",
"e": 1110,
"s": 561,
"text": null
},
{
"code": null,
"e": 1120,
"s": 1110,
"text": "Output: "
},
{
"code": null,
"e": 1231,
"s": 1120,
"text": "<select> size Attribute: This attribute specifies the number of visible options in a drop-down list. Syntax: "
},
{
"code": null,
"e": 1281,
"s": 1231,
"text": "<select size = \"value\"> option values...</select>"
},
{
"code": null,
"e": 1292,
"s": 1281,
"text": "Example: "
},
{
"code": null,
"e": 1297,
"s": 1292,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>HTML size Attribute</title> <style> h1, h2 { text-align: center; } </style> </head> <body> <h1 style = \"color: green;\"> GeeksforGeeks </h1> <h2> HTML size Attribute </h2> <p>Sorting Algorithms</p> <select size=\"3\"> <option value=\"merge\"> merge sort </option> <option value=\"bubble\"> bubble sort </option> <option value=\"selection\"> selection sort</option> <option value=\"quick\">quick sort</option> <option value=\"insertion\">insertion sort</option> </select> </body></html>",
"e": 2078,
"s": 1297,
"text": null
},
{
"code": null,
"e": 2088,
"s": 2078,
"text": "Output: "
},
{
"code": null,
"e": 2179,
"s": 2088,
"text": "<hr> size Attribute: This attribute specifies the height of the horizontal line. Syntax: "
},
{
"code": null,
"e": 2199,
"s": 2179,
"text": "<hr size = \"value\">"
},
{
"code": null,
"e": 2210,
"s": 2199,
"text": "Example: "
},
{
"code": null,
"e": 2215,
"s": 2210,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>HTML size Attribute</title> <style> h1, h2 { text-align: center; } hr { background: green; } </style> </head> <body> <h1 style = \"color: green;\"> GeeksforGeeks </h1> <h2> HTML size Attribute </h2> <hr size = \"26\"> </body></html>",
"e": 2653,
"s": 2215,
"text": null
},
{
"code": null,
"e": 2663,
"s": 2653,
"text": "Output: "
},
{
"code": null,
"e": 2744,
"s": 2663,
"text": "Supported Browsers: The browsers supported by size attribute are listed below: "
},
{
"code": null,
"e": 2758,
"s": 2744,
"text": "Google Chrome"
},
{
"code": null,
"e": 2776,
"s": 2758,
"text": "Internet Explorer"
},
{
"code": null,
"e": 2784,
"s": 2776,
"text": "Firefox"
},
{
"code": null,
"e": 2790,
"s": 2784,
"text": "Opera"
},
{
"code": null,
"e": 2797,
"s": 2790,
"text": "Safari"
},
{
"code": null,
"e": 2810,
"s": 2799,
"text": "nidhi_biet"
},
{
"code": null,
"e": 2824,
"s": 2810,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 2840,
"s": 2824,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 2844,
"s": 2840,
"text": "CSS"
},
{
"code": null,
"e": 2849,
"s": 2844,
"text": "HTML"
},
{
"code": null,
"e": 2866,
"s": 2849,
"text": "Web Technologies"
},
{
"code": null,
"e": 2871,
"s": 2866,
"text": "HTML"
}
] |
Python | Remove square brackets from list
|
05 Sep, 2019
Sometimes, while working with displaying the contents of list, the square brackets, both opening and closing are undesired. For this when we need to print whole list without accessing the elements for loops, we require a method to perform this. Let’s discuss a shorthand by which this task can be performed.
Method : Using str() + list slicingThe shorthand that can be applied, without having need to access each element of list is to convert the entire list to string and then strip the initial and last character of list using list slicing. This won’t work if list contains a string. In that case, each element can be joined using join(), as discussed in many other articles.
# Python3 code to demonstrate working of# Remove square brackets from list# using str() + list slicing # initialize listtest_list = [5, 6, 8, 9, 10, 21] # printing original listprint("The original list is : " + str(test_list)) # Remove square brackets from list# using str() + list slicingres = str(test_list)[1:-1] # printing resultprint("List after removing square brackets : " + res)
The original list is : [5, 6, 8, 9, 10, 21]
List after removing square brackets : 5, 6, 8, 9, 10, 21
Python list-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n05 Sep, 2019"
},
{
"code": null,
"e": 361,
"s": 53,
"text": "Sometimes, while working with displaying the contents of list, the square brackets, both opening and closing are undesired. For this when we need to print whole list without accessing the elements for loops, we require a method to perform this. Let’s discuss a shorthand by which this task can be performed."
},
{
"code": null,
"e": 731,
"s": 361,
"text": "Method : Using str() + list slicingThe shorthand that can be applied, without having need to access each element of list is to convert the entire list to string and then strip the initial and last character of list using list slicing. This won’t work if list contains a string. In that case, each element can be joined using join(), as discussed in many other articles."
},
{
"code": "# Python3 code to demonstrate working of# Remove square brackets from list# using str() + list slicing # initialize listtest_list = [5, 6, 8, 9, 10, 21] # printing original listprint(\"The original list is : \" + str(test_list)) # Remove square brackets from list# using str() + list slicingres = str(test_list)[1:-1] # printing resultprint(\"List after removing square brackets : \" + res)",
"e": 1122,
"s": 731,
"text": null
},
{
"code": null,
"e": 1224,
"s": 1122,
"text": "The original list is : [5, 6, 8, 9, 10, 21]\nList after removing square brackets : 5, 6, 8, 9, 10, 21\n"
},
{
"code": null,
"e": 1245,
"s": 1224,
"text": "Python list-programs"
},
{
"code": null,
"e": 1252,
"s": 1245,
"text": "Python"
}
] |
String rjust() and ljust() in python()
|
08 Jan, 2018
1. String rjust() The string rjust() method returns a new string of given length after substituting a given character in left side of original string.
Syntax:
string.rjust(length, fillchar)
Parameters:
length: length of the modified string. If length is less than or equal to the length of the original string then original string is returned.fillchar: (optional) characters which needs to be padded. If it’s not provided, space is taken as a default argument.
Returns:
Returns a new string of given length after substituting a given character in left side of original string.
Example
# Python program to demonstrate working of # rjust()string = 'geeks'length = 8 # If no fill character is provided, space# is used as fill characterprint(string.rjust(length))
Output:
geeks
Example
# example stringstring = 'geeks'length = 8fillchar = '*' print(string.rjust(length, fillchar))
Output:
***geeks
2. String ljust()The string ljust() method returns a new string of given length after substituting a given character in right side of original string.
Syntax:
string.ljust(length, fillchar)
Parameters:
length: length of the modified string. If length is less than or equal to the length of the original string then original string is returned.fillchar: (optional) characters which needs to be padded. If it’s not provided, space is taken as a default argument.
Returns:
Returns a new string of given length after substituting a given character in right side of original string.
Example 1
# example stringstring = 'geeks'length = 8 # If no fill character is provided, space# is used as fill character.print(string.ljust(length))
Output: (Three spaces are printed after geeks)
geeks
Example 2
# example stringstring = 'geeks'length = 8fillchar = '*' # print left justified stringprint(string.ljust(length, fillchar))
Output:
geeks***
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Jan, 2018"
},
{
"code": null,
"e": 179,
"s": 28,
"text": "1. String rjust() The string rjust() method returns a new string of given length after substituting a given character in left side of original string."
},
{
"code": null,
"e": 187,
"s": 179,
"text": "Syntax:"
},
{
"code": null,
"e": 218,
"s": 187,
"text": "string.rjust(length, fillchar)"
},
{
"code": null,
"e": 230,
"s": 218,
"text": "Parameters:"
},
{
"code": null,
"e": 489,
"s": 230,
"text": "length: length of the modified string. If length is less than or equal to the length of the original string then original string is returned.fillchar: (optional) characters which needs to be padded. If it’s not provided, space is taken as a default argument."
},
{
"code": null,
"e": 498,
"s": 489,
"text": "Returns:"
},
{
"code": null,
"e": 605,
"s": 498,
"text": "Returns a new string of given length after substituting a given character in left side of original string."
},
{
"code": null,
"e": 613,
"s": 605,
"text": "Example"
},
{
"code": "# Python program to demonstrate working of # rjust()string = 'geeks'length = 8 # If no fill character is provided, space# is used as fill characterprint(string.rjust(length))",
"e": 789,
"s": 613,
"text": null
},
{
"code": null,
"e": 797,
"s": 789,
"text": "Output:"
},
{
"code": null,
"e": 806,
"s": 797,
"text": " geeks"
},
{
"code": null,
"e": 814,
"s": 806,
"text": "Example"
},
{
"code": "# example stringstring = 'geeks'length = 8fillchar = '*' print(string.rjust(length, fillchar))",
"e": 910,
"s": 814,
"text": null
},
{
"code": null,
"e": 918,
"s": 910,
"text": "Output:"
},
{
"code": null,
"e": 930,
"s": 918,
"text": "***geeks \n"
},
{
"code": null,
"e": 1083,
"s": 932,
"text": "2. String ljust()The string ljust() method returns a new string of given length after substituting a given character in right side of original string."
},
{
"code": null,
"e": 1091,
"s": 1083,
"text": "Syntax:"
},
{
"code": null,
"e": 1122,
"s": 1091,
"text": "string.ljust(length, fillchar)"
},
{
"code": null,
"e": 1134,
"s": 1122,
"text": "Parameters:"
},
{
"code": null,
"e": 1393,
"s": 1134,
"text": "length: length of the modified string. If length is less than or equal to the length of the original string then original string is returned.fillchar: (optional) characters which needs to be padded. If it’s not provided, space is taken as a default argument."
},
{
"code": null,
"e": 1402,
"s": 1393,
"text": "Returns:"
},
{
"code": null,
"e": 1510,
"s": 1402,
"text": "Returns a new string of given length after substituting a given character in right side of original string."
},
{
"code": null,
"e": 1520,
"s": 1510,
"text": "Example 1"
},
{
"code": "# example stringstring = 'geeks'length = 8 # If no fill character is provided, space# is used as fill character.print(string.ljust(length))",
"e": 1661,
"s": 1520,
"text": null
},
{
"code": null,
"e": 1708,
"s": 1661,
"text": "Output: (Three spaces are printed after geeks)"
},
{
"code": null,
"e": 1718,
"s": 1708,
"text": "geeks \n"
},
{
"code": null,
"e": 1728,
"s": 1718,
"text": "Example 2"
},
{
"code": "# example stringstring = 'geeks'length = 8fillchar = '*' # print left justified stringprint(string.ljust(length, fillchar))",
"e": 1853,
"s": 1728,
"text": null
},
{
"code": null,
"e": 1861,
"s": 1853,
"text": "Output:"
},
{
"code": null,
"e": 1873,
"s": 1861,
"text": "geeks*** \n"
},
{
"code": null,
"e": 1887,
"s": 1873,
"text": "python-string"
},
{
"code": null,
"e": 1894,
"s": 1887,
"text": "Python"
}
] |
How to create a link in JavaScript ?
|
20 Jul, 2021
Given an HTML document and the task is to create a JavaScript link and add it to the document using JavaScript.
Approach:
Create an anchor <a> element.
Create a text node with some text which will display as a link.
Append the text node to the anchor <a> element.
Set the title and href property of the <a> element.
Append <a> element in the body.
Example 1: In this example, the node is created and the attributes are set by the JavaScript methods.
<!DOCTYPE HTML> <html> <head> <title> How to create a link in JavaScript ? </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 19px; font-weight: bold;"> </p> <button onclick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "color: green; font-size: 24px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to generate " + "a link using JavaScript."; function GFG_Fun() { // Create anchor element. var a = document.createElement('a'); // Create the text node for anchor element. var link = document.createTextNode("This is link"); // Append the text node to anchor element. a.appendChild(link); // Set the title. a.title = "This is Link"; // Set the href property. a.href = "https://www.geeksforgeeks.org"; // Append the anchor element to the body. document.body.appendChild(a); } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Example 2: This example is similar to the above but uses prepend() method to add anchor element to the body.
<!DOCTYPE HTML> <html> <head> <title> How to create a link in JavaScript ? </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 19px; font-weight: bold;"> </p> <button onclick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "color: green; font-size: 24px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to generate " + "a link using JavaScript."; function GFG_Fun() { // Create anchor element. var a = document.createElement('a'); // Create the text node for anchor element. var link = document.createTextNode("This is link"); // Append the text node to anchor element. a.appendChild(link); // Set the title. a.title = "This is Link"; // Set the href property. a.href = "https://www.geeksforgeeks.org"; // Append the anchor element to the body. document.body.prepend(a); } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Jul, 2021"
},
{
"code": null,
"e": 140,
"s": 28,
"text": "Given an HTML document and the task is to create a JavaScript link and add it to the document using JavaScript."
},
{
"code": null,
"e": 150,
"s": 140,
"text": "Approach:"
},
{
"code": null,
"e": 180,
"s": 150,
"text": "Create an anchor <a> element."
},
{
"code": null,
"e": 244,
"s": 180,
"text": "Create a text node with some text which will display as a link."
},
{
"code": null,
"e": 292,
"s": 244,
"text": "Append the text node to the anchor <a> element."
},
{
"code": null,
"e": 344,
"s": 292,
"text": "Set the title and href property of the <a> element."
},
{
"code": null,
"e": 376,
"s": 344,
"text": "Append <a> element in the body."
},
{
"code": null,
"e": 478,
"s": 376,
"text": "Example 1: In this example, the node is created and the attributes are set by the JavaScript methods."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> How to create a link in JavaScript ? </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 19px; font-weight: bold;\"> </p> <button onclick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color: green; font-size: 24px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); el_up.innerHTML = \"Click on the button to generate \" + \"a link using JavaScript.\"; function GFG_Fun() { // Create anchor element. var a = document.createElement('a'); // Create the text node for anchor element. var link = document.createTextNode(\"This is link\"); // Append the text node to anchor element. a.appendChild(link); // Set the title. a.title = \"This is Link\"; // Set the href property. a.href = \"https://www.geeksforgeeks.org\"; // Append the anchor element to the body. document.body.appendChild(a); } </script> </body> </html> ",
"e": 2135,
"s": 478,
"text": null
},
{
"code": null,
"e": 2143,
"s": 2135,
"text": "Output:"
},
{
"code": null,
"e": 2174,
"s": 2143,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 2204,
"s": 2174,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 2313,
"s": 2204,
"text": "Example 2: This example is similar to the above but uses prepend() method to add anchor element to the body."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> How to create a link in JavaScript ? </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 19px; font-weight: bold;\"> </p> <button onclick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color: green; font-size: 24px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); el_up.innerHTML = \"Click on the button to generate \" + \"a link using JavaScript.\"; function GFG_Fun() { // Create anchor element. var a = document.createElement('a'); // Create the text node for anchor element. var link = document.createTextNode(\"This is link\"); // Append the text node to anchor element. a.appendChild(link); // Set the title. a.title = \"This is Link\"; // Set the href property. a.href = \"https://www.geeksforgeeks.org\"; // Append the anchor element to the body. document.body.prepend(a); } </script> </body> </html> ",
"e": 3966,
"s": 2313,
"text": null
},
{
"code": null,
"e": 3974,
"s": 3966,
"text": "Output:"
},
{
"code": null,
"e": 4005,
"s": 3974,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 4035,
"s": 4005,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 4254,
"s": 4035,
"text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples."
},
{
"code": null,
"e": 4270,
"s": 4254,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 4281,
"s": 4270,
"text": "JavaScript"
},
{
"code": null,
"e": 4298,
"s": 4281,
"text": "Web Technologies"
},
{
"code": null,
"e": 4325,
"s": 4298,
"text": "Web technologies Questions"
}
] |
Peterson’s Algorithm in Process Synchronization
|
28 Oct, 2019
Prerequisite – synchronization, Critical Section
Problem:The producer consumer problem (or bounded buffer problem) describes two processes, the producer and the consumer, which share a common, fixed-size buffer used as a queue. Producer produce an item and put it into buffer. If buffer is already full then producer will have to wait for an empty block in buffer. Consumer consume an item from buffer. If buffer is already empty then consumer will have to wait for an item in buffer. Implement Peterson’s Algorithm for the two processes using shared memory such that there is mutual exclusion between them. The solution should have free from synchronization problems.
Peterson’s algorithm –
// code for producer (j) // producer j is ready// to produce an itemflag[j] = true; // but consumer (i) can consume an itemturn = i; // if consumer is ready to consume an item// and if its consumer's turnwhile (flag[i] == true && turn == i) { // then producer will wait } // otherwise producer will produce // an item and put it into buffer (critical Section) // Now, producer is out of critical section flag[j] = false; // end of code for producer //-------------------------------------------------------- // code for consumer i // consumer i is ready // to consume an item flag[i] = true; // but producer (j) can produce an item turn = j; // if producer is ready to produce an item // and if its producer's turn while (flag[j] == true && turn == j) { // then consumer will wait } // otherwise consumer will consume // an item from buffer (critical Section) // Now, consumer is out of critical section flag[i] = false;// end of code for consumer
Explanation of Peterson’s algorithm –
Peterson’s Algorithm is used to synchronize two processes. It uses two variables, a bool array flag of size 2 and an int variable turn to accomplish it.In the solution i represents the Consumer and j represents the Producer. Initially the flags are false. When a process wants to execute it’s critical section, it sets it’s flag to true and turn as the index of the other process. This means that the process wants to execute but it will allow the other process to run first. The process performs busy waiting until the other process has finished it’s own critical section.After this the current process enters it’s critical section and adds or removes a random number from the shared buffer. After completing the critical section, it sets it’s own flag to false, indication it does not wish to execute anymore.
The program runs for a fixed amount of time before exiting. This time can be changed by changing value of the macro RT.
// C program to implement Peterson’s Algorithm// for producer-consumer problem.#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <time.h>#include <sys/types.h>#include <sys/ipc.h>#include <sys/shm.h>#include <stdbool.h>#define _BSD_SOURCE#include <sys/time.h>#include <stdio.h> #define BSIZE 8 // Buffer size#define PWT 2 // Producer wait time limit#define CWT 10 // Consumer wait time limit#define RT 10 // Program run-time in seconds int shmid1, shmid2, shmid3, shmid4;key_t k1 = 5491, k2 = 5812, k3 = 4327, k4 = 3213;bool* SHM1;int* SHM2;int* SHM3; int myrand(int n) // Returns a random number between 1 and n{ time_t t; srand((unsigned)time(&t)); return (rand() % n + 1);} int main(){ shmid1 = shmget(k1, sizeof(bool) * 2, IPC_CREAT | 0660); // flag shmid2 = shmget(k2, sizeof(int) * 1, IPC_CREAT | 0660); // turn shmid3 = shmget(k3, sizeof(int) * BSIZE, IPC_CREAT | 0660); // buffer shmid4 = shmget(k4, sizeof(int) * 1, IPC_CREAT | 0660); // time stamp if (shmid1 < 0 || shmid2 < 0 || shmid3 < 0 || shmid4 < 0) { perror("Main shmget error: "); exit(1); } SHM3 = (int*)shmat(shmid3, NULL, 0); int ix = 0; while (ix < BSIZE) // Initializing buffer SHM3[ix++] = 0; struct timeval t; time_t t1, t2; gettimeofday(&t, NULL); t1 = t.tv_sec; int* state = (int*)shmat(shmid4, NULL, 0); *state = 1; int wait_time; int i = 0; // Consumer int j = 1; // Producer if (fork() == 0) // Producer code { SHM1 = (bool*)shmat(shmid1, NULL, 0); SHM2 = (int*)shmat(shmid2, NULL, 0); SHM3 = (int*)shmat(shmid3, NULL, 0); if (SHM1 == (bool*)-1 || SHM2 == (int*)-1 || SHM3 == (int*)-1) { perror("Producer shmat error: "); exit(1); } bool* flag = SHM1; int* turn = SHM2; int* buf = SHM3; int index = 0; while (*state == 1) { flag[j] = true; printf("Producer is ready now.\n\n"); *turn = i; while (flag[i] == true && *turn == i) ; // Critical Section Begin index = 0; while (index < BSIZE) { if (buf[index] == 0) { int tempo = myrand(BSIZE * 3); printf("Job %d has been produced\n", tempo); buf[index] = tempo; break; } index++; } if (index == BSIZE) printf("Buffer is full, nothing can be produced!!!\n"); printf("Buffer: "); index = 0; while (index < BSIZE) printf("%d ", buf[index++]); printf("\n"); // Critical Section End flag[j] = false; if (*state == 0) break; wait_time = myrand(PWT); printf("Producer will wait for %d seconds\n\n", wait_time); sleep(wait_time); } exit(0); } if (fork() == 0) // Consumer code { SHM1 = (bool*)shmat(shmid1, NULL, 0); SHM2 = (int*)shmat(shmid2, NULL, 0); SHM3 = (int*)shmat(shmid3, NULL, 0); if (SHM1 == (bool*)-1 || SHM2 == (int*)-1 || SHM3 == (int*)-1) { perror("Consumer shmat error:"); exit(1); } bool* flag = SHM1; int* turn = SHM2; int* buf = SHM3; int index = 0; flag[i] = false; sleep(5); while (*state == 1) { flag[i] = true; printf("Consumer is ready now.\n\n"); *turn = j; while (flag[j] == true && *turn == j) ; // Critical Section Begin if (buf[0] != 0) { printf("Job %d has been consumed\n", buf[0]); buf[0] = 0; index = 1; while (index < BSIZE) // Shifting remaining jobs forward { buf[index - 1] = buf[index]; index++; } buf[index - 1] = 0; } else printf("Buffer is empty, nothing can be consumed!!!\n"); printf("Buffer: "); index = 0; while (index < BSIZE) printf("%d ", buf[index++]); printf("\n"); // Critical Section End flag[i] = false; if (*state == 0) break; wait_time = myrand(CWT); printf("Consumer will sleep for %d seconds\n\n", wait_time); sleep(wait_time); } exit(0); } // Parent process will now for RT seconds before causing child to terminate while (1) { gettimeofday(&t, NULL); t2 = t.tv_sec; if (t2 - t1 > RT) // Program will exit after RT seconds { *state = 0; break; } } // Waiting for both processes to exit wait(); wait(); printf("The clock ran out.\n"); return 0;}
Output:
Producer is ready now.
Job 9 has been produced
Buffer: 9 0 0 0 0 0 0 0
Producer will wait for 1 seconds
Producer is ready now.
Job 8 has been produced
Buffer: 9 8 0 0 0 0 0 0
Producer will wait for 2 seconds
Producer is ready now.
Job 13 has been produced
Buffer: 9 8 13 0 0 0 0 0
Producer will wait for 1 seconds
Producer is ready now.
Job 23 has been produced
Buffer: 9 8 13 23 0 0 0 0
Producer will wait for 1 seconds
Consumer is ready now.
Job 9 has been consumed
Buffer: 8 13 23 0 0 0 0 0
Consumer will sleep for 9 seconds
Producer is ready now.
Job 15 has been produced
Buffer: 8 13 23 15 0 0 0 0
Producer will wait for 1 seconds
Producer is ready now.
Job 13 has been produced
Buffer: 8 13 23 15 13 0 0 0
Producer will wait for 1 seconds
Producer is ready now.
Job 11 has been produced
Buffer: 8 13 23 15 13 11 0 0
Producer will wait for 1 seconds
Producer is ready now.
Job 22 has been produced
Buffer: 8 13 23 15 13 11 22 0
Producer will wait for 2 seconds
Producer is ready now.
Job 23 has been produced
Buffer: 8 13 23 15 13 11 22 23
Producer will wait for 1 seconds
The clock ran out.
This article is contributed by Nabaneet Roy. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Akanksha_Rai
Algorithms
GATE CS
Operating Systems
Operating Systems
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Oct, 2019"
},
{
"code": null,
"e": 101,
"s": 52,
"text": "Prerequisite – synchronization, Critical Section"
},
{
"code": null,
"e": 721,
"s": 101,
"text": "Problem:The producer consumer problem (or bounded buffer problem) describes two processes, the producer and the consumer, which share a common, fixed-size buffer used as a queue. Producer produce an item and put it into buffer. If buffer is already full then producer will have to wait for an empty block in buffer. Consumer consume an item from buffer. If buffer is already empty then consumer will have to wait for an item in buffer. Implement Peterson’s Algorithm for the two processes using shared memory such that there is mutual exclusion between them. The solution should have free from synchronization problems."
},
{
"code": null,
"e": 744,
"s": 721,
"text": "Peterson’s algorithm –"
},
{
"code": "// code for producer (j) // producer j is ready// to produce an itemflag[j] = true; // but consumer (i) can consume an itemturn = i; // if consumer is ready to consume an item// and if its consumer's turnwhile (flag[i] == true && turn == i) { // then producer will wait } // otherwise producer will produce // an item and put it into buffer (critical Section) // Now, producer is out of critical section flag[j] = false; // end of code for producer //-------------------------------------------------------- // code for consumer i // consumer i is ready // to consume an item flag[i] = true; // but producer (j) can produce an item turn = j; // if producer is ready to produce an item // and if its producer's turn while (flag[j] == true && turn == j) { // then consumer will wait } // otherwise consumer will consume // an item from buffer (critical Section) // Now, consumer is out of critical section flag[i] = false;// end of code for consumer",
"e": 1798,
"s": 744,
"text": null
},
{
"code": null,
"e": 1836,
"s": 1798,
"text": "Explanation of Peterson’s algorithm –"
},
{
"code": null,
"e": 2648,
"s": 1836,
"text": "Peterson’s Algorithm is used to synchronize two processes. It uses two variables, a bool array flag of size 2 and an int variable turn to accomplish it.In the solution i represents the Consumer and j represents the Producer. Initially the flags are false. When a process wants to execute it’s critical section, it sets it’s flag to true and turn as the index of the other process. This means that the process wants to execute but it will allow the other process to run first. The process performs busy waiting until the other process has finished it’s own critical section.After this the current process enters it’s critical section and adds or removes a random number from the shared buffer. After completing the critical section, it sets it’s own flag to false, indication it does not wish to execute anymore."
},
{
"code": null,
"e": 2768,
"s": 2648,
"text": "The program runs for a fixed amount of time before exiting. This time can be changed by changing value of the macro RT."
},
{
"code": "// C program to implement Peterson’s Algorithm// for producer-consumer problem.#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <time.h>#include <sys/types.h>#include <sys/ipc.h>#include <sys/shm.h>#include <stdbool.h>#define _BSD_SOURCE#include <sys/time.h>#include <stdio.h> #define BSIZE 8 // Buffer size#define PWT 2 // Producer wait time limit#define CWT 10 // Consumer wait time limit#define RT 10 // Program run-time in seconds int shmid1, shmid2, shmid3, shmid4;key_t k1 = 5491, k2 = 5812, k3 = 4327, k4 = 3213;bool* SHM1;int* SHM2;int* SHM3; int myrand(int n) // Returns a random number between 1 and n{ time_t t; srand((unsigned)time(&t)); return (rand() % n + 1);} int main(){ shmid1 = shmget(k1, sizeof(bool) * 2, IPC_CREAT | 0660); // flag shmid2 = shmget(k2, sizeof(int) * 1, IPC_CREAT | 0660); // turn shmid3 = shmget(k3, sizeof(int) * BSIZE, IPC_CREAT | 0660); // buffer shmid4 = shmget(k4, sizeof(int) * 1, IPC_CREAT | 0660); // time stamp if (shmid1 < 0 || shmid2 < 0 || shmid3 < 0 || shmid4 < 0) { perror(\"Main shmget error: \"); exit(1); } SHM3 = (int*)shmat(shmid3, NULL, 0); int ix = 0; while (ix < BSIZE) // Initializing buffer SHM3[ix++] = 0; struct timeval t; time_t t1, t2; gettimeofday(&t, NULL); t1 = t.tv_sec; int* state = (int*)shmat(shmid4, NULL, 0); *state = 1; int wait_time; int i = 0; // Consumer int j = 1; // Producer if (fork() == 0) // Producer code { SHM1 = (bool*)shmat(shmid1, NULL, 0); SHM2 = (int*)shmat(shmid2, NULL, 0); SHM3 = (int*)shmat(shmid3, NULL, 0); if (SHM1 == (bool*)-1 || SHM2 == (int*)-1 || SHM3 == (int*)-1) { perror(\"Producer shmat error: \"); exit(1); } bool* flag = SHM1; int* turn = SHM2; int* buf = SHM3; int index = 0; while (*state == 1) { flag[j] = true; printf(\"Producer is ready now.\\n\\n\"); *turn = i; while (flag[i] == true && *turn == i) ; // Critical Section Begin index = 0; while (index < BSIZE) { if (buf[index] == 0) { int tempo = myrand(BSIZE * 3); printf(\"Job %d has been produced\\n\", tempo); buf[index] = tempo; break; } index++; } if (index == BSIZE) printf(\"Buffer is full, nothing can be produced!!!\\n\"); printf(\"Buffer: \"); index = 0; while (index < BSIZE) printf(\"%d \", buf[index++]); printf(\"\\n\"); // Critical Section End flag[j] = false; if (*state == 0) break; wait_time = myrand(PWT); printf(\"Producer will wait for %d seconds\\n\\n\", wait_time); sleep(wait_time); } exit(0); } if (fork() == 0) // Consumer code { SHM1 = (bool*)shmat(shmid1, NULL, 0); SHM2 = (int*)shmat(shmid2, NULL, 0); SHM3 = (int*)shmat(shmid3, NULL, 0); if (SHM1 == (bool*)-1 || SHM2 == (int*)-1 || SHM3 == (int*)-1) { perror(\"Consumer shmat error:\"); exit(1); } bool* flag = SHM1; int* turn = SHM2; int* buf = SHM3; int index = 0; flag[i] = false; sleep(5); while (*state == 1) { flag[i] = true; printf(\"Consumer is ready now.\\n\\n\"); *turn = j; while (flag[j] == true && *turn == j) ; // Critical Section Begin if (buf[0] != 0) { printf(\"Job %d has been consumed\\n\", buf[0]); buf[0] = 0; index = 1; while (index < BSIZE) // Shifting remaining jobs forward { buf[index - 1] = buf[index]; index++; } buf[index - 1] = 0; } else printf(\"Buffer is empty, nothing can be consumed!!!\\n\"); printf(\"Buffer: \"); index = 0; while (index < BSIZE) printf(\"%d \", buf[index++]); printf(\"\\n\"); // Critical Section End flag[i] = false; if (*state == 0) break; wait_time = myrand(CWT); printf(\"Consumer will sleep for %d seconds\\n\\n\", wait_time); sleep(wait_time); } exit(0); } // Parent process will now for RT seconds before causing child to terminate while (1) { gettimeofday(&t, NULL); t2 = t.tv_sec; if (t2 - t1 > RT) // Program will exit after RT seconds { *state = 0; break; } } // Waiting for both processes to exit wait(); wait(); printf(\"The clock ran out.\\n\"); return 0;}",
"e": 7724,
"s": 2768,
"text": null
},
{
"code": null,
"e": 7732,
"s": 7724,
"text": "Output:"
},
{
"code": null,
"e": 8860,
"s": 7732,
"text": "Producer is ready now.\n\nJob 9 has been produced\nBuffer: 9 0 0 0 0 0 0 0 \nProducer will wait for 1 seconds\n\nProducer is ready now.\n\nJob 8 has been produced\nBuffer: 9 8 0 0 0 0 0 0 \nProducer will wait for 2 seconds\n\nProducer is ready now.\n\nJob 13 has been produced\nBuffer: 9 8 13 0 0 0 0 0 \nProducer will wait for 1 seconds\n\nProducer is ready now.\n\nJob 23 has been produced\nBuffer: 9 8 13 23 0 0 0 0 \nProducer will wait for 1 seconds\n\nConsumer is ready now.\n\nJob 9 has been consumed\nBuffer: 8 13 23 0 0 0 0 0 \nConsumer will sleep for 9 seconds\n\nProducer is ready now.\n\nJob 15 has been produced\nBuffer: 8 13 23 15 0 0 0 0 \nProducer will wait for 1 seconds\n\nProducer is ready now.\n\nJob 13 has been produced\nBuffer: 8 13 23 15 13 0 0 0 \nProducer will wait for 1 seconds\n\nProducer is ready now.\n\nJob 11 has been produced\nBuffer: 8 13 23 15 13 11 0 0 \nProducer will wait for 1 seconds\n\nProducer is ready now.\n\nJob 22 has been produced\nBuffer: 8 13 23 15 13 11 22 0 \nProducer will wait for 2 seconds\n\nProducer is ready now.\n\nJob 23 has been produced\nBuffer: 8 13 23 15 13 11 22 23 \nProducer will wait for 1 seconds\n\nThe clock ran out.\n"
},
{
"code": null,
"e": 9160,
"s": 8860,
"text": "This article is contributed by Nabaneet Roy. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 9285,
"s": 9160,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 9298,
"s": 9285,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 9309,
"s": 9298,
"text": "Algorithms"
},
{
"code": null,
"e": 9317,
"s": 9309,
"text": "GATE CS"
},
{
"code": null,
"e": 9335,
"s": 9317,
"text": "Operating Systems"
},
{
"code": null,
"e": 9353,
"s": 9335,
"text": "Operating Systems"
},
{
"code": null,
"e": 9364,
"s": 9353,
"text": "Algorithms"
}
] |
Observer Pattern | Set 1 (Introduction)
|
01 Sep, 2021
Let us first consider the following scenario to understand observer pattern.
Scenario:
Suppose we are building a cricket app that notifies viewers about the information such as current score, run rate etc. Suppose we have made two display elements CurrentScoreDisplay and AverageScoreDisplay. CricketData has all the data (runs, bowls etc.) and whenever data changes the display elements are notified with new data and they display the latest data accordingly.
Below is the java implementation of this design.
// Java implementation of above design for Cricket App. The// problems with this design are discussed below. // A class that gets information from stadium and notifies// display elements, CurrentScoreDisplay & AverageScoreDisplayclass CricketData{ int runs, wickets; float overs; CurrentScoreDisplay currentScoreDisplay; AverageScoreDisplay averageScoreDisplay; // Constructor public CricketData(CurrentScoreDisplay currentScoreDisplay, AverageScoreDisplay averageScoreDisplay) { this.currentScoreDisplay = currentScoreDisplay; this.averageScoreDisplay = averageScoreDisplay; } // Get latest runs from stadium private int getLatestRuns() { // return 90 for simplicity return 90; } // Get latest wickets from stadium private int getLatestWickets() { // return 2 for simplicity return 2; } // Get latest overs from stadium private float getLatestOvers() { // return 10.2 for simplicity return (float)10.2; } // This method is used update displays when data changes public void dataChanged() { // get latest data runs = getLatestRuns(); wickets = getLatestWickets(); overs = getLatestOvers(); currentScoreDisplay.update(runs,wickets,overs); averageScoreDisplay.update(runs,wickets,overs); }} // A class to display average score. Data of this class is// updated by CricketDataclass AverageScoreDisplay{ private float runRate; private int predictedScore; public void update(int runs, int wickets, float overs) { this.runRate = (float)runs/overs; this.predictedScore = (int) (this.runRate * 50); display(); } public void display() { System.out.println("\nAverage Score Display:\n" + "Run Rate: " + runRate + "\nPredictedScore: " + predictedScore); }} // A class to display score. Data of this class is// updated by CricketDataclass CurrentScoreDisplay{ private int runs, wickets; private float overs; public void update(int runs,int wickets,float overs) { this.runs = runs; this.wickets = wickets; this.overs = overs; display(); } public void display() { System.out.println("\nCurrent Score Display: \n" + "Runs: " + runs +"\nWickets:" + wickets + "\nOvers: " + overs ); }} // Driver classclass Main{ public static void main(String args[]) { // Create objects for testing AverageScoreDisplay averageScoreDisplay = new AverageScoreDisplay(); CurrentScoreDisplay currentScoreDisplay = new CurrentScoreDisplay(); // Pass the displays to Cricket data CricketData cricketData = new CricketData(currentScoreDisplay, averageScoreDisplay); // In real app you would have some logic to call this // function when data changes cricketData.dataChanged(); }}
Output:
Current Score Display:
Runs: 90
Wickets:2
Overs: 10.2
Average Score Display:
Run Rate: 8.823529
PredictedScore: 441
Problems with above design:
CricketData holds references to concrete display element objects even though it needs to call only the update method of these objects. It has access to too much additional information than it requires.
This statement “currentScoreDisplay.update(runs,wickets,overs);” violates one of the most important design principle “Program to interfaces, not implementations.” as we are using concrete objects to share data rather than abstract interfaces.
CricketData and display elements are tightly coupled.
If in future another requirement comes in and we need another display element to be added we need to make changes to the non-varying part of our code(CricketData). This is definitely not a good design practice and application might not be able to handle changes and not easy to maintain.
How to avoid these problems?Use Observer Pattern
Observer pattern
To understand observer pattern, first you need to understand the subject and observer objects.
The relation between subject and observer can easily be understood as an analogy to magazine subscription.
A magazine publisher(subject) is in the business and publishes magazines (data).
If you(user of data/observer) are interested in the magazine you subscribe(register), and if a new edition is published it gets delivered to you.
If you unsubscribe(unregister) you stop getting new editions.
Publisher doesn’t know who you are and how you use the magazine, it just delivers it to you because you are a subscriber(loose coupling).
Definition:
The Observer Pattern defines a one to many dependency between objects so that one object changes state, all of its dependents are notified and updated automatically.
Explanation:
One to many dependency is between Subject(One) and Observer(Many).
There is dependency as Observers themselves don’t have access to data. They are dependent on Subject to provide them data.
Class diagram:
Image Source : Wikipedia
Here Observer and Subject are interfaces(can be any abstract super type not necessarily java interface).
All observers who need the data need to implement observer interface.
notify() method in observer interface defines the action to be taken when the subject provides it data.
The subject maintains an observerCollection which is simply the list of currently registered(subscribed) observers.
registerObserver(observer) and unregisterObserver(observer) are methods to add and remove observers respectively.
notifyObservers() is called when the data is changed and the observers need to be supplied with new data.
Advantages:Provides a loosely coupled design between objects that interact. Loosely coupled objects are flexible with changing requirements. Here loose coupling means that the interacting objects should have less information about each other.
Observer pattern provides this loose coupling as:
Subject only knows that observer implement Observer interface.Nothing more.
There is no need to modify Subject to add or remove observers.
We can reuse subject and observer classes independently of each other.
Disadvantages:
Memory leaks caused by Lapsed listener problem because of explicit register and unregistering of observers.
When to use this pattern?You should consider using this pattern in your application when multiple objects are dependent on the state of one object as it provides a neat and well tested design for the same.
Real Life Uses:
It is heavily used in GUI toolkits and event listener. In java the button(subject) and onClickListener(observer) are modelled with observer pattern.
Social media, RSS feeds, email subscription in which you have the option to follow or subscribe and you receive latest notification.
All users of an app on play store gets notified if there is an update.
Observer Pattern | Set 2 (Implementation)
Further Read – Observer Method in Python
This article is contributed by Sulabh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
RahulSindhav
Design Pattern
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Factory method design pattern in Java
Builder Design Pattern
Introduction of Programming Paradigms
Unified Modeling Language (UML) | An Introduction
MVC Design Pattern
Abstract Factory Pattern
Monolithic vs Microservices architecture
Composite Design Pattern
Unified Modeling Language (UML) | State Diagrams
Chain of Responsibility Design Pattern
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Sep, 2021"
},
{
"code": null,
"e": 129,
"s": 52,
"text": "Let us first consider the following scenario to understand observer pattern."
},
{
"code": null,
"e": 139,
"s": 129,
"text": "Scenario:"
},
{
"code": null,
"e": 513,
"s": 139,
"text": "Suppose we are building a cricket app that notifies viewers about the information such as current score, run rate etc. Suppose we have made two display elements CurrentScoreDisplay and AverageScoreDisplay. CricketData has all the data (runs, bowls etc.) and whenever data changes the display elements are notified with new data and they display the latest data accordingly."
},
{
"code": null,
"e": 562,
"s": 513,
"text": "Below is the java implementation of this design."
},
{
"code": "// Java implementation of above design for Cricket App. The// problems with this design are discussed below. // A class that gets information from stadium and notifies// display elements, CurrentScoreDisplay & AverageScoreDisplayclass CricketData{ int runs, wickets; float overs; CurrentScoreDisplay currentScoreDisplay; AverageScoreDisplay averageScoreDisplay; // Constructor public CricketData(CurrentScoreDisplay currentScoreDisplay, AverageScoreDisplay averageScoreDisplay) { this.currentScoreDisplay = currentScoreDisplay; this.averageScoreDisplay = averageScoreDisplay; } // Get latest runs from stadium private int getLatestRuns() { // return 90 for simplicity return 90; } // Get latest wickets from stadium private int getLatestWickets() { // return 2 for simplicity return 2; } // Get latest overs from stadium private float getLatestOvers() { // return 10.2 for simplicity return (float)10.2; } // This method is used update displays when data changes public void dataChanged() { // get latest data runs = getLatestRuns(); wickets = getLatestWickets(); overs = getLatestOvers(); currentScoreDisplay.update(runs,wickets,overs); averageScoreDisplay.update(runs,wickets,overs); }} // A class to display average score. Data of this class is// updated by CricketDataclass AverageScoreDisplay{ private float runRate; private int predictedScore; public void update(int runs, int wickets, float overs) { this.runRate = (float)runs/overs; this.predictedScore = (int) (this.runRate * 50); display(); } public void display() { System.out.println(\"\\nAverage Score Display:\\n\" + \"Run Rate: \" + runRate + \"\\nPredictedScore: \" + predictedScore); }} // A class to display score. Data of this class is// updated by CricketDataclass CurrentScoreDisplay{ private int runs, wickets; private float overs; public void update(int runs,int wickets,float overs) { this.runs = runs; this.wickets = wickets; this.overs = overs; display(); } public void display() { System.out.println(\"\\nCurrent Score Display: \\n\" + \"Runs: \" + runs +\"\\nWickets:\" + wickets + \"\\nOvers: \" + overs ); }} // Driver classclass Main{ public static void main(String args[]) { // Create objects for testing AverageScoreDisplay averageScoreDisplay = new AverageScoreDisplay(); CurrentScoreDisplay currentScoreDisplay = new CurrentScoreDisplay(); // Pass the displays to Cricket data CricketData cricketData = new CricketData(currentScoreDisplay, averageScoreDisplay); // In real app you would have some logic to call this // function when data changes cricketData.dataChanged(); }}",
"e": 3727,
"s": 562,
"text": null
},
{
"code": null,
"e": 3735,
"s": 3727,
"text": "Output:"
},
{
"code": null,
"e": 3853,
"s": 3735,
"text": "Current Score Display: \nRuns: 90\nWickets:2\nOvers: 10.2\n\nAverage Score Display:\nRun Rate: 8.823529\nPredictedScore: 441"
},
{
"code": null,
"e": 3881,
"s": 3853,
"text": "Problems with above design:"
},
{
"code": null,
"e": 4083,
"s": 3881,
"text": "CricketData holds references to concrete display element objects even though it needs to call only the update method of these objects. It has access to too much additional information than it requires."
},
{
"code": null,
"e": 4326,
"s": 4083,
"text": "This statement “currentScoreDisplay.update(runs,wickets,overs);” violates one of the most important design principle “Program to interfaces, not implementations.” as we are using concrete objects to share data rather than abstract interfaces."
},
{
"code": null,
"e": 4380,
"s": 4326,
"text": "CricketData and display elements are tightly coupled."
},
{
"code": null,
"e": 4668,
"s": 4380,
"text": "If in future another requirement comes in and we need another display element to be added we need to make changes to the non-varying part of our code(CricketData). This is definitely not a good design practice and application might not be able to handle changes and not easy to maintain."
},
{
"code": null,
"e": 4717,
"s": 4668,
"text": "How to avoid these problems?Use Observer Pattern"
},
{
"code": null,
"e": 4734,
"s": 4717,
"text": "Observer pattern"
},
{
"code": null,
"e": 4829,
"s": 4734,
"text": "To understand observer pattern, first you need to understand the subject and observer objects."
},
{
"code": null,
"e": 4936,
"s": 4829,
"text": "The relation between subject and observer can easily be understood as an analogy to magazine subscription."
},
{
"code": null,
"e": 5017,
"s": 4936,
"text": "A magazine publisher(subject) is in the business and publishes magazines (data)."
},
{
"code": null,
"e": 5163,
"s": 5017,
"text": "If you(user of data/observer) are interested in the magazine you subscribe(register), and if a new edition is published it gets delivered to you."
},
{
"code": null,
"e": 5225,
"s": 5163,
"text": "If you unsubscribe(unregister) you stop getting new editions."
},
{
"code": null,
"e": 5363,
"s": 5225,
"text": "Publisher doesn’t know who you are and how you use the magazine, it just delivers it to you because you are a subscriber(loose coupling)."
},
{
"code": null,
"e": 5375,
"s": 5363,
"text": "Definition:"
},
{
"code": null,
"e": 5541,
"s": 5375,
"text": "The Observer Pattern defines a one to many dependency between objects so that one object changes state, all of its dependents are notified and updated automatically."
},
{
"code": null,
"e": 5554,
"s": 5541,
"text": "Explanation:"
},
{
"code": null,
"e": 5621,
"s": 5554,
"text": "One to many dependency is between Subject(One) and Observer(Many)."
},
{
"code": null,
"e": 5744,
"s": 5621,
"text": "There is dependency as Observers themselves don’t have access to data. They are dependent on Subject to provide them data."
},
{
"code": null,
"e": 5759,
"s": 5744,
"text": "Class diagram:"
},
{
"code": null,
"e": 5784,
"s": 5759,
"text": "Image Source : Wikipedia"
},
{
"code": null,
"e": 5889,
"s": 5784,
"text": "Here Observer and Subject are interfaces(can be any abstract super type not necessarily java interface)."
},
{
"code": null,
"e": 5959,
"s": 5889,
"text": "All observers who need the data need to implement observer interface."
},
{
"code": null,
"e": 6063,
"s": 5959,
"text": "notify() method in observer interface defines the action to be taken when the subject provides it data."
},
{
"code": null,
"e": 6179,
"s": 6063,
"text": "The subject maintains an observerCollection which is simply the list of currently registered(subscribed) observers."
},
{
"code": null,
"e": 6293,
"s": 6179,
"text": "registerObserver(observer) and unregisterObserver(observer) are methods to add and remove observers respectively."
},
{
"code": null,
"e": 6399,
"s": 6293,
"text": "notifyObservers() is called when the data is changed and the observers need to be supplied with new data."
},
{
"code": null,
"e": 6642,
"s": 6399,
"text": "Advantages:Provides a loosely coupled design between objects that interact. Loosely coupled objects are flexible with changing requirements. Here loose coupling means that the interacting objects should have less information about each other."
},
{
"code": null,
"e": 6692,
"s": 6642,
"text": "Observer pattern provides this loose coupling as:"
},
{
"code": null,
"e": 6768,
"s": 6692,
"text": "Subject only knows that observer implement Observer interface.Nothing more."
},
{
"code": null,
"e": 6831,
"s": 6768,
"text": "There is no need to modify Subject to add or remove observers."
},
{
"code": null,
"e": 6902,
"s": 6831,
"text": "We can reuse subject and observer classes independently of each other."
},
{
"code": null,
"e": 6917,
"s": 6902,
"text": "Disadvantages:"
},
{
"code": null,
"e": 7025,
"s": 6917,
"text": "Memory leaks caused by Lapsed listener problem because of explicit register and unregistering of observers."
},
{
"code": null,
"e": 7231,
"s": 7025,
"text": "When to use this pattern?You should consider using this pattern in your application when multiple objects are dependent on the state of one object as it provides a neat and well tested design for the same."
},
{
"code": null,
"e": 7247,
"s": 7231,
"text": "Real Life Uses:"
},
{
"code": null,
"e": 7396,
"s": 7247,
"text": "It is heavily used in GUI toolkits and event listener. In java the button(subject) and onClickListener(observer) are modelled with observer pattern."
},
{
"code": null,
"e": 7529,
"s": 7396,
"text": "Social media, RSS feeds, email subscription in which you have the option to follow or subscribe and you receive latest notification."
},
{
"code": null,
"e": 7600,
"s": 7529,
"text": "All users of an app on play store gets notified if there is an update."
},
{
"code": null,
"e": 7642,
"s": 7600,
"text": "Observer Pattern | Set 2 (Implementation)"
},
{
"code": null,
"e": 7683,
"s": 7642,
"text": "Further Read – Observer Method in Python"
},
{
"code": null,
"e": 7950,
"s": 7683,
"text": "This article is contributed by Sulabh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 8074,
"s": 7950,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 8087,
"s": 8074,
"text": "RahulSindhav"
},
{
"code": null,
"e": 8102,
"s": 8087,
"text": "Design Pattern"
},
{
"code": null,
"e": 8200,
"s": 8102,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8238,
"s": 8200,
"text": "Factory method design pattern in Java"
},
{
"code": null,
"e": 8261,
"s": 8238,
"text": "Builder Design Pattern"
},
{
"code": null,
"e": 8299,
"s": 8261,
"text": "Introduction of Programming Paradigms"
},
{
"code": null,
"e": 8349,
"s": 8299,
"text": "Unified Modeling Language (UML) | An Introduction"
},
{
"code": null,
"e": 8368,
"s": 8349,
"text": "MVC Design Pattern"
},
{
"code": null,
"e": 8393,
"s": 8368,
"text": "Abstract Factory Pattern"
},
{
"code": null,
"e": 8434,
"s": 8393,
"text": "Monolithic vs Microservices architecture"
},
{
"code": null,
"e": 8459,
"s": 8434,
"text": "Composite Design Pattern"
},
{
"code": null,
"e": 8508,
"s": 8459,
"text": "Unified Modeling Language (UML) | State Diagrams"
}
] |
How to remove SVG content?
|
30 Jun, 2022
In order to remove SVG content, you can use the remove() function provided by D3.js. The remove() function is used along with two methods which are also provided by D3.js. Following methods are:
Using select() Method with remove() Method: The d3.select() method is used to select the first element that need to remove.
Syntax:
d3.select("element").remove()
Example: In this example, first paragraph (p) element is removed.
html
<!DOCTYPE html><html> <head> <title> How can I remove SVG content? </title> <script src = "https://d3js.org/d3.v4.min.js"></script></head> <body style="text-align:center"> <h1 style="color:green">GeeksforGeeks</h1> <h3> How can I remove SVG content?</h3> <p>Geeks1</p> <p>Geeks2</p> <p>Geeks3</p> <script> // Calling the selectAll() function d3.select("p").remove(); </script></body> </html>
Output:
Using selectAll() Method with remove() Method: The d3.selectAll() method is used to select all the element that matched and remove it. Syntax:
d3.selectAll("element").remove()
Example: In this example, all paragraph (p) elements are removed.
html
<!DOCTYPE html><html> <head> <title> How can I remove SVG content? </title> <script src = "https://d3js.org/d3.v4.min.js"></script></head> <body style="text-align:center"> <h1 style="color:green">GeeksforGeeks</h1> <h3> How can I remove SVG content?</h3> <p>Geeks1</p> <p>Geeks2</p> <p>Geeks3</p> <script> // Calling the selectAll() function d3.selectAll("p").remove(); </script></body> </html>
Output:
sidhanthnandansaaho
CSS-Misc
HTML-Misc
JavaScript-Misc
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jun, 2022"
},
{
"code": null,
"e": 223,
"s": 28,
"text": "In order to remove SVG content, you can use the remove() function provided by D3.js. The remove() function is used along with two methods which are also provided by D3.js. Following methods are:"
},
{
"code": null,
"e": 348,
"s": 223,
"text": "Using select() Method with remove() Method: The d3.select() method is used to select the first element that need to remove. "
},
{
"code": null,
"e": 356,
"s": 348,
"text": "Syntax:"
},
{
"code": null,
"e": 386,
"s": 356,
"text": "d3.select(\"element\").remove()"
},
{
"code": null,
"e": 453,
"s": 386,
"text": "Example: In this example, first paragraph (p) element is removed. "
},
{
"code": null,
"e": 458,
"s": 453,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How can I remove SVG content? </title> <script src = \"https://d3js.org/d3.v4.min.js\"></script></head> <body style=\"text-align:center\"> <h1 style=\"color:green\">GeeksforGeeks</h1> <h3> How can I remove SVG content?</h3> <p>Geeks1</p> <p>Geeks2</p> <p>Geeks3</p> <script> // Calling the selectAll() function d3.select(\"p\").remove(); </script></body> </html> ",
"e": 935,
"s": 458,
"text": null
},
{
"code": null,
"e": 943,
"s": 935,
"text": "Output:"
},
{
"code": null,
"e": 1088,
"s": 945,
"text": "Using selectAll() Method with remove() Method: The d3.selectAll() method is used to select all the element that matched and remove it. Syntax:"
},
{
"code": null,
"e": 1121,
"s": 1088,
"text": "d3.selectAll(\"element\").remove()"
},
{
"code": null,
"e": 1188,
"s": 1121,
"text": "Example: In this example, all paragraph (p) elements are removed. "
},
{
"code": null,
"e": 1193,
"s": 1188,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How can I remove SVG content? </title> <script src = \"https://d3js.org/d3.v4.min.js\"></script></head> <body style=\"text-align:center\"> <h1 style=\"color:green\">GeeksforGeeks</h1> <h3> How can I remove SVG content?</h3> <p>Geeks1</p> <p>Geeks2</p> <p>Geeks3</p> <script> // Calling the selectAll() function d3.selectAll(\"p\").remove(); </script></body> </html> ",
"e": 1673,
"s": 1193,
"text": null
},
{
"code": null,
"e": 1681,
"s": 1673,
"text": "Output:"
},
{
"code": null,
"e": 1703,
"s": 1683,
"text": "sidhanthnandansaaho"
},
{
"code": null,
"e": 1712,
"s": 1703,
"text": "CSS-Misc"
},
{
"code": null,
"e": 1722,
"s": 1712,
"text": "HTML-Misc"
},
{
"code": null,
"e": 1738,
"s": 1722,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 1742,
"s": 1738,
"text": "CSS"
},
{
"code": null,
"e": 1747,
"s": 1742,
"text": "HTML"
},
{
"code": null,
"e": 1758,
"s": 1747,
"text": "JavaScript"
},
{
"code": null,
"e": 1775,
"s": 1758,
"text": "Web Technologies"
},
{
"code": null,
"e": 1802,
"s": 1775,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 1807,
"s": 1802,
"text": "HTML"
}
] |
PLSQL | ADD_MONTHS Function
|
24 Oct, 2019
The PLSQL ADD_MONTHS function is used to return a date with a specified number of months added to it. The ADD_MONTHS function accepts two parameters which are the initial date and the number of months to be added to it.The ADD_MONTHS function returns a value of the date data type.
The date argument can be a datetime value or any value that can be implicitly converted to DATE. The integer argument to be added can be an integer or any value that can be implicitly converted to an integer. The return type is always DATE, regardless of the data type of date. If the date specified in the argument is the last day of the month or if the resulting month has fewer days than the day component of date, then the result is the last day of the resulting month.
Syntax:
ADD_MONTHS( init_date, add_months )
Parameters Used
init_date – It is used to specify the initial date.add_months – It is used to specify the number of months to be added to the initial date.
init_date – It is used to specify the initial date.
add_months – It is used to specify the number of months to be added to the initial date.
Return Value:The ADD_MONTHS function returns a value of the date data type.
Supported Versions of Oracle/PLSQL:
Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i
Oracle 12c
Oracle 11g
Oracle 10g
Oracle 9i
Oracle 8i
Example-1: Using positive numeric value in the add_months argument of the ADD_MONTHS function.
DECLARE
Test_Date date := '01-Aug-18';
Add_Month number := 3;
BEGIN
dbms_output.put_line(ADD_MONTHS(Test_Date, Add_Month));
END;
Output:
01.12.18
Example-2: Using negative numeric value in the add_months argument of the ADD_MONTHS function.
DECLARE
Test_Date date := '01-Aug-18';
Add_Month number := -3;
BEGIN
dbms_output.put_line(ADD_MONTHS(Test_Date, Add_Month));
END;
Output:
01.05.03
Example-3: Using negative numeric value in the add_months argument of the ADD_MONTHS function.
DECLARE
Test_Date date := '31-Aug-18';
Add_Month number := -4;
BEGIN
dbms_output.put_line(ADD_MONTHS(Test_Date, Add_Month));
END;
Output:
30.04.18
Since April has 30 days, the ADD_MONTHS returns 30.04.18 as the last day.
Example-4: Using a positive numeric value in the add_months argument of the ADD_MONTHS function.
DECLARE
Test_Date date := '31-Aug-18';
Add_Month number := 3;
BEGIN
dbms_output.put_line(ADD_MONTHS(Test_Date, Add_Month));
END;
Output:
30.11.18
Since November has 30 days, the ADD_MONTHS returns 30.11.18 as the last day.
Example-5: Using select query with the ADD_MONTHS function.
SELECT
ADD_MONTHS( DATE '2016-02-29', 1 )
FROM
dual;
Output:
31-MAR-16
Advantages:The integer argument to be added can be an integer or any value that can be implicitly converted to an integer.
SQL-PL/SQL
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": "\n24 Oct, 2019"
},
{
"code": null,
"e": 310,
"s": 28,
"text": "The PLSQL ADD_MONTHS function is used to return a date with a specified number of months added to it. The ADD_MONTHS function accepts two parameters which are the initial date and the number of months to be added to it.The ADD_MONTHS function returns a value of the date data type."
},
{
"code": null,
"e": 784,
"s": 310,
"text": "The date argument can be a datetime value or any value that can be implicitly converted to DATE. The integer argument to be added can be an integer or any value that can be implicitly converted to an integer. The return type is always DATE, regardless of the data type of date. If the date specified in the argument is the last day of the month or if the resulting month has fewer days than the day component of date, then the result is the last day of the resulting month."
},
{
"code": null,
"e": 792,
"s": 784,
"text": "Syntax:"
},
{
"code": null,
"e": 828,
"s": 792,
"text": "ADD_MONTHS( init_date, add_months )"
},
{
"code": null,
"e": 844,
"s": 828,
"text": "Parameters Used"
},
{
"code": null,
"e": 984,
"s": 844,
"text": "init_date – It is used to specify the initial date.add_months – It is used to specify the number of months to be added to the initial date."
},
{
"code": null,
"e": 1036,
"s": 984,
"text": "init_date – It is used to specify the initial date."
},
{
"code": null,
"e": 1125,
"s": 1036,
"text": "add_months – It is used to specify the number of months to be added to the initial date."
},
{
"code": null,
"e": 1201,
"s": 1125,
"text": "Return Value:The ADD_MONTHS function returns a value of the date data type."
},
{
"code": null,
"e": 1237,
"s": 1201,
"text": "Supported Versions of Oracle/PLSQL:"
},
{
"code": null,
"e": 1286,
"s": 1237,
"text": "Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i"
},
{
"code": null,
"e": 1297,
"s": 1286,
"text": "Oracle 12c"
},
{
"code": null,
"e": 1308,
"s": 1297,
"text": "Oracle 11g"
},
{
"code": null,
"e": 1319,
"s": 1308,
"text": "Oracle 10g"
},
{
"code": null,
"e": 1329,
"s": 1319,
"text": "Oracle 9i"
},
{
"code": null,
"e": 1339,
"s": 1329,
"text": "Oracle 8i"
},
{
"code": null,
"e": 1434,
"s": 1339,
"text": "Example-1: Using positive numeric value in the add_months argument of the ADD_MONTHS function."
},
{
"code": null,
"e": 1584,
"s": 1434,
"text": "DECLARE \n Test_Date date := '01-Aug-18';\n Add_Month number := 3;\n \nBEGIN \n dbms_output.put_line(ADD_MONTHS(Test_Date, Add_Month)); \n \nEND; "
},
{
"code": null,
"e": 1592,
"s": 1584,
"text": "Output:"
},
{
"code": null,
"e": 1602,
"s": 1592,
"text": "01.12.18 "
},
{
"code": null,
"e": 1697,
"s": 1602,
"text": "Example-2: Using negative numeric value in the add_months argument of the ADD_MONTHS function."
},
{
"code": null,
"e": 1848,
"s": 1697,
"text": "DECLARE \n Test_Date date := '01-Aug-18';\n Add_Month number := -3;\n \nBEGIN \n dbms_output.put_line(ADD_MONTHS(Test_Date, Add_Month)); \n \nEND; "
},
{
"code": null,
"e": 1856,
"s": 1848,
"text": "Output:"
},
{
"code": null,
"e": 1866,
"s": 1856,
"text": "01.05.03 "
},
{
"code": null,
"e": 1961,
"s": 1866,
"text": "Example-3: Using negative numeric value in the add_months argument of the ADD_MONTHS function."
},
{
"code": null,
"e": 2112,
"s": 1961,
"text": "DECLARE \n Test_Date date := '31-Aug-18';\n Add_Month number := -4;\n \nBEGIN \n dbms_output.put_line(ADD_MONTHS(Test_Date, Add_Month)); \n \nEND; "
},
{
"code": null,
"e": 2120,
"s": 2112,
"text": "Output:"
},
{
"code": null,
"e": 2130,
"s": 2120,
"text": "30.04.18 "
},
{
"code": null,
"e": 2204,
"s": 2130,
"text": "Since April has 30 days, the ADD_MONTHS returns 30.04.18 as the last day."
},
{
"code": null,
"e": 2301,
"s": 2204,
"text": "Example-4: Using a positive numeric value in the add_months argument of the ADD_MONTHS function."
},
{
"code": null,
"e": 2451,
"s": 2301,
"text": "DECLARE \n Test_Date date := '31-Aug-18';\n Add_Month number := 3;\n \nBEGIN \n dbms_output.put_line(ADD_MONTHS(Test_Date, Add_Month)); \n \nEND; "
},
{
"code": null,
"e": 2459,
"s": 2451,
"text": "Output:"
},
{
"code": null,
"e": 2469,
"s": 2459,
"text": "30.11.18 "
},
{
"code": null,
"e": 2546,
"s": 2469,
"text": "Since November has 30 days, the ADD_MONTHS returns 30.11.18 as the last day."
},
{
"code": null,
"e": 2606,
"s": 2546,
"text": "Example-5: Using select query with the ADD_MONTHS function."
},
{
"code": null,
"e": 2664,
"s": 2606,
"text": "SELECT\n ADD_MONTHS( DATE '2016-02-29', 1 )\nFROM\n dual; "
},
{
"code": null,
"e": 2672,
"s": 2664,
"text": "Output:"
},
{
"code": null,
"e": 2683,
"s": 2672,
"text": "31-MAR-16 "
},
{
"code": null,
"e": 2806,
"s": 2683,
"text": "Advantages:The integer argument to be added can be an integer or any value that can be implicitly converted to an integer."
},
{
"code": null,
"e": 2817,
"s": 2806,
"text": "SQL-PL/SQL"
},
{
"code": null,
"e": 2821,
"s": 2817,
"text": "SQL"
},
{
"code": null,
"e": 2825,
"s": 2821,
"text": "SQL"
}
] |
Largest and Smallest N-digit Octal Numbers
|
30 Nov, 2021
Given an integer N, the task is to find the smallest and largest N-digit numbers in Octal Number System.
Examples:
Input: N = 4 Output: Largest: 7777 Smallest: 1000
Input: N = 2 Output: Largest: 77 Smallest: 10
Approach: The following steps can be followed to compute the required answer:
Largest Number: To get the largest number, every digit of the number must be maximum. The maximum digit in the Octal number system is ‘7‘. Therefore:
1 Digit Largest Number: '7'
2 Digit Largest Number: '77'
3 Digit Largest Number: '777'
.
.
.
N Digit Largest Number: '777....(N) times'
Smallest Number: The smallest number in Octal number is ‘0‘. The idea is that the first digit needs to be as minimum as possible other than 0 which is ‘1’ and the remaining digits needs to be 0. Therefore:
1 Digit Smallest Number: '1'
2 Digit Smallest Number: '10'
3 Digit Smallest Number: '100'
.
.
.
N Digit Smallest Number: '100....(N - 1) times'
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find the largest// and smallest N-digit numbers// in Octal Number System #include <bits/stdc++.h>using namespace std; // Function to return the largest// N-digit number in Octal// Number Systemstring findLargest(int N){ // Append '7' N times string largest = string(N, '7'); return largest;} // Function to return the smallest// N-digit number in Octal// Number Systemstring findSmallest(int N){ // Append '0' (N - 1) times to 1 string smallest = "1" + string((N - 1), '0'); return smallest;} // Function to print the largest and// smallest N-digit Octal numbervoid printLargestSmallest(int N){ cout << "Largest: " << findLargest(N) << endl; cout << "Smallest: " << findSmallest(N) << endl;} // Driver codeint main(){ int N = 4; // Function Call printLargestSmallest(N); return 0;}
// Java program to find the largest// and smallest N-digit numbers// in Octal Number Systemclass GFG{ // Function to return the largest// N-digit number in Octal// Number Systemstatic String findLargest(int N){ // Append '7' N times String largest = strings(N, '7'); return largest;} // Function to return the smallest// N-digit number in Octal// Number Systemstatic String findSmallest(int N){ // Append '0' (N - 1) times to 1 String smallest = "1" + strings((N - 1), '0'); return smallest;} private static String strings(int N, char c) { String temp =""; for(int i= 0; i < N; i++) { temp+=c; } return temp;} // Function to print the largest and// smallest N-digit Octal numberstatic void printLargestSmallest(int N){ System.out.print("Largest: " + findLargest(N) +"\n"); System.out.print("Smallest: " + findSmallest(N) +"\n");} // Driver codepublic static void main(String[] args){ int N = 4; // Function Call printLargestSmallest(N);}} // This code is contributed by 29AjayKumar
# Python program to find the largest# and smallest N-digit numbers# in Octal Number System # Function to return the largest# N-digit number in Octal# Number Systemdef findLargest(N): # Append '7' N times largest = strings(N, '7'); return largest; # Function to return the smallest# N-digit number in Octal# Number Systemdef findSmallest(N): # Append '0' (N - 1) times to 1 smallest = "1" + strings((N - 1), '0'); return smallest; def strings(N, c): temp = ""; for i in range(N): temp += c; return temp; # Function to print the largest and# smallest N-digit Octal numberdef printLargestSmallest(N): print("Largest: ",findLargest(N)); print("Smallest: ",findSmallest(N)); # Driver codeif __name__ == '__main__': N = 4; # Function Call printLargestSmallest(N); # This code is contributed by sapnasingh4991
// C# program to find the largest// and smallest N-digit numbers// in Octal Number Systemusing System; class GFG{ // Function to return the largest// N-digit number in Octal// Number Systemstatic String findLargest(int N){ // Append '7' N times String largest = strings(N, '7'); return largest;} // Function to return the smallest// N-digit number in Octal// Number Systemstatic String findSmallest(int N){ // Append '0' (N - 1) times to 1 String smallest = "1" + strings((N - 1), '0'); return smallest;} private static String strings(int N, char c) { String temp =""; for(int i= 0; i < N; i++) { temp+=c; } return temp;} // Function to print the largest and// smallest N-digit Octal numberstatic void printLargestSmallest(int N){ Console.Write("Largest: " + findLargest(N) +"\n"); Console.Write("Smallest: " + findSmallest(N) +"\n");} // Driver codepublic static void Main(String[] args){ int N = 4; // Function Call printLargestSmallest(N);}} // This code is contributed by PrinciRaj1992
<script> // Javascript program to find the largest// and smallest N-digit numbers// in Octal Number System // Function to return the largest// N-digit number in Octal// Number Systemfunction findLargest(N){ // Append '7' N times var largest = new Array(N+1).join( '7' ); return largest;} // Function to return the smallest// N-digit number in Octal// Number Systemfunction findSmallest(N){ // Append '0' (N - 1) times to 1 var smallest = "1" + new Array(N).join( '0' ); return smallest;} // Function to print the largest and// smallest N-digit Octal numberfunction printLargestSmallest(N){ document.write("Largest: " + findLargest(N) + "<br>"); document.write( "Smallest: " + findSmallest(N));} // Driver codevar N = 4;// Function CallprintLargestSmallest(N); </script>
Largest: 7777
Smallest: 1000
Time Complexity: O(N) where N is the length of the string.
Auxiliary Space: O(1)
29AjayKumar
princiraj1992
sapnasingh4991
noob2000
nidhi_biet
rishavmahato348
number-digits
Numbers
Mathematical
Strings
Strings
Mathematical
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Nov, 2021"
},
{
"code": null,
"e": 133,
"s": 28,
"text": "Given an integer N, the task is to find the smallest and largest N-digit numbers in Octal Number System."
},
{
"code": null,
"e": 144,
"s": 133,
"text": "Examples: "
},
{
"code": null,
"e": 194,
"s": 144,
"text": "Input: N = 4 Output: Largest: 7777 Smallest: 1000"
},
{
"code": null,
"e": 241,
"s": 194,
"text": "Input: N = 2 Output: Largest: 77 Smallest: 10 "
},
{
"code": null,
"e": 321,
"s": 241,
"text": "Approach: The following steps can be followed to compute the required answer: "
},
{
"code": null,
"e": 471,
"s": 321,
"text": "Largest Number: To get the largest number, every digit of the number must be maximum. The maximum digit in the Octal number system is ‘7‘. Therefore:"
},
{
"code": null,
"e": 655,
"s": 471,
"text": "1 Digit Largest Number: '7'\n2 Digit Largest Number: '77'\n3 Digit Largest Number: '777'\n .\n .\n .\nN Digit Largest Number: '777....(N) times'"
},
{
"code": null,
"e": 861,
"s": 655,
"text": "Smallest Number: The smallest number in Octal number is ‘0‘. The idea is that the first digit needs to be as minimum as possible other than 0 which is ‘1’ and the remaining digits needs to be 0. Therefore:"
},
{
"code": null,
"e": 1053,
"s": 861,
"text": "1 Digit Smallest Number: '1'\n2 Digit Smallest Number: '10'\n3 Digit Smallest Number: '100'\n .\n .\n .\nN Digit Smallest Number: '100....(N - 1) times'"
},
{
"code": null,
"e": 1106,
"s": 1053,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1110,
"s": 1106,
"text": "C++"
},
{
"code": null,
"e": 1115,
"s": 1110,
"text": "Java"
},
{
"code": null,
"e": 1123,
"s": 1115,
"text": "Python3"
},
{
"code": null,
"e": 1126,
"s": 1123,
"text": "C#"
},
{
"code": null,
"e": 1137,
"s": 1126,
"text": "Javascript"
},
{
"code": "// C++ program to find the largest// and smallest N-digit numbers// in Octal Number System #include <bits/stdc++.h>using namespace std; // Function to return the largest// N-digit number in Octal// Number Systemstring findLargest(int N){ // Append '7' N times string largest = string(N, '7'); return largest;} // Function to return the smallest// N-digit number in Octal// Number Systemstring findSmallest(int N){ // Append '0' (N - 1) times to 1 string smallest = \"1\" + string((N - 1), '0'); return smallest;} // Function to print the largest and// smallest N-digit Octal numbervoid printLargestSmallest(int N){ cout << \"Largest: \" << findLargest(N) << endl; cout << \"Smallest: \" << findSmallest(N) << endl;} // Driver codeint main(){ int N = 4; // Function Call printLargestSmallest(N); return 0;}",
"e": 2009,
"s": 1137,
"text": null
},
{
"code": "// Java program to find the largest// and smallest N-digit numbers// in Octal Number Systemclass GFG{ // Function to return the largest// N-digit number in Octal// Number Systemstatic String findLargest(int N){ // Append '7' N times String largest = strings(N, '7'); return largest;} // Function to return the smallest// N-digit number in Octal// Number Systemstatic String findSmallest(int N){ // Append '0' (N - 1) times to 1 String smallest = \"1\" + strings((N - 1), '0'); return smallest;} private static String strings(int N, char c) { String temp =\"\"; for(int i= 0; i < N; i++) { temp+=c; } return temp;} // Function to print the largest and// smallest N-digit Octal numberstatic void printLargestSmallest(int N){ System.out.print(\"Largest: \" + findLargest(N) +\"\\n\"); System.out.print(\"Smallest: \" + findSmallest(N) +\"\\n\");} // Driver codepublic static void main(String[] args){ int N = 4; // Function Call printLargestSmallest(N);}} // This code is contributed by 29AjayKumar",
"e": 3085,
"s": 2009,
"text": null
},
{
"code": "# Python program to find the largest# and smallest N-digit numbers# in Octal Number System # Function to return the largest# N-digit number in Octal# Number Systemdef findLargest(N): # Append '7' N times largest = strings(N, '7'); return largest; # Function to return the smallest# N-digit number in Octal# Number Systemdef findSmallest(N): # Append '0' (N - 1) times to 1 smallest = \"1\" + strings((N - 1), '0'); return smallest; def strings(N, c): temp = \"\"; for i in range(N): temp += c; return temp; # Function to print the largest and# smallest N-digit Octal numberdef printLargestSmallest(N): print(\"Largest: \",findLargest(N)); print(\"Smallest: \",findSmallest(N)); # Driver codeif __name__ == '__main__': N = 4; # Function Call printLargestSmallest(N); # This code is contributed by sapnasingh4991",
"e": 3940,
"s": 3085,
"text": null
},
{
"code": "// C# program to find the largest// and smallest N-digit numbers// in Octal Number Systemusing System; class GFG{ // Function to return the largest// N-digit number in Octal// Number Systemstatic String findLargest(int N){ // Append '7' N times String largest = strings(N, '7'); return largest;} // Function to return the smallest// N-digit number in Octal// Number Systemstatic String findSmallest(int N){ // Append '0' (N - 1) times to 1 String smallest = \"1\" + strings((N - 1), '0'); return smallest;} private static String strings(int N, char c) { String temp =\"\"; for(int i= 0; i < N; i++) { temp+=c; } return temp;} // Function to print the largest and// smallest N-digit Octal numberstatic void printLargestSmallest(int N){ Console.Write(\"Largest: \" + findLargest(N) +\"\\n\"); Console.Write(\"Smallest: \" + findSmallest(N) +\"\\n\");} // Driver codepublic static void Main(String[] args){ int N = 4; // Function Call printLargestSmallest(N);}} // This code is contributed by PrinciRaj1992",
"e": 5032,
"s": 3940,
"text": null
},
{
"code": "<script> // Javascript program to find the largest// and smallest N-digit numbers// in Octal Number System // Function to return the largest// N-digit number in Octal// Number Systemfunction findLargest(N){ // Append '7' N times var largest = new Array(N+1).join( '7' ); return largest;} // Function to return the smallest// N-digit number in Octal// Number Systemfunction findSmallest(N){ // Append '0' (N - 1) times to 1 var smallest = \"1\" + new Array(N).join( '0' ); return smallest;} // Function to print the largest and// smallest N-digit Octal numberfunction printLargestSmallest(N){ document.write(\"Largest: \" + findLargest(N) + \"<br>\"); document.write( \"Smallest: \" + findSmallest(N));} // Driver codevar N = 4;// Function CallprintLargestSmallest(N); </script>",
"e": 5860,
"s": 5032,
"text": null
},
{
"code": null,
"e": 5889,
"s": 5860,
"text": "Largest: 7777\nSmallest: 1000"
},
{
"code": null,
"e": 5950,
"s": 5891,
"text": "Time Complexity: O(N) where N is the length of the string."
},
{
"code": null,
"e": 5973,
"s": 5950,
"text": "Auxiliary Space: O(1) "
},
{
"code": null,
"e": 5985,
"s": 5973,
"text": "29AjayKumar"
},
{
"code": null,
"e": 5999,
"s": 5985,
"text": "princiraj1992"
},
{
"code": null,
"e": 6014,
"s": 5999,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 6023,
"s": 6014,
"text": "noob2000"
},
{
"code": null,
"e": 6034,
"s": 6023,
"text": "nidhi_biet"
},
{
"code": null,
"e": 6050,
"s": 6034,
"text": "rishavmahato348"
},
{
"code": null,
"e": 6064,
"s": 6050,
"text": "number-digits"
},
{
"code": null,
"e": 6072,
"s": 6064,
"text": "Numbers"
},
{
"code": null,
"e": 6085,
"s": 6072,
"text": "Mathematical"
},
{
"code": null,
"e": 6093,
"s": 6085,
"text": "Strings"
},
{
"code": null,
"e": 6101,
"s": 6093,
"text": "Strings"
},
{
"code": null,
"e": 6114,
"s": 6101,
"text": "Mathematical"
},
{
"code": null,
"e": 6122,
"s": 6114,
"text": "Numbers"
}
] |
Python | Pandas Timestamp.isoformat
|
14 Jan, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Timestamp.isoformat() function is used to convert the given Timestamp object into the ISO format.
Syntax :Timestamp.isoformat()
Parameters : None
Return : date time as a string
Example #1: Use Timestamp.isoformat() function to convert the date in the given Timestamp object to ISO format.
# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2011, month = 11, day = 21, hour = 10, second = 49, tz = 'US/Central') # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.isoformat() function to convert the date in the given Timestamp object to ISO format.
# convert to ISO formatts.isoformat()
Output :
As we can see in the output, the Timestamp.isoformat() function has returned the date in the ISO format.
Example #2: Use Timestamp.isoformat() function to convert the date in the given Timestamp object to ISO format.
# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31, hour = 4, second = 49, tz = 'Europe/Berlin') # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.isoformat() function to convert the date in the given Timestamp object to ISO format.
# convert to ISO formatts.isoformat()
Output :
As we can see in the output, the Timestamp.isoformat() function has returned the date in the ISO format.
Python Pandas-Timestamp
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Jan, 2019"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 347,
"s": 242,
"text": "Pandas Timestamp.isoformat() function is used to convert the given Timestamp object into the ISO format."
},
{
"code": null,
"e": 377,
"s": 347,
"text": "Syntax :Timestamp.isoformat()"
},
{
"code": null,
"e": 395,
"s": 377,
"text": "Parameters : None"
},
{
"code": null,
"e": 426,
"s": 395,
"text": "Return : date time as a string"
},
{
"code": null,
"e": 538,
"s": 426,
"text": "Example #1: Use Timestamp.isoformat() function to convert the date in the given Timestamp object to ISO format."
},
{
"code": "# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2011, month = 11, day = 21, hour = 10, second = 49, tz = 'US/Central') # Print the Timestamp objectprint(ts)",
"e": 765,
"s": 538,
"text": null
},
{
"code": null,
"e": 774,
"s": 765,
"text": "Output :"
},
{
"code": null,
"e": 890,
"s": 774,
"text": "Now we will use the Timestamp.isoformat() function to convert the date in the given Timestamp object to ISO format."
},
{
"code": "# convert to ISO formatts.isoformat()",
"e": 928,
"s": 890,
"text": null
},
{
"code": null,
"e": 937,
"s": 928,
"text": "Output :"
},
{
"code": null,
"e": 1042,
"s": 937,
"text": "As we can see in the output, the Timestamp.isoformat() function has returned the date in the ISO format."
},
{
"code": null,
"e": 1154,
"s": 1042,
"text": "Example #2: Use Timestamp.isoformat() function to convert the date in the given Timestamp object to ISO format."
},
{
"code": "# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31, hour = 4, second = 49, tz = 'Europe/Berlin') # Print the Timestamp objectprint(ts)",
"e": 1381,
"s": 1154,
"text": null
},
{
"code": null,
"e": 1390,
"s": 1381,
"text": "Output :"
},
{
"code": null,
"e": 1506,
"s": 1390,
"text": "Now we will use the Timestamp.isoformat() function to convert the date in the given Timestamp object to ISO format."
},
{
"code": "# convert to ISO formatts.isoformat()",
"e": 1544,
"s": 1506,
"text": null
},
{
"code": null,
"e": 1553,
"s": 1544,
"text": "Output :"
},
{
"code": null,
"e": 1658,
"s": 1553,
"text": "As we can see in the output, the Timestamp.isoformat() function has returned the date in the ISO format."
},
{
"code": null,
"e": 1682,
"s": 1658,
"text": "Python Pandas-Timestamp"
},
{
"code": null,
"e": 1696,
"s": 1682,
"text": "Python-pandas"
},
{
"code": null,
"e": 1703,
"s": 1696,
"text": "Python"
}
] |
C# Program to Find Binary Equivalent of an Integer using Recursion - GeeksforGeeks
|
18 Oct, 2021
Given an integer number, now we convert the given integer number into a binary number using recursion. Recursion is a method in which a function calls itself directly or indirectly and such type of function is known as a recursive function. It solves the problem very efficiently like we find the binary equivalent of an integer.
Examples:
Input : 10
Output: 1010
Input : 11
Output: 1011
Approach:
To display the binary equivalent of an integer we use the following steps:
If condition is used to check if the given value is not equal to zero.
If the given condition is true then perform the modulus of the val by 2, then add the modulus result to 10 and then multiply the value of the result with the value of decimaltobinary() function.
Now repeat step 2 until the value of val variable is greater than zero.
Print the array in reverse order now.
And if the condition is false then it will execute the else section, i.e., return 0
The below image can help you better understand the approach.
Let us considered the integer number is 10. Now we find the binary equivalent of 10 so,
10 % 2 + 10 * (10 / 2) % 2 will return 0
5 % 2 + 10 * (5 / 2) % 2 will return 1
2 % 2 + 10 * (2 / 2) % 2 will return 0
1 % 2 + 10 * (1 / 2) % 2 will return 1
So the final result is 1010.
Example 1:
C#
// C# program to display the binary equivalent// of an integerusing System; class GFG{ // Driver codepublic static void Main(string[] args){ // Input int num = 15; decimaltobinary(num);} // Function to display the binary equivalent // of an integerpublic static int decimaltobinary(int val){ int binary; if (val != 0) { binary = (val % 2) + 10 * decimaltobinary(val / 2); Console.Write(binary); return 0; } else { return 0; }}}
1111
Example 2:
C#
// C# program to display the binary equivalent// of an integerusing System; class GFG{ // Function to display the binary equivalent // of an integerpublic static int decimaltobinary(int val){ int binary; if (val != 0) { binary = (val % 2) + 10 * decimaltobinary(val / 2); Console.Write(binary); return 0; } else { return 0; }} // Driver codepublic static void Main(string[] args){ int num; // Reading input from user Console.Write("Hi! Enter the number:"); num = int.Parse(Console.ReadLine()); decimaltobinary(num); }}
Output:
Hi! Enter the number:10
1010
CSharp LINQ
CSharp-programs
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
Partial Classes in C#
C# | Inheritance
C# | Generics - Introduction
Switch Statement in C#
Top 50 C# Interview Questions & Answers
Lambda Expressions in C#
C# | How to insert an element in an Array?
Convert String to Character Array in C#
|
[
{
"code": null,
"e": 26098,
"s": 26070,
"text": "\n18 Oct, 2021"
},
{
"code": null,
"e": 26428,
"s": 26098,
"text": "Given an integer number, now we convert the given integer number into a binary number using recursion. Recursion is a method in which a function calls itself directly or indirectly and such type of function is known as a recursive function. It solves the problem very efficiently like we find the binary equivalent of an integer."
},
{
"code": null,
"e": 26438,
"s": 26428,
"text": "Examples:"
},
{
"code": null,
"e": 26487,
"s": 26438,
"text": "Input : 10\nOutput: 1010\n\nInput : 11\nOutput: 1011"
},
{
"code": null,
"e": 26498,
"s": 26487,
"text": "Approach: "
},
{
"code": null,
"e": 26573,
"s": 26498,
"text": "To display the binary equivalent of an integer we use the following steps:"
},
{
"code": null,
"e": 26644,
"s": 26573,
"text": "If condition is used to check if the given value is not equal to zero."
},
{
"code": null,
"e": 26839,
"s": 26644,
"text": "If the given condition is true then perform the modulus of the val by 2, then add the modulus result to 10 and then multiply the value of the result with the value of decimaltobinary() function."
},
{
"code": null,
"e": 26911,
"s": 26839,
"text": "Now repeat step 2 until the value of val variable is greater than zero."
},
{
"code": null,
"e": 26949,
"s": 26911,
"text": "Print the array in reverse order now."
},
{
"code": null,
"e": 27033,
"s": 26949,
"text": "And if the condition is false then it will execute the else section, i.e., return 0"
},
{
"code": null,
"e": 27094,
"s": 27033,
"text": "The below image can help you better understand the approach."
},
{
"code": null,
"e": 27182,
"s": 27094,
"text": "Let us considered the integer number is 10. Now we find the binary equivalent of 10 so,"
},
{
"code": null,
"e": 27223,
"s": 27182,
"text": "10 % 2 + 10 * (10 / 2) % 2 will return 0"
},
{
"code": null,
"e": 27262,
"s": 27223,
"text": "5 % 2 + 10 * (5 / 2) % 2 will return 1"
},
{
"code": null,
"e": 27301,
"s": 27262,
"text": "2 % 2 + 10 * (2 / 2) % 2 will return 0"
},
{
"code": null,
"e": 27340,
"s": 27301,
"text": "1 % 2 + 10 * (1 / 2) % 2 will return 1"
},
{
"code": null,
"e": 27369,
"s": 27340,
"text": "So the final result is 1010."
},
{
"code": null,
"e": 27380,
"s": 27369,
"text": "Example 1:"
},
{
"code": null,
"e": 27383,
"s": 27380,
"text": "C#"
},
{
"code": "// C# program to display the binary equivalent// of an integerusing System; class GFG{ // Driver codepublic static void Main(string[] args){ // Input int num = 15; decimaltobinary(num);} // Function to display the binary equivalent // of an integerpublic static int decimaltobinary(int val){ int binary; if (val != 0) { binary = (val % 2) + 10 * decimaltobinary(val / 2); Console.Write(binary); return 0; } else { return 0; }}}",
"e": 27890,
"s": 27383,
"text": null
},
{
"code": null,
"e": 27895,
"s": 27890,
"text": "1111"
},
{
"code": null,
"e": 27906,
"s": 27895,
"text": "Example 2:"
},
{
"code": null,
"e": 27909,
"s": 27906,
"text": "C#"
},
{
"code": "// C# program to display the binary equivalent// of an integerusing System; class GFG{ // Function to display the binary equivalent // of an integerpublic static int decimaltobinary(int val){ int binary; if (val != 0) { binary = (val % 2) + 10 * decimaltobinary(val / 2); Console.Write(binary); return 0; } else { return 0; }} // Driver codepublic static void Main(string[] args){ int num; // Reading input from user Console.Write(\"Hi! Enter the number:\"); num = int.Parse(Console.ReadLine()); decimaltobinary(num); }}",
"e": 28512,
"s": 27909,
"text": null
},
{
"code": null,
"e": 28520,
"s": 28512,
"text": "Output:"
},
{
"code": null,
"e": 28549,
"s": 28520,
"text": "Hi! Enter the number:10\n1010"
},
{
"code": null,
"e": 28561,
"s": 28549,
"text": "CSharp LINQ"
},
{
"code": null,
"e": 28577,
"s": 28561,
"text": "CSharp-programs"
},
{
"code": null,
"e": 28584,
"s": 28577,
"text": "Picked"
},
{
"code": null,
"e": 28587,
"s": 28584,
"text": "C#"
},
{
"code": null,
"e": 28685,
"s": 28587,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28708,
"s": 28685,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28736,
"s": 28708,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 28758,
"s": 28736,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 28775,
"s": 28758,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 28804,
"s": 28775,
"text": "C# | Generics - Introduction"
},
{
"code": null,
"e": 28827,
"s": 28804,
"text": "Switch Statement in C#"
},
{
"code": null,
"e": 28867,
"s": 28827,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 28892,
"s": 28867,
"text": "Lambda Expressions in C#"
},
{
"code": null,
"e": 28935,
"s": 28892,
"text": "C# | How to insert an element in an Array?"
}
] |
Google’s Open Images: Now easier to download and evaluate with FiftyOne | by Eric Hofesmann | Towards Data Science
|
Google’s Open Images is a behemoth of a dataset. With over 9 million images, 80 million annotations, and 600 classes spanning multiple tasks, it stands to be one of the leading datasets in the computer vision community.
Working with Open Images is now easier than ever with the its integration into the open-source ML developer tool, FiftyOne.
Computer vision models have become more data-hungry than ever before. Developing your own model requires you to either collect and annotate massive amounts of data yourself or turn to public datasets hoping that they contain relevant data for your task. The team behind Open Images set out to provide a massive data lake for anyone to access. By only curating images under a Creative Commons Attribution (CC-BY) license, Open Images can be used by anyone who is interested.
With image-level labels, segmentations, visual relationships, localized narratives, and 15x more object detections than the next largest detection dataset, Open Images can be tempting to add to your data lake and training workflows. However, learning and incorporating a new dataset format into your workflow is often tedious and time-consuming. Previously, the procedure to download Open Images consisted of writing custom scripts to download and parse the images and labels you want. This has spawned multiple tools to aid in loading the dataset, but they each have serious drawbacks like not supporting segmentations and relationships, no visualization capabilities, and not being able to specify the download format.
At Voxel51, we have collaborated with Google to create an easy-to-use source for downloading Open Images by incorporating it into the Dataset Zoo of our open-source ML tool, FiftyOne. With FiftyOne, you can specify exactly the subset of Open Images you want to download, export it into dozens of different formats, visualize it in the FiftyOne App, and even evaluate your models with Open Images-style object detection evaluation.
This blog post walks you through how to use FiftyOne to:
Download Open Images
Export Open Images in a different dataset format
Evaluate an object detection model with Open Images-style evaluation
Before we begin, make sure to install FiftyOne:
pip install fiftyone
You can run the examples in this blog post directly in your browser in this Google Colab notebook. Follow the link and click “Run in Google Colab”.
It now only takes one command or one line of Python code to download exactly the samples you want from Open Images. You can then explore the dataset in the FiftyOne App with one more line of code.
The integration of Open Images into FiftyOne provides multiple parameters that you can use to specify exactly which and how many samples you want to download:
label_types: a list of types of labels to load. Values are ("detections", "classifications", "relationships", "segmentations"). By default, all labels are loaded but not every sample will include each label type. If max_samples and label_types are both specified, then every sample will include the specified label types.
split and splits: either a string or list of strings dictating the splits to load. Available splits are ("test", "train", "validation").
classes: a list of strings specifying required classes to load. Only samples containing at least one instance of a specified class will be downloaded.
attrs: a list of strings for relationship attributes to load. This parameter is only useful if "relationships" is in label_types.
max_samples: a maximum number of samples to import. By default, all samples are imported.
shuffle: boolean dictating whether to randomly shuffle the order in which the samples are imported.
seed: a random seed to use when shuffling.
image_ids: a list of specific image IDs to load. The IDs can be specified either as <split>/<image-id> or <image-id>
image_ids_file: the path to a newline-separated .txt, .json, or .csv file containing a list of image IDs to load. The IDs can be specified either as <split>/<image-id> or <image-id>. If image_ids is provided, this parameter is ignored
Some of these parameters allow you to specify specific classes and attributes that you want in your subset. You can use the following commands to see the list of options available in Open Images:
Putting this functionality to use, we can curate datasets for specific tasks without needing to download the entire dataset or parse any raw annotation files. For example, if we wanted to train a detector for wooden objects, we can specify that we only want samples from Open Images containing an object with the visual relationship annotated as Wooden:
As another example, let’s build a dataset for detecting cats and dogs. We can get both detections as well as the image-level classifications for the classes Dog and Cat:
When working with a dataset containing object detections, FiftyOne lets you create a patches view wherein every sample contains a single object. This can be extremely useful when attempting to analyze specific object classes or attributes, especially in cluttered scenes.
For years, the COCO dataset has been the most prominent object detection dataset resulting in a sizable percentage of the computer vision (CV) community adopting the COCO format for their object detection problems. Choosing a dataset format for a project dictates the parsers needed to load and work with your dataset, making it difficult to work with new data in a different format. FiftyOne lets you export datasets into dozens of different formats letting you integrate it easily into existing workflows.
For example, you can export into formats like COCO, Pascal VOC, CVAT, YOLO, TFRecords, directory trees for classifications, and more. Many of these formats also support exporting segmentation masks.
In practice, exporting the subset of Open Images that we loaded previously to disk in COCO format is as easy as:
If you then want to import your data back into FiftyOne and the dataset follows one of the supported formats, that can also be done in one line of code:
Even if your dataset is in a completely custom format, it is still easy to load it into FiftyOne.
FiftyOne not only makes it easy to load and export Open Images and custom datasets, but it also lets you visualize your data and evaluate model results.
Open Images-style object detection evaluation was created for the Open Images challenges. It differs from COCO-style evaluation in a few notable ways:
Image-level labels dictate which object classes are evaluated in each image. If a class was predicted but not annotated as a positive or negative image-level label, it is ignored.
A semantic class hierarchy is used to expand predicted and ground truth object lists to include and evaluate all parent classes. By default, the ground truth detections only include leaf classes and must be expanded before evaluation takes place. This is performed automatically in FiftyOne.
Like COCO, “crowd” ground truth detections are able to be matched with multiple predictions. But unlike COCO, only one prediction will count as a true positive per crowd.
COCO-style evaluation averages AP over a sweep of 10 different IoU values, Open Images-style evaluation only uses an IoU of 0.5 to compute mAP.
Click these links if you want to see the detailed steps for the evaluation protocol for Open Images-style evaluation or COCO-style evaluation.
In order to try out Open Images-style evaluation, we can use a model from the FiftyOne Model Zoo to generate detection predictions on the cat and dog subset of Open Images we downloaded. We will add a new predictions field to the dataset:
Note: Running this model requires TensorFlow 1.14.
pip install tensorflow==1.14
For this example, we are only interested in predictions for the classes “Cat” and “Dog”, so we can utilize the flexible dataset representations of FiftyOne to create a view into the dataset containing only those classes. Additionally, the model we ran was trained on COCO which uses lower-case class names so we will need to remap them to match the upper-case class names of Open Images:
We can now run Open Images-style evaluation on our dataset and predictions:
The results object that is returned contains everything we need from mAP, to PR curves, to confusion matrices.
It should be noted that by default, these detection protocols will only match predicted objects to ground truth objects of the same class. That means that if we want an interesting confusion matrix, we will need to evaluate with the parameter classwise equal to False :
We can now view an interactive confusion matrix where if we click on a cell, the FiftyOne App will be updated showing only samples existing in that cell. So, for example, if we click on the cell containing ground truth “Dog” detections matched with predicted “Cat” detections, we can gain insight into the failure modes of our model:
Note: Interactive plots are currently only supported in Jupyter Notebooks. Support for other environments will be added soon.
When evaluating an object detection dataset in FiftyOne, after running evaluate_detections and storing the results on the dataset with an eval_key , we are then able to create what is called an evaluation view. This is a view into the dataset where every sample is an individual ground truth or predicted object patch allowing you to sort by true positives, false positives, and false negatives, the IoU of matches, and other evaluation metadata at the click of a button.
If we want to get an even more nuanced understanding of our model, it can be useful to visualize object embeddings in a low-dimensional space allowing us to quickly pick out patterns, clusters, and anomalies in our data. The FiftyOne Brain provides exactly this kind of workflow.
Note: The default dimensionality reduction method used by the Brain is umap which we need to install:
pip install umap-learn
We can again use the FiftyOne Model Zoo to generate embeddings that we will then visualize:
This kind of visualization can be invaluable for a multitude of reasons, but especially for datasets like Open Images that contain machine-generated labels. Visualizing and interactively exploring embeddings lets you quickly spot-check which machine-generated labels may need to be reviewed and sent off for reannotation.
We can also use these embeddings to automatically find similar and duplicate samples with the click of a button.
Once we have thoroughly explored our dataset and found aspects of it that we want to analyze further or improve, it is easy to tag individual samples or labels in order to isolate them for downstream use cases.
Open Images is a massive yet thoroughly labeled dataset that can make a useful addition to your data lake and model training workflows. The easiest way to download and explore Open Images is with FiftyOne. With datasets as large as Open Images, hands-on evaluation of your model results can be difficult. FiftyOne makes it easy to understand your dataset, find failure modes in your model, and reveal patterns in your data by visualizing embeddings.
Headquartered in Ann Arbor, Michigan, and founded in 2016 by Dr. Jason Corso and Dr. Brian Moore, Voxel51 is an AI software company that is democratizing access to software 2.0 by providing the open core software building blocks that enable computer vision and machine learning engineers to rapidly engineer data-powered workflows.
Want to learn more? Check us out at fiftyone.ai.
|
[
{
"code": null,
"e": 392,
"s": 172,
"text": "Google’s Open Images is a behemoth of a dataset. With over 9 million images, 80 million annotations, and 600 classes spanning multiple tasks, it stands to be one of the leading datasets in the computer vision community."
},
{
"code": null,
"e": 516,
"s": 392,
"text": "Working with Open Images is now easier than ever with the its integration into the open-source ML developer tool, FiftyOne."
},
{
"code": null,
"e": 990,
"s": 516,
"text": "Computer vision models have become more data-hungry than ever before. Developing your own model requires you to either collect and annotate massive amounts of data yourself or turn to public datasets hoping that they contain relevant data for your task. The team behind Open Images set out to provide a massive data lake for anyone to access. By only curating images under a Creative Commons Attribution (CC-BY) license, Open Images can be used by anyone who is interested."
},
{
"code": null,
"e": 1711,
"s": 990,
"text": "With image-level labels, segmentations, visual relationships, localized narratives, and 15x more object detections than the next largest detection dataset, Open Images can be tempting to add to your data lake and training workflows. However, learning and incorporating a new dataset format into your workflow is often tedious and time-consuming. Previously, the procedure to download Open Images consisted of writing custom scripts to download and parse the images and labels you want. This has spawned multiple tools to aid in loading the dataset, but they each have serious drawbacks like not supporting segmentations and relationships, no visualization capabilities, and not being able to specify the download format."
},
{
"code": null,
"e": 2142,
"s": 1711,
"text": "At Voxel51, we have collaborated with Google to create an easy-to-use source for downloading Open Images by incorporating it into the Dataset Zoo of our open-source ML tool, FiftyOne. With FiftyOne, you can specify exactly the subset of Open Images you want to download, export it into dozens of different formats, visualize it in the FiftyOne App, and even evaluate your models with Open Images-style object detection evaluation."
},
{
"code": null,
"e": 2199,
"s": 2142,
"text": "This blog post walks you through how to use FiftyOne to:"
},
{
"code": null,
"e": 2220,
"s": 2199,
"text": "Download Open Images"
},
{
"code": null,
"e": 2269,
"s": 2220,
"text": "Export Open Images in a different dataset format"
},
{
"code": null,
"e": 2338,
"s": 2269,
"text": "Evaluate an object detection model with Open Images-style evaluation"
},
{
"code": null,
"e": 2386,
"s": 2338,
"text": "Before we begin, make sure to install FiftyOne:"
},
{
"code": null,
"e": 2407,
"s": 2386,
"text": "pip install fiftyone"
},
{
"code": null,
"e": 2555,
"s": 2407,
"text": "You can run the examples in this blog post directly in your browser in this Google Colab notebook. Follow the link and click “Run in Google Colab”."
},
{
"code": null,
"e": 2752,
"s": 2555,
"text": "It now only takes one command or one line of Python code to download exactly the samples you want from Open Images. You can then explore the dataset in the FiftyOne App with one more line of code."
},
{
"code": null,
"e": 2911,
"s": 2752,
"text": "The integration of Open Images into FiftyOne provides multiple parameters that you can use to specify exactly which and how many samples you want to download:"
},
{
"code": null,
"e": 3233,
"s": 2911,
"text": "label_types: a list of types of labels to load. Values are (\"detections\", \"classifications\", \"relationships\", \"segmentations\"). By default, all labels are loaded but not every sample will include each label type. If max_samples and label_types are both specified, then every sample will include the specified label types."
},
{
"code": null,
"e": 3370,
"s": 3233,
"text": "split and splits: either a string or list of strings dictating the splits to load. Available splits are (\"test\", \"train\", \"validation\")."
},
{
"code": null,
"e": 3521,
"s": 3370,
"text": "classes: a list of strings specifying required classes to load. Only samples containing at least one instance of a specified class will be downloaded."
},
{
"code": null,
"e": 3651,
"s": 3521,
"text": "attrs: a list of strings for relationship attributes to load. This parameter is only useful if \"relationships\" is in label_types."
},
{
"code": null,
"e": 3741,
"s": 3651,
"text": "max_samples: a maximum number of samples to import. By default, all samples are imported."
},
{
"code": null,
"e": 3841,
"s": 3741,
"text": "shuffle: boolean dictating whether to randomly shuffle the order in which the samples are imported."
},
{
"code": null,
"e": 3884,
"s": 3841,
"text": "seed: a random seed to use when shuffling."
},
{
"code": null,
"e": 4001,
"s": 3884,
"text": "image_ids: a list of specific image IDs to load. The IDs can be specified either as <split>/<image-id> or <image-id>"
},
{
"code": null,
"e": 4236,
"s": 4001,
"text": "image_ids_file: the path to a newline-separated .txt, .json, or .csv file containing a list of image IDs to load. The IDs can be specified either as <split>/<image-id> or <image-id>. If image_ids is provided, this parameter is ignored"
},
{
"code": null,
"e": 4432,
"s": 4236,
"text": "Some of these parameters allow you to specify specific classes and attributes that you want in your subset. You can use the following commands to see the list of options available in Open Images:"
},
{
"code": null,
"e": 4786,
"s": 4432,
"text": "Putting this functionality to use, we can curate datasets for specific tasks without needing to download the entire dataset or parse any raw annotation files. For example, if we wanted to train a detector for wooden objects, we can specify that we only want samples from Open Images containing an object with the visual relationship annotated as Wooden:"
},
{
"code": null,
"e": 4956,
"s": 4786,
"text": "As another example, let’s build a dataset for detecting cats and dogs. We can get both detections as well as the image-level classifications for the classes Dog and Cat:"
},
{
"code": null,
"e": 5228,
"s": 4956,
"text": "When working with a dataset containing object detections, FiftyOne lets you create a patches view wherein every sample contains a single object. This can be extremely useful when attempting to analyze specific object classes or attributes, especially in cluttered scenes."
},
{
"code": null,
"e": 5736,
"s": 5228,
"text": "For years, the COCO dataset has been the most prominent object detection dataset resulting in a sizable percentage of the computer vision (CV) community adopting the COCO format for their object detection problems. Choosing a dataset format for a project dictates the parsers needed to load and work with your dataset, making it difficult to work with new data in a different format. FiftyOne lets you export datasets into dozens of different formats letting you integrate it easily into existing workflows."
},
{
"code": null,
"e": 5935,
"s": 5736,
"text": "For example, you can export into formats like COCO, Pascal VOC, CVAT, YOLO, TFRecords, directory trees for classifications, and more. Many of these formats also support exporting segmentation masks."
},
{
"code": null,
"e": 6048,
"s": 5935,
"text": "In practice, exporting the subset of Open Images that we loaded previously to disk in COCO format is as easy as:"
},
{
"code": null,
"e": 6201,
"s": 6048,
"text": "If you then want to import your data back into FiftyOne and the dataset follows one of the supported formats, that can also be done in one line of code:"
},
{
"code": null,
"e": 6299,
"s": 6201,
"text": "Even if your dataset is in a completely custom format, it is still easy to load it into FiftyOne."
},
{
"code": null,
"e": 6452,
"s": 6299,
"text": "FiftyOne not only makes it easy to load and export Open Images and custom datasets, but it also lets you visualize your data and evaluate model results."
},
{
"code": null,
"e": 6603,
"s": 6452,
"text": "Open Images-style object detection evaluation was created for the Open Images challenges. It differs from COCO-style evaluation in a few notable ways:"
},
{
"code": null,
"e": 6783,
"s": 6603,
"text": "Image-level labels dictate which object classes are evaluated in each image. If a class was predicted but not annotated as a positive or negative image-level label, it is ignored."
},
{
"code": null,
"e": 7075,
"s": 6783,
"text": "A semantic class hierarchy is used to expand predicted and ground truth object lists to include and evaluate all parent classes. By default, the ground truth detections only include leaf classes and must be expanded before evaluation takes place. This is performed automatically in FiftyOne."
},
{
"code": null,
"e": 7246,
"s": 7075,
"text": "Like COCO, “crowd” ground truth detections are able to be matched with multiple predictions. But unlike COCO, only one prediction will count as a true positive per crowd."
},
{
"code": null,
"e": 7390,
"s": 7246,
"text": "COCO-style evaluation averages AP over a sweep of 10 different IoU values, Open Images-style evaluation only uses an IoU of 0.5 to compute mAP."
},
{
"code": null,
"e": 7533,
"s": 7390,
"text": "Click these links if you want to see the detailed steps for the evaluation protocol for Open Images-style evaluation or COCO-style evaluation."
},
{
"code": null,
"e": 7772,
"s": 7533,
"text": "In order to try out Open Images-style evaluation, we can use a model from the FiftyOne Model Zoo to generate detection predictions on the cat and dog subset of Open Images we downloaded. We will add a new predictions field to the dataset:"
},
{
"code": null,
"e": 7823,
"s": 7772,
"text": "Note: Running this model requires TensorFlow 1.14."
},
{
"code": null,
"e": 7852,
"s": 7823,
"text": "pip install tensorflow==1.14"
},
{
"code": null,
"e": 8240,
"s": 7852,
"text": "For this example, we are only interested in predictions for the classes “Cat” and “Dog”, so we can utilize the flexible dataset representations of FiftyOne to create a view into the dataset containing only those classes. Additionally, the model we ran was trained on COCO which uses lower-case class names so we will need to remap them to match the upper-case class names of Open Images:"
},
{
"code": null,
"e": 8316,
"s": 8240,
"text": "We can now run Open Images-style evaluation on our dataset and predictions:"
},
{
"code": null,
"e": 8427,
"s": 8316,
"text": "The results object that is returned contains everything we need from mAP, to PR curves, to confusion matrices."
},
{
"code": null,
"e": 8697,
"s": 8427,
"text": "It should be noted that by default, these detection protocols will only match predicted objects to ground truth objects of the same class. That means that if we want an interesting confusion matrix, we will need to evaluate with the parameter classwise equal to False :"
},
{
"code": null,
"e": 9031,
"s": 8697,
"text": "We can now view an interactive confusion matrix where if we click on a cell, the FiftyOne App will be updated showing only samples existing in that cell. So, for example, if we click on the cell containing ground truth “Dog” detections matched with predicted “Cat” detections, we can gain insight into the failure modes of our model:"
},
{
"code": null,
"e": 9157,
"s": 9031,
"text": "Note: Interactive plots are currently only supported in Jupyter Notebooks. Support for other environments will be added soon."
},
{
"code": null,
"e": 9629,
"s": 9157,
"text": "When evaluating an object detection dataset in FiftyOne, after running evaluate_detections and storing the results on the dataset with an eval_key , we are then able to create what is called an evaluation view. This is a view into the dataset where every sample is an individual ground truth or predicted object patch allowing you to sort by true positives, false positives, and false negatives, the IoU of matches, and other evaluation metadata at the click of a button."
},
{
"code": null,
"e": 9909,
"s": 9629,
"text": "If we want to get an even more nuanced understanding of our model, it can be useful to visualize object embeddings in a low-dimensional space allowing us to quickly pick out patterns, clusters, and anomalies in our data. The FiftyOne Brain provides exactly this kind of workflow."
},
{
"code": null,
"e": 10011,
"s": 9909,
"text": "Note: The default dimensionality reduction method used by the Brain is umap which we need to install:"
},
{
"code": null,
"e": 10034,
"s": 10011,
"text": "pip install umap-learn"
},
{
"code": null,
"e": 10126,
"s": 10034,
"text": "We can again use the FiftyOne Model Zoo to generate embeddings that we will then visualize:"
},
{
"code": null,
"e": 10448,
"s": 10126,
"text": "This kind of visualization can be invaluable for a multitude of reasons, but especially for datasets like Open Images that contain machine-generated labels. Visualizing and interactively exploring embeddings lets you quickly spot-check which machine-generated labels may need to be reviewed and sent off for reannotation."
},
{
"code": null,
"e": 10561,
"s": 10448,
"text": "We can also use these embeddings to automatically find similar and duplicate samples with the click of a button."
},
{
"code": null,
"e": 10772,
"s": 10561,
"text": "Once we have thoroughly explored our dataset and found aspects of it that we want to analyze further or improve, it is easy to tag individual samples or labels in order to isolate them for downstream use cases."
},
{
"code": null,
"e": 11222,
"s": 10772,
"text": "Open Images is a massive yet thoroughly labeled dataset that can make a useful addition to your data lake and model training workflows. The easiest way to download and explore Open Images is with FiftyOne. With datasets as large as Open Images, hands-on evaluation of your model results can be difficult. FiftyOne makes it easy to understand your dataset, find failure modes in your model, and reveal patterns in your data by visualizing embeddings."
},
{
"code": null,
"e": 11554,
"s": 11222,
"text": "Headquartered in Ann Arbor, Michigan, and founded in 2016 by Dr. Jason Corso and Dr. Brian Moore, Voxel51 is an AI software company that is democratizing access to software 2.0 by providing the open core software building blocks that enable computer vision and machine learning engineers to rapidly engineer data-powered workflows."
}
] |
Python | Pandas dataframe.applymap()
|
16 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Dataframe.applymap() method applies a function that accepts and returns a scalar to every element of a DataFrame.
Syntax: DataFrame.applymap(func)
Parameters:
func: Python function, returns a single value from a single value.
Returns: Transformed DataFrame.
For link to CSV file Used in Code, click here
Example #1: Apply the applymap() function on the dataframe to find the no. of characters in all cells.
# importing pandas as pdimport pandas as pd # Making data frame from the csv filedf = pd.read_csv("nba.csv") # Printing the first 10 rows of # the data frame for visualizationdf[:10]
# Using lambda function we first convert all # the cell to a string value and then find# its length using len() functiondf.applymap(lambda x: len(str(x)))
Output:Notice how all nan value has been converted to string nan and their length is evaluated to be 3.
Example #2: Append _X in each cell using applymap() function.
In order to append _X in each cell, first convert each cell into a string.
# importing pandas as pdimport pandas as pd # Making data frame from the csv filedf = pd.read_csv("nba.csv") # Using applymap() to append '_X'# in each cell of the dataframedf.applymap(lambda x: str(x) + '_X')
Output:
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Nov, 2018"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 356,
"s": 242,
"text": "Dataframe.applymap() method applies a function that accepts and returns a scalar to every element of a DataFrame."
},
{
"code": null,
"e": 503,
"s": 356,
"text": "Syntax: DataFrame.applymap(func)\n\nParameters:\nfunc: Python function, returns a single value from a single value.\n\nReturns: Transformed DataFrame.\n"
},
{
"code": null,
"e": 549,
"s": 503,
"text": "For link to CSV file Used in Code, click here"
},
{
"code": null,
"e": 652,
"s": 549,
"text": "Example #1: Apply the applymap() function on the dataframe to find the no. of characters in all cells."
},
{
"code": "# importing pandas as pdimport pandas as pd # Making data frame from the csv filedf = pd.read_csv(\"nba.csv\") # Printing the first 10 rows of # the data frame for visualizationdf[:10]",
"e": 837,
"s": 652,
"text": null
},
{
"code": "# Using lambda function we first convert all # the cell to a string value and then find# its length using len() functiondf.applymap(lambda x: len(str(x)))",
"e": 992,
"s": 837,
"text": null
},
{
"code": null,
"e": 1096,
"s": 992,
"text": "Output:Notice how all nan value has been converted to string nan and their length is evaluated to be 3."
},
{
"code": null,
"e": 1159,
"s": 1096,
"text": " Example #2: Append _X in each cell using applymap() function."
},
{
"code": null,
"e": 1234,
"s": 1159,
"text": "In order to append _X in each cell, first convert each cell into a string."
},
{
"code": "# importing pandas as pdimport pandas as pd # Making data frame from the csv filedf = pd.read_csv(\"nba.csv\") # Using applymap() to append '_X'# in each cell of the dataframedf.applymap(lambda x: str(x) + '_X')",
"e": 1446,
"s": 1234,
"text": null
},
{
"code": null,
"e": 1454,
"s": 1446,
"text": "Output:"
},
{
"code": null,
"e": 1478,
"s": 1454,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 1510,
"s": 1478,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 1524,
"s": 1510,
"text": "Python-pandas"
},
{
"code": null,
"e": 1531,
"s": 1524,
"text": "Python"
},
{
"code": null,
"e": 1629,
"s": 1531,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1647,
"s": 1629,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1689,
"s": 1647,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1711,
"s": 1689,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1746,
"s": 1711,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1772,
"s": 1746,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1804,
"s": 1772,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1833,
"s": 1804,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1860,
"s": 1833,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1890,
"s": 1860,
"text": "Iterate over a list in Python"
}
] |
Program to perform a letter frequency attack on a monoalphabetic substitution cipher
|
19 Dec, 2021
Given a string S of size N representing a monoalphabetic cipher, the task is to print the top five possible plain texts that can be decrypted from the given monoalphabetic cipher using a letter frequency attack.
Examples:
Input: S = “ETAOINSHRDLCUMWFGYPBVKJXQZ”Output: A SIMPLE MESSAGE B TJNQMF NFTTBHF A SIMPLE MESSAGE C UKORNG OGUUCIG C UKORNG OGUUCIG
Input: S = “ABCDEFGH”Output: W OEILHA IAOOWCA J BRVYUN VNBBJPN C UKORNG OGUUCIG R JZDGCV DVJJRXV Y QGKNJC KCQQYEC
Approach: The problem can be solved based on the following observations:
Frequency analysis is one of the known ciphertext attacks. It is based on the study of the frequency of letters or groups of letters in a ciphertext. In all languages, different letters are used with different frequencies.The frequency array attack is based on the observation that in an English text, not all letters occur with the same frequency.In the given problem, the string, T = “ETAOINSHRDLCUMWFGYPBVKJXQZ” is used for deciphering.Therefore, the idea is to find the difference between ith maximum occurring letter in the given string and the string T and then shift all the letters of the given string with that difference. The string obtained will be one of the possible decrypted strings.
Frequency analysis is one of the known ciphertext attacks. It is based on the study of the frequency of letters or groups of letters in a ciphertext. In all languages, different letters are used with different frequencies.
The frequency array attack is based on the observation that in an English text, not all letters occur with the same frequency.
In the given problem, the string, T = “ETAOINSHRDLCUMWFGYPBVKJXQZ” is used for deciphering.
Therefore, the idea is to find the difference between ith maximum occurring letter in the given string and the string T and then shift all the letters of the given string with that difference. The string obtained will be one of the possible decrypted strings.
Follow the steps below to solve the problem:
Initialize a string say T as “ETAOINSHRDLCUMWFGYPBVKJXQZ”.
Find the frequency of each character of the string S, and store it in a variable, say freq[].
Iterate over the range [0, 5] using the variable i and perform the following steps:Find the ith most occurring element in the string S and store it in a variable, say ch.Find the difference between the ch and ith character of the string T and store it in a variable, say x.Iterate over the characters of string S, and shift all characters by x and then push the obtained string into an array plaintext[].
Find the ith most occurring element in the string S and store it in a variable, say ch.
Find the difference between the ch and ith character of the string T and store it in a variable, say x.
Iterate over the characters of string S, and shift all characters by x and then push the obtained string into an array plaintext[].
Finally, after the above steps, print the strings obtained in the array plaintext[].
Below is the implementation of the above approach:
C++
Java
Python3
C#
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to decrypt a monoalphabetic// substitution cipher using the letter// frequency attackvoid printString(string S, int N){ // Stores final 5 possible deciphered // plaintext string plaintext[5]; // Store the frequency of each letter in // cipher text int freq[26] = { 0 }; // Stores the frequency of each letter // in cipher text in descending order int freqSorted[26]; // Store which alphabet is used already int Used[26] = { 0 }; // Traverse the string S for (int i = 0; i < N; i++) { if (S[i] != ' ') { freq[S[i] - 'A']++; } } // Copy the frequency array for (int i = 0; i < 26; i++) { freqSorted[i] = freq[i]; } // Stores the string formed from concatenating // the english letters in the decreasing frequency // in the english language string T = "ETAOINSHRDLCUMWFGYPBVKJXQZ"; // Sort the array in descending order sort(freqSorted, freqSorted + 26, greater<int>()); // Iterate over the range [0, 5] for (int i = 0; i < 5; i++) { int ch = -1; // Iterate over the range [0, 26] for (int j = 0; j < 26; j++) { if (freqSorted[i] == freq[j] && Used[j] == 0) { Used[j] = 1; ch = j; break; } } if (ch == -1) break; // Store the numerical equivalent of letter at // ith index of array letter_frequency int x = T[i] - 'A'; // Calculate the probable shift used // in monoalphabetic cipher x = x - ch; // Temporary string to generate one // plaintext at a time string curr = ""; // Generate the probable ith plaintext // string using the shift calculated above for (int k = 0; k < N; k++) { // Insert whitespaces as it is if (S[k] == ' ') { curr += ' '; continue; } // Shift the kth letter of the // cipher by x int y = S[k] - 'A'; y += x; if (y < 0) y += 26; if (y > 25) y -= 26; // Add the kth calculated/shifted // letter to temporary string curr += 'A' + y; } plaintext[i] = curr; } // Print the generated 5 possible plaintexts for (int i = 0; i < 5; i++) { cout << plaintext[i] << endl; }} // Driver Codeint main(){ // Given string string S = "B TJNQMF NFTTBHF"; int N = S.length(); // Function Call printString(S, N); return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function to decrypt a monoalphabetic// substitution cipher using the letter// frequency attackstatic void printString(String S, int N){ // Stores final 5 possible deciphered // plaintext String []plaintext = new String[5]; // Store the frequency of each letter in // cipher text int freq[] = new int[26]; // Stores the frequency of each letter // in cipher text in descending order int freqSorted[] = new int[26]; // Store which alphabet is used already int Used[] = new int[26]; // Traverse the String S for (int i = 0; i < N; i++) { if (S.charAt(i) != ' ') { freq[S.charAt(i) - 'A']++; } } // Copy the frequency array for (int i = 0; i < 26; i++) { freqSorted[i] = freq[i]; } // Stores the String formed from concatenating // the english letters in the decreasing frequency // in the english language String T = "ETAOINSHRDLCUMWFGYPBVKJXQZ"; // Sort the array in descending order Arrays.sort(freqSorted); freqSorted= reverse(freqSorted); // Iterate over the range [0, 5] for (int i = 0; i < 5; i++) { int ch = -1; // Iterate over the range [0, 26] for (int j = 0; j < 26; j++) { if (freqSorted[i] == freq[j] && Used[j] == 0) { Used[j] = 1; ch = j; break; } } if (ch == -1) break; // Store the numerical equivalent of letter at // ith index of array letter_frequency int x = T.charAt(i) - 'A'; // Calculate the probable shift used // in monoalphabetic cipher x = x - ch; // Temporary String to generate one // plaintext at a time String curr = ""; // Generate the probable ith plaintext // String using the shift calculated above for (int k = 0; k < N; k++) { // Insert whitespaces as it is if (S.charAt(k) == ' ') { curr += (char)' '; continue; } // Shift the kth letter of the // cipher by x int y = S.charAt(k) - 'A'; y += x; if (y < 0) y += 26; if (y > 25) y -= 26; // Add the kth calculated/shifted // letter to temporary String curr += (char)('A' + y); } plaintext[i] = curr; } // Print the generated 5 possible plaintexts for (int i = 0; i < 5; i++) { System.out.print(plaintext[i] +"\n"); }}static int[] reverse(int a[]) { int i, n = a.length, t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } return a;}// Driver Codepublic static void main(String[] args){ // Given String String S = "B TJNQMF NFTTBHF"; int N = S.length(); // Function Call printString(S, N); }} // This code contributed by Princi Singh
# Python3 program for the above approach # Function to decrypt a monoalphabetic# substitution cipher using the letter# frequency attackdef printString(S, N): # Stores final 5 possible deciphered # plaintext plaintext = [None] * 5 # Store the frequency of each letter in # cipher text freq = [0] * 26 # Stores the frequency of each letter # in cipher text in descending order freqSorted = [None] * 26 # Store which alphabet is used already used = [0] * 26 # Traverse the string S for i in range(N): if S[i] != ' ': freq[ord(S[i]) - 65] += 1 # Copy the frequency array for i in range(26): freqSorted[i] = freq[i] # Stores the string formed from # concatenating the english letters # in the decreasing frequency in the # english language T = "ETAOINSHRDLCUMWFGYPBVKJXQZ" # Sort the array in descending order freqSorted.sort(reverse = True) # Iterate over the range [0, 5] for i in range(5): ch = -1 # Iterate over the range [0, 26] for j in range(26): if freqSorted[i] == freq[j] and used[j] == 0: used[j] = 1 ch = j break if ch == -1: break # Store the numerical equivalent of letter # at ith index of array letter_frequency x = ord(T[i]) - 65 # Calculate the probable shift used # in monoalphabetic cipher x = x - ch # Temporary string to generate one # plaintext at a time curr = "" # Generate the probable ith plaintext # string using the shift calculated above for k in range(N): # Insert whitespaces as it is if S[k] == ' ': curr += " " continue # Shift the kth letter of the # cipher by x y = ord(S[k]) - 65 y += x if y < 0: y += 26 if y > 25: y -= 26 # Add the kth calculated/shifted # letter to temporary string curr += chr(y + 65) plaintext[i] = curr # Print the generated 5 possible plaintexts for i in range(5): print(plaintext[i]) # Driver code # Given stringS = "B TJNQMF NFTTBHF"N = len(S) # Function CallprintString(S, N) # This code is contributed by Parth Manchanda
// C# program for the above approachusing System; public class GFG{ // Function to decrypt a monoalphabetic// substitution cipher using the letter// frequency attackstatic void printString(String S, int N){ // Stores readonly 5 possible deciphered // plaintext String []plaintext = new String[5]; // Store the frequency of each letter in // cipher text int []freq = new int[26]; // Stores the frequency of each letter // in cipher text in descending order int []freqSorted = new int[26]; // Store which alphabet is used already int []Used = new int[26]; // Traverse the String S for (int i = 0; i < N; i++) { if (S[i] != ' ') { freq[S[i] - 'A']++; } } // Copy the frequency array for (int i = 0; i < 26; i++) { freqSorted[i] = freq[i]; } // Stores the String formed from concatenating // the english letters in the decreasing frequency // in the english language String T = "ETAOINSHRDLCUMWFGYPBVKJXQZ"; // Sort the array in descending order Array.Sort(freqSorted); freqSorted= reverse(freqSorted); // Iterate over the range [0, 5] for (int i = 0; i < 5; i++) { int ch = -1; // Iterate over the range [0, 26] for (int j = 0; j < 26; j++) { if (freqSorted[i] == freq[j] && Used[j] == 0) { Used[j] = 1; ch = j; break; } } if (ch == -1) break; // Store the numerical equivalent of letter at // ith index of array letter_frequency int x = T[i] - 'A'; // Calculate the probable shift used // in monoalphabetic cipher x = x - ch; // Temporary String to generate one // plaintext at a time String curr = ""; // Generate the probable ith plaintext // String using the shift calculated above for (int k = 0; k < N; k++) { // Insert whitespaces as it is if (S[k] == ' ') { curr += (char)' '; continue; } // Shift the kth letter of the // cipher by x int y = S[k] - 'A'; y += x; if (y < 0) y += 26; if (y > 25) y -= 26; // Add the kth calculated/shifted // letter to temporary String curr += (char)('A' + y); } plaintext[i] = curr; } // Print the generated 5 possible plaintexts for (int i = 0; i < 5; i++) { Console.Write(plaintext[i] +"\n"); }}static int[] reverse(int []a) { int i, n = a.Length, t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } return a;} // Driver Codepublic static void Main(String[] args){ // Given String String S = "B TJNQMF NFTTBHF"; int N = S.Length; // Function Call printString(S, N); }} // This code is contributed by shikhasingrajput
A SIMPLE MESSAGE
B TJNQMF NFTTBHF
A SIMPLE MESSAGE
C UKORNG OGUUCIG
C UKORNG OGUUCIG
Time Complexity: O(N)Auxiliary Space: O(N)
parthmanchanda81
princi singh
shikhasingrajput
gulshankumarar231
akshaysingh98088
Arrays
cpp-string
encoding-decoding
frequency-counting
Strings
Arrays
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n19 Dec, 2021"
},
{
"code": null,
"e": 266,
"s": 54,
"text": "Given a string S of size N representing a monoalphabetic cipher, the task is to print the top five possible plain texts that can be decrypted from the given monoalphabetic cipher using a letter frequency attack."
},
{
"code": null,
"e": 276,
"s": 266,
"text": "Examples:"
},
{
"code": null,
"e": 457,
"s": 276,
"text": "Input: S = “ETAOINSHRDLCUMWFGYPBVKJXQZ”Output: A SIMPLE MESSAGE B TJNQMF NFTTBHF A SIMPLE MESSAGE C UKORNG OGUUCIG C UKORNG OGUUCIG"
},
{
"code": null,
"e": 620,
"s": 457,
"text": "Input: S = “ABCDEFGH”Output: W OEILHA IAOOWCA J BRVYUN VNBBJPN C UKORNG OGUUCIG R JZDGCV DVJJRXV Y QGKNJC KCQQYEC"
},
{
"code": null,
"e": 693,
"s": 620,
"text": "Approach: The problem can be solved based on the following observations:"
},
{
"code": null,
"e": 1393,
"s": 693,
"text": "Frequency analysis is one of the known ciphertext attacks. It is based on the study of the frequency of letters or groups of letters in a ciphertext. In all languages, different letters are used with different frequencies.The frequency array attack is based on the observation that in an English text, not all letters occur with the same frequency.In the given problem, the string, T = “ETAOINSHRDLCUMWFGYPBVKJXQZ” is used for deciphering.Therefore, the idea is to find the difference between ith maximum occurring letter in the given string and the string T and then shift all the letters of the given string with that difference. The string obtained will be one of the possible decrypted strings. "
},
{
"code": null,
"e": 1616,
"s": 1393,
"text": "Frequency analysis is one of the known ciphertext attacks. It is based on the study of the frequency of letters or groups of letters in a ciphertext. In all languages, different letters are used with different frequencies."
},
{
"code": null,
"e": 1743,
"s": 1616,
"text": "The frequency array attack is based on the observation that in an English text, not all letters occur with the same frequency."
},
{
"code": null,
"e": 1835,
"s": 1743,
"text": "In the given problem, the string, T = “ETAOINSHRDLCUMWFGYPBVKJXQZ” is used for deciphering."
},
{
"code": null,
"e": 2096,
"s": 1835,
"text": "Therefore, the idea is to find the difference between ith maximum occurring letter in the given string and the string T and then shift all the letters of the given string with that difference. The string obtained will be one of the possible decrypted strings. "
},
{
"code": null,
"e": 2141,
"s": 2096,
"text": "Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 2200,
"s": 2141,
"text": "Initialize a string say T as “ETAOINSHRDLCUMWFGYPBVKJXQZ”."
},
{
"code": null,
"e": 2294,
"s": 2200,
"text": "Find the frequency of each character of the string S, and store it in a variable, say freq[]."
},
{
"code": null,
"e": 2699,
"s": 2294,
"text": "Iterate over the range [0, 5] using the variable i and perform the following steps:Find the ith most occurring element in the string S and store it in a variable, say ch.Find the difference between the ch and ith character of the string T and store it in a variable, say x.Iterate over the characters of string S, and shift all characters by x and then push the obtained string into an array plaintext[]."
},
{
"code": null,
"e": 2787,
"s": 2699,
"text": "Find the ith most occurring element in the string S and store it in a variable, say ch."
},
{
"code": null,
"e": 2891,
"s": 2787,
"text": "Find the difference between the ch and ith character of the string T and store it in a variable, say x."
},
{
"code": null,
"e": 3023,
"s": 2891,
"text": "Iterate over the characters of string S, and shift all characters by x and then push the obtained string into an array plaintext[]."
},
{
"code": null,
"e": 3108,
"s": 3023,
"text": "Finally, after the above steps, print the strings obtained in the array plaintext[]."
},
{
"code": null,
"e": 3159,
"s": 3108,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 3163,
"s": 3159,
"text": "C++"
},
{
"code": null,
"e": 3168,
"s": 3163,
"text": "Java"
},
{
"code": null,
"e": 3176,
"s": 3168,
"text": "Python3"
},
{
"code": null,
"e": 3179,
"s": 3176,
"text": "C#"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to decrypt a monoalphabetic// substitution cipher using the letter// frequency attackvoid printString(string S, int N){ // Stores final 5 possible deciphered // plaintext string plaintext[5]; // Store the frequency of each letter in // cipher text int freq[26] = { 0 }; // Stores the frequency of each letter // in cipher text in descending order int freqSorted[26]; // Store which alphabet is used already int Used[26] = { 0 }; // Traverse the string S for (int i = 0; i < N; i++) { if (S[i] != ' ') { freq[S[i] - 'A']++; } } // Copy the frequency array for (int i = 0; i < 26; i++) { freqSorted[i] = freq[i]; } // Stores the string formed from concatenating // the english letters in the decreasing frequency // in the english language string T = \"ETAOINSHRDLCUMWFGYPBVKJXQZ\"; // Sort the array in descending order sort(freqSorted, freqSorted + 26, greater<int>()); // Iterate over the range [0, 5] for (int i = 0; i < 5; i++) { int ch = -1; // Iterate over the range [0, 26] for (int j = 0; j < 26; j++) { if (freqSorted[i] == freq[j] && Used[j] == 0) { Used[j] = 1; ch = j; break; } } if (ch == -1) break; // Store the numerical equivalent of letter at // ith index of array letter_frequency int x = T[i] - 'A'; // Calculate the probable shift used // in monoalphabetic cipher x = x - ch; // Temporary string to generate one // plaintext at a time string curr = \"\"; // Generate the probable ith plaintext // string using the shift calculated above for (int k = 0; k < N; k++) { // Insert whitespaces as it is if (S[k] == ' ') { curr += ' '; continue; } // Shift the kth letter of the // cipher by x int y = S[k] - 'A'; y += x; if (y < 0) y += 26; if (y > 25) y -= 26; // Add the kth calculated/shifted // letter to temporary string curr += 'A' + y; } plaintext[i] = curr; } // Print the generated 5 possible plaintexts for (int i = 0; i < 5; i++) { cout << plaintext[i] << endl; }} // Driver Codeint main(){ // Given string string S = \"B TJNQMF NFTTBHF\"; int N = S.length(); // Function Call printString(S, N); return 0;}",
"e": 5870,
"s": 3179,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to decrypt a monoalphabetic// substitution cipher using the letter// frequency attackstatic void printString(String S, int N){ // Stores final 5 possible deciphered // plaintext String []plaintext = new String[5]; // Store the frequency of each letter in // cipher text int freq[] = new int[26]; // Stores the frequency of each letter // in cipher text in descending order int freqSorted[] = new int[26]; // Store which alphabet is used already int Used[] = new int[26]; // Traverse the String S for (int i = 0; i < N; i++) { if (S.charAt(i) != ' ') { freq[S.charAt(i) - 'A']++; } } // Copy the frequency array for (int i = 0; i < 26; i++) { freqSorted[i] = freq[i]; } // Stores the String formed from concatenating // the english letters in the decreasing frequency // in the english language String T = \"ETAOINSHRDLCUMWFGYPBVKJXQZ\"; // Sort the array in descending order Arrays.sort(freqSorted); freqSorted= reverse(freqSorted); // Iterate over the range [0, 5] for (int i = 0; i < 5; i++) { int ch = -1; // Iterate over the range [0, 26] for (int j = 0; j < 26; j++) { if (freqSorted[i] == freq[j] && Used[j] == 0) { Used[j] = 1; ch = j; break; } } if (ch == -1) break; // Store the numerical equivalent of letter at // ith index of array letter_frequency int x = T.charAt(i) - 'A'; // Calculate the probable shift used // in monoalphabetic cipher x = x - ch; // Temporary String to generate one // plaintext at a time String curr = \"\"; // Generate the probable ith plaintext // String using the shift calculated above for (int k = 0; k < N; k++) { // Insert whitespaces as it is if (S.charAt(k) == ' ') { curr += (char)' '; continue; } // Shift the kth letter of the // cipher by x int y = S.charAt(k) - 'A'; y += x; if (y < 0) y += 26; if (y > 25) y -= 26; // Add the kth calculated/shifted // letter to temporary String curr += (char)('A' + y); } plaintext[i] = curr; } // Print the generated 5 possible plaintexts for (int i = 0; i < 5; i++) { System.out.print(plaintext[i] +\"\\n\"); }}static int[] reverse(int a[]) { int i, n = a.length, t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } return a;}// Driver Codepublic static void main(String[] args){ // Given String String S = \"B TJNQMF NFTTBHF\"; int N = S.length(); // Function Call printString(S, N); }} // This code contributed by Princi Singh",
"e": 8900,
"s": 5870,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to decrypt a monoalphabetic# substitution cipher using the letter# frequency attackdef printString(S, N): # Stores final 5 possible deciphered # plaintext plaintext = [None] * 5 # Store the frequency of each letter in # cipher text freq = [0] * 26 # Stores the frequency of each letter # in cipher text in descending order freqSorted = [None] * 26 # Store which alphabet is used already used = [0] * 26 # Traverse the string S for i in range(N): if S[i] != ' ': freq[ord(S[i]) - 65] += 1 # Copy the frequency array for i in range(26): freqSorted[i] = freq[i] # Stores the string formed from # concatenating the english letters # in the decreasing frequency in the # english language T = \"ETAOINSHRDLCUMWFGYPBVKJXQZ\" # Sort the array in descending order freqSorted.sort(reverse = True) # Iterate over the range [0, 5] for i in range(5): ch = -1 # Iterate over the range [0, 26] for j in range(26): if freqSorted[i] == freq[j] and used[j] == 0: used[j] = 1 ch = j break if ch == -1: break # Store the numerical equivalent of letter # at ith index of array letter_frequency x = ord(T[i]) - 65 # Calculate the probable shift used # in monoalphabetic cipher x = x - ch # Temporary string to generate one # plaintext at a time curr = \"\" # Generate the probable ith plaintext # string using the shift calculated above for k in range(N): # Insert whitespaces as it is if S[k] == ' ': curr += \" \" continue # Shift the kth letter of the # cipher by x y = ord(S[k]) - 65 y += x if y < 0: y += 26 if y > 25: y -= 26 # Add the kth calculated/shifted # letter to temporary string curr += chr(y + 65) plaintext[i] = curr # Print the generated 5 possible plaintexts for i in range(5): print(plaintext[i]) # Driver code # Given stringS = \"B TJNQMF NFTTBHF\"N = len(S) # Function CallprintString(S, N) # This code is contributed by Parth Manchanda",
"e": 11463,
"s": 8900,
"text": null
},
{
"code": "// C# program for the above approachusing System; public class GFG{ // Function to decrypt a monoalphabetic// substitution cipher using the letter// frequency attackstatic void printString(String S, int N){ // Stores readonly 5 possible deciphered // plaintext String []plaintext = new String[5]; // Store the frequency of each letter in // cipher text int []freq = new int[26]; // Stores the frequency of each letter // in cipher text in descending order int []freqSorted = new int[26]; // Store which alphabet is used already int []Used = new int[26]; // Traverse the String S for (int i = 0; i < N; i++) { if (S[i] != ' ') { freq[S[i] - 'A']++; } } // Copy the frequency array for (int i = 0; i < 26; i++) { freqSorted[i] = freq[i]; } // Stores the String formed from concatenating // the english letters in the decreasing frequency // in the english language String T = \"ETAOINSHRDLCUMWFGYPBVKJXQZ\"; // Sort the array in descending order Array.Sort(freqSorted); freqSorted= reverse(freqSorted); // Iterate over the range [0, 5] for (int i = 0; i < 5; i++) { int ch = -1; // Iterate over the range [0, 26] for (int j = 0; j < 26; j++) { if (freqSorted[i] == freq[j] && Used[j] == 0) { Used[j] = 1; ch = j; break; } } if (ch == -1) break; // Store the numerical equivalent of letter at // ith index of array letter_frequency int x = T[i] - 'A'; // Calculate the probable shift used // in monoalphabetic cipher x = x - ch; // Temporary String to generate one // plaintext at a time String curr = \"\"; // Generate the probable ith plaintext // String using the shift calculated above for (int k = 0; k < N; k++) { // Insert whitespaces as it is if (S[k] == ' ') { curr += (char)' '; continue; } // Shift the kth letter of the // cipher by x int y = S[k] - 'A'; y += x; if (y < 0) y += 26; if (y > 25) y -= 26; // Add the kth calculated/shifted // letter to temporary String curr += (char)('A' + y); } plaintext[i] = curr; } // Print the generated 5 possible plaintexts for (int i = 0; i < 5; i++) { Console.Write(plaintext[i] +\"\\n\"); }}static int[] reverse(int []a) { int i, n = a.Length, t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } return a;} // Driver Codepublic static void Main(String[] args){ // Given String String S = \"B TJNQMF NFTTBHF\"; int N = S.Length; // Function Call printString(S, N); }} // This code is contributed by shikhasingrajput",
"e": 14464,
"s": 11463,
"text": null
},
{
"code": null,
"e": 14549,
"s": 14464,
"text": "A SIMPLE MESSAGE\nB TJNQMF NFTTBHF\nA SIMPLE MESSAGE\nC UKORNG OGUUCIG\nC UKORNG OGUUCIG"
},
{
"code": null,
"e": 14592,
"s": 14549,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 14609,
"s": 14592,
"text": "parthmanchanda81"
},
{
"code": null,
"e": 14622,
"s": 14609,
"text": "princi singh"
},
{
"code": null,
"e": 14639,
"s": 14622,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 14657,
"s": 14639,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 14674,
"s": 14657,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 14681,
"s": 14674,
"text": "Arrays"
},
{
"code": null,
"e": 14692,
"s": 14681,
"text": "cpp-string"
},
{
"code": null,
"e": 14710,
"s": 14692,
"text": "encoding-decoding"
},
{
"code": null,
"e": 14729,
"s": 14710,
"text": "frequency-counting"
},
{
"code": null,
"e": 14737,
"s": 14729,
"text": "Strings"
},
{
"code": null,
"e": 14744,
"s": 14737,
"text": "Arrays"
},
{
"code": null,
"e": 14752,
"s": 14744,
"text": "Strings"
}
] |
Add and Remove Views in Android Dynamically in Kotlin?
|
This example demonstrates how to Add and Remove Views in Android Dynamically in Kotlin.
Step 1 − Create a new project in Android Studio, go to File ? New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/parent_linear_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal">
<EditText
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:inputType="phone" />
<Spinner
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:entries="@array/types"
android:gravity="right" />
<Button
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight="1"
android:background="@android:drawable/ic_delete"
android:onClick="onDelete" />
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="onAddField"
android:text="Add Field"
android:textColor="@android:color/background_dark" />
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private var parentLinearLayout: LinearLayout? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
parentLinearLayout = findViewById(R.id.parent_linear_layout)
}
fun onDelete(view: View) {
parentLinearLayout!!.removeView(view.parent as View)
}
fun onAddField(view: View) {
val inflater =
getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val rowView: View = inflater.inflate(R.layout.field, null)
parentLinearLayout!!.addView(rowView, parentLinearLayout!!.childCount - 1)
}
}
Step 4 − Create a new Layout Resource file (field.xml) and add the following code −
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal">
<EditText
android:id="@+id/number_edit_text"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:inputType="phone" />
<Spinner
android:id="@+id/type_spinner"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:entries="@array/types"
android:gravity="right" />
<Button
android:id="@+id/delete_button"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight="1"
android:background="@android:drawable/ic_delete"
android:onClick="onDelete" />
</LinearLayout>
Step 5 − Open res/values/strings.xml and add the following code −
<resources>
<string name="app_name">YourAppName</string>
<string-array name="types">
<item>Mobile</item>
<item>Office</item>
<item>Home</item>
</string-array>
</resources>
Step 6 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.q1">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
|
[
{
"code": null,
"e": 1275,
"s": 1187,
"text": "This example demonstrates how to Add and Remove Views in Android Dynamically in Kotlin."
},
{
"code": null,
"e": 1404,
"s": 1275,
"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": 1470,
"s": 1404,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2885,
"s": 1470,
"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/parent_linear_layout\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:layout_margin=\"5dp\"\n android:orientation=\"vertical\"\n tools:context=\".MainActivity\">\n <LinearLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"50dp\"\n android:orientation=\"horizontal\">\n <EditText\n android:layout_width=\"0dp\"\n android:layout_height=\"match_parent\"\n android:layout_weight=\"5\"\n android:inputType=\"phone\" />\n <Spinner\n android:layout_width=\"0dp\"\n android:layout_height=\"wrap_content\"\n android:layout_weight=\"3\"\n android:entries=\"@array/types\"\n android:gravity=\"right\" />\n <Button\n android:layout_width=\"0dp\"\n android:layout_height=\"40dp\"\n android:layout_weight=\"1\"\n android:background=\"@android:drawable/ic_delete\"\n android:onClick=\"onDelete\" />\n </LinearLayout>\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_gravity=\"center\"\n android:onClick=\"onAddField\"\n android:text=\"Add Field\"\n android:textColor=\"@android:color/background_dark\" />\n</LinearLayout>"
},
{
"code": null,
"e": 2940,
"s": 2885,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 3852,
"s": 2940,
"text": "import android.content.Context\nimport android.os.Bundle\nimport android.view.LayoutInflater\nimport android.view.View\nimport android.widget.LinearLayout\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n private var parentLinearLayout: LinearLayout? = null\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n parentLinearLayout = findViewById(R.id.parent_linear_layout)\n }\n fun onDelete(view: View) {\n parentLinearLayout!!.removeView(view.parent as View)\n }\n fun onAddField(view: View) {\n val inflater =\n getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater\n val rowView: View = inflater.inflate(R.layout.field, null)\n parentLinearLayout!!.addView(rowView, parentLinearLayout!!.childCount - 1)\n }\n}"
},
{
"code": null,
"e": 3936,
"s": 3852,
"text": "Step 4 − Create a new Layout Resource file (field.xml) and add the following code −"
},
{
"code": null,
"e": 4803,
"s": 3936,
"text": "<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"50dp\"\n android:orientation=\"horizontal\">\n <EditText\n android:id=\"@+id/number_edit_text\"\n android:layout_width=\"0dp\"\n android:layout_height=\"match_parent\"\n android:layout_weight=\"5\"\n android:inputType=\"phone\" />\n <Spinner\n android:id=\"@+id/type_spinner\"\n android:layout_width=\"0dp\"\n android:layout_height=\"wrap_content\"\n android:layout_weight=\"3\"\n android:entries=\"@array/types\"\n android:gravity=\"right\" />\n <Button\n android:id=\"@+id/delete_button\"\n android:layout_width=\"0dp\"\n android:layout_height=\"40dp\"\n android:layout_weight=\"1\"\n android:background=\"@android:drawable/ic_delete\"\n android:onClick=\"onDelete\" />\n</LinearLayout>"
},
{
"code": null,
"e": 4869,
"s": 4803,
"text": "Step 5 − Open res/values/strings.xml and add the following code −"
},
{
"code": null,
"e": 5065,
"s": 4869,
"text": "<resources>\n<string name=\"app_name\">YourAppName</string>\n <string-array name=\"types\">\n <item>Mobile</item>\n <item>Office</item>\n <item>Home</item>\n </string-array>\n</resources>"
},
{
"code": null,
"e": 5120,
"s": 5065,
"text": "Step 6 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 5786,
"s": 5120,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.q1\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 6136,
"s": 5786,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen"
}
] |
What is a Loopback Address?
|
24 Nov, 2021
A loopback address is a distinct reserved IP address range that starts from 127.0.0.0 ends at 127.255.255.255 though 127.255.255.255 is the broadcast address for 127.0.0.0/8. The loopback addresses are built into the IP domain system, enabling devices to transmit and receive the data packets. The loopback address 127.0.0.1 is generally known as localhost.
TCP/IP protocol manages all the loopback addresses in the operating system. It mocks the TCP/IP server or TCP/IP client on the same system. These loopback addresses are always accessible so that the user can use them anytime for troubleshooting TCP/IP.
Whenever a protocol or program sends any data from a computer with any loopback IP address, that traffic is processed by a TCP/IP protocol stack within itself, i.e., without transmitting it to the network. That is, if a user is pinging a loopback address, they’ll get the reply from the same TCP/IP stack running on their computer. So, all the data transmitted to any of the loopback addresses as the destination address will not pop up on the network.
127.0.0.1 is the most commonly used loopback address; generally, 127.0.0.1 and localhost are functionally similar, i.e., the loopback address 127.0.0.1 and the hostname localhost; are internally mapped. Though, other loopback addresses are also accessible and can be used.
IPv4 and IPv6 Loopback Addresses:
The IPv4 loopback address is 127.0.0.0/8 and the most commonly used loopback address is 127.0.0.1.
The IPv6 loopback address is ::1
How to use the “ping” Command:
To use the “ping” command go to the windows start menu.
Search for “Command prompt”.
Type in “ping” followed by the loopback address. and,
Hit enter.
For example, as can be seen below, the outputs of four different IPv4 loopback addresses (127.0.0.0, 127.0.0.1, 127.15.90.69, and 127.255.255.255) the network and broadcast addresses are unreachable loopback addresses and IPv6 loopback address ::1.
ping output for 127.0.0.0 (Network address).
C:\Users\bklad>ping 127.0.0.0
Pinging 127.0.0.0 with 32 bytes of data:
General failure.
General failure.
General failure.
General failure.
Ping statistics for 127.0.0.0:
Packets: Sent = 4, Received = 0, Lost = 4 (100% loss),
ping output for 127.0.0.1
C:\Users\bklad>ping 127.0.0.1
Pinging 127.0.0.1 with 32 bytes of data:
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Ping statistics for 127.0.0.1:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 0ms, Average = 0ms
ping output for 127.15.90.69
C:\Users\bklad>ping 127.15.90.69
Pinging 127.15.90.69 with 32 bytes of data:
Reply from 127.15.90.69: bytes=32 time<1ms TTL=128
Reply from 127.15.90.69: bytes=32 time<1ms TTL=128
Reply from 127.15.90.69: bytes=32 time<1ms TTL=128
Reply from 127.15.90.69: bytes=32 time<1ms TTL=128
Ping statistics for 127.15.90.69:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 0ms, Average = 0ms
ping output for 127.255.255.255 (Broadcast address).
C:\Users\bklad>ping 127.255.255.255
Pinging 127.255.255.255 with 32 bytes of data:
Request timed out.
Request timed out.
Request timed out.
Request timed out.
Ping statistics for 127.255.255.255:
Packets: Sent = 4, Received = 0, Lost = 4 (100% loss),
ping output for ::1.
C:\Users\bklad>ping ::1
Pinging ::1 with 32 bytes of data:
Reply from ::1: time<1ms
Reply from ::1: time<1ms
Reply from ::1: time<1ms
Reply from ::1: time<1ms
Ping statistics for ::1:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 0ms, Average = 0ms
Advantages of loopback address:
It is an efficient method to find a device on the network.
It can be configured as the router ID for protocols such as BGP and OSPF.
It is used as a source and destination address for testing network connectivity.
It can also be used for testing IP software.
Disadvantages:
Just like physical interfaces, it needs a unique address.
Picked
Computer Networks
Computer Subject
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GSM in Wireless Communication
Wireless Application Protocol
Secure Socket Layer (SSL)
Mobile Internet Protocol (or Mobile IP)
Advanced Encryption Standard (AES)
SDE SHEET - A Complete Guide for SDE Preparation
What is Algorithm | Introduction to Algorithms
Software Engineering | Coupling and Cohesion
Type Checking in Compiler Design
Difference between NP hard and NP complete problem
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 386,
"s": 28,
"text": "A loopback address is a distinct reserved IP address range that starts from 127.0.0.0 ends at 127.255.255.255 though 127.255.255.255 is the broadcast address for 127.0.0.0/8. The loopback addresses are built into the IP domain system, enabling devices to transmit and receive the data packets. The loopback address 127.0.0.1 is generally known as localhost."
},
{
"code": null,
"e": 639,
"s": 386,
"text": "TCP/IP protocol manages all the loopback addresses in the operating system. It mocks the TCP/IP server or TCP/IP client on the same system. These loopback addresses are always accessible so that the user can use them anytime for troubleshooting TCP/IP."
},
{
"code": null,
"e": 1093,
"s": 639,
"text": "Whenever a protocol or program sends any data from a computer with any loopback IP address, that traffic is processed by a TCP/IP protocol stack within itself, i.e., without transmitting it to the network. That is, if a user is pinging a loopback address, they’ll get the reply from the same TCP/IP stack running on their computer. So, all the data transmitted to any of the loopback addresses as the destination address will not pop up on the network."
},
{
"code": null,
"e": 1367,
"s": 1093,
"text": "127.0.0.1 is the most commonly used loopback address; generally, 127.0.0.1 and localhost are functionally similar, i.e., the loopback address 127.0.0.1 and the hostname localhost; are internally mapped. Though, other loopback addresses are also accessible and can be used. "
},
{
"code": null,
"e": 1401,
"s": 1367,
"text": "IPv4 and IPv6 Loopback Addresses:"
},
{
"code": null,
"e": 1500,
"s": 1401,
"text": "The IPv4 loopback address is 127.0.0.0/8 and the most commonly used loopback address is 127.0.0.1."
},
{
"code": null,
"e": 1533,
"s": 1500,
"text": "The IPv6 loopback address is ::1"
},
{
"code": null,
"e": 1564,
"s": 1533,
"text": "How to use the “ping” Command:"
},
{
"code": null,
"e": 1620,
"s": 1564,
"text": "To use the “ping” command go to the windows start menu."
},
{
"code": null,
"e": 1649,
"s": 1620,
"text": "Search for “Command prompt”."
},
{
"code": null,
"e": 1703,
"s": 1649,
"text": "Type in “ping” followed by the loopback address. and,"
},
{
"code": null,
"e": 1714,
"s": 1703,
"text": "Hit enter."
},
{
"code": null,
"e": 1963,
"s": 1714,
"text": "For example, as can be seen below, the outputs of four different IPv4 loopback addresses (127.0.0.0, 127.0.0.1, 127.15.90.69, and 127.255.255.255) the network and broadcast addresses are unreachable loopback addresses and IPv6 loopback address ::1."
},
{
"code": null,
"e": 2008,
"s": 1963,
"text": "ping output for 127.0.0.0 (Network address)."
},
{
"code": null,
"e": 2238,
"s": 2008,
"text": "C:\\Users\\bklad>ping 127.0.0.0\n\nPinging 127.0.0.0 with 32 bytes of data:\nGeneral failure.\nGeneral failure.\nGeneral failure.\nGeneral failure.\n\nPing statistics for 127.0.0.0:\n Packets: Sent = 4, Received = 0, Lost = 4 (100% loss),"
},
{
"code": null,
"e": 2264,
"s": 2238,
"text": "ping output for 127.0.0.1"
},
{
"code": null,
"e": 2712,
"s": 2264,
"text": "C:\\Users\\bklad>ping 127.0.0.1\n\nPinging 127.0.0.1 with 32 bytes of data:\nReply from 127.0.0.1: bytes=32 time<1ms TTL=128\nReply from 127.0.0.1: bytes=32 time<1ms TTL=128\nReply from 127.0.0.1: bytes=32 time<1ms TTL=128\nReply from 127.0.0.1: bytes=32 time<1ms TTL=128\n\nPing statistics for 127.0.0.1:\n Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),\nApproximate round trip times in milli-seconds:\n Minimum = 0ms, Maximum = 0ms, Average = 0ms "
},
{
"code": null,
"e": 2741,
"s": 2712,
"text": "ping output for 127.15.90.69"
},
{
"code": null,
"e": 3208,
"s": 2741,
"text": "C:\\Users\\bklad>ping 127.15.90.69\n\nPinging 127.15.90.69 with 32 bytes of data:\nReply from 127.15.90.69: bytes=32 time<1ms TTL=128\nReply from 127.15.90.69: bytes=32 time<1ms TTL=128\nReply from 127.15.90.69: bytes=32 time<1ms TTL=128\nReply from 127.15.90.69: bytes=32 time<1ms TTL=128\n\nPing statistics for 127.15.90.69:\n Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),\nApproximate round trip times in milli-seconds:\n Minimum = 0ms, Maximum = 0ms, Average = 0ms"
},
{
"code": null,
"e": 3261,
"s": 3208,
"text": "ping output for 127.255.255.255 (Broadcast address)."
},
{
"code": null,
"e": 3517,
"s": 3261,
"text": "C:\\Users\\bklad>ping 127.255.255.255\n\nPinging 127.255.255.255 with 32 bytes of data:\nRequest timed out.\nRequest timed out.\nRequest timed out.\nRequest timed out.\n\nPing statistics for 127.255.255.255:\n Packets: Sent = 4, Received = 0, Lost = 4 (100% loss),"
},
{
"code": null,
"e": 3538,
"s": 3517,
"text": "ping output for ::1."
},
{
"code": null,
"e": 3874,
"s": 3538,
"text": "C:\\Users\\bklad>ping ::1\n\nPinging ::1 with 32 bytes of data:\nReply from ::1: time<1ms\nReply from ::1: time<1ms\nReply from ::1: time<1ms\nReply from ::1: time<1ms\n\nPing statistics for ::1:\n Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),\nApproximate round trip times in milli-seconds:\n Minimum = 0ms, Maximum = 0ms, Average = 0ms"
},
{
"code": null,
"e": 3906,
"s": 3874,
"text": "Advantages of loopback address:"
},
{
"code": null,
"e": 3965,
"s": 3906,
"text": "It is an efficient method to find a device on the network."
},
{
"code": null,
"e": 4039,
"s": 3965,
"text": "It can be configured as the router ID for protocols such as BGP and OSPF."
},
{
"code": null,
"e": 4120,
"s": 4039,
"text": "It is used as a source and destination address for testing network connectivity."
},
{
"code": null,
"e": 4165,
"s": 4120,
"text": "It can also be used for testing IP software."
},
{
"code": null,
"e": 4180,
"s": 4165,
"text": "Disadvantages:"
},
{
"code": null,
"e": 4238,
"s": 4180,
"text": "Just like physical interfaces, it needs a unique address."
},
{
"code": null,
"e": 4245,
"s": 4238,
"text": "Picked"
},
{
"code": null,
"e": 4263,
"s": 4245,
"text": "Computer Networks"
},
{
"code": null,
"e": 4280,
"s": 4263,
"text": "Computer Subject"
},
{
"code": null,
"e": 4298,
"s": 4280,
"text": "Computer Networks"
},
{
"code": null,
"e": 4396,
"s": 4298,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4426,
"s": 4396,
"text": "GSM in Wireless Communication"
},
{
"code": null,
"e": 4456,
"s": 4426,
"text": "Wireless Application Protocol"
},
{
"code": null,
"e": 4482,
"s": 4456,
"text": "Secure Socket Layer (SSL)"
},
{
"code": null,
"e": 4522,
"s": 4482,
"text": "Mobile Internet Protocol (or Mobile IP)"
},
{
"code": null,
"e": 4557,
"s": 4522,
"text": "Advanced Encryption Standard (AES)"
},
{
"code": null,
"e": 4606,
"s": 4557,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 4653,
"s": 4606,
"text": "What is Algorithm | Introduction to Algorithms"
},
{
"code": null,
"e": 4698,
"s": 4653,
"text": "Software Engineering | Coupling and Cohesion"
},
{
"code": null,
"e": 4731,
"s": 4698,
"text": "Type Checking in Compiler Design"
}
] |
Locale getDefault() method in Java - GeeksforGeeks
|
07 Sep, 2018
This method returns default Locale set by the Java Virtual Machine. This is static method so it can be called without creating object of the class Locale.
Syntax:
public static Locale getDefault()
Return Value: The method returns default Locale set by the Java Virtual Machine.
Below is the code to illustrate getDefault() method:
Program 1:
// Java code to demonstrate// getLocale() method in Locale import java.util.Locale;public class GfG { // main method public static void main(String[] args) { // declaring object of Locale Locale locale; // calling the getDefault method locale = Locale.getDefault(); // printing the locale System.out.println(locale); }}
en_US
This method returns default Locale set by the Java Virtual Machine for the specified category. This is static method so it can be called without creating object of the class Locale.
Syntax:
Locale.getDefault(Locale.Category category)
Parameters: It takes a mandatory parameter category of type Locale.Category.
Return Value: The method returns default Locale set of type Locale, for the specified category.
Exceptions: If the category passed in the parameter is null, the getDefault() method will throw NullPointerException.
Below is the code to illustrate getDefault(Locale.Category category):
Program 1:
// Java code to demonstrate// getLocale() method in Locale import java.util.Locale; public class GfG { // main method public static void main(String[] args) { // declaring object of Locale Locale locale; // Specified category. Locale.Category category = Locale.Category.DISPLAY; // calling the getDefault method locale = Locale.getDefault(category); // printing the locale System.out.println(locale); }}
en_US
Program 2: To demonstrate NullPointerException
// Java code to demonstrate// getLocale() method in Locale import java.util.*; public class GfG { // main method public static void main(String[] args) { // declaring object of Locale Locale locale; try { // Specified category = null Locale.Category category = null; // calling the getDefault method // This will throw exception // as the category passed is null locale = Locale.getDefault(category); // printing the locale System.out.println(locale); } catch (Exception e) { System.out.println("Exception: " + e); } }}
Exception: java.lang.NullPointerException
Java - util package
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Interfaces in Java
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
Overriding in Java
Stack Class in Java
Collections in Java
|
[
{
"code": null,
"e": 24186,
"s": 24158,
"text": "\n07 Sep, 2018"
},
{
"code": null,
"e": 24341,
"s": 24186,
"text": "This method returns default Locale set by the Java Virtual Machine. This is static method so it can be called without creating object of the class Locale."
},
{
"code": null,
"e": 24349,
"s": 24341,
"text": "Syntax:"
},
{
"code": null,
"e": 24383,
"s": 24349,
"text": "public static Locale getDefault()"
},
{
"code": null,
"e": 24464,
"s": 24383,
"text": "Return Value: The method returns default Locale set by the Java Virtual Machine."
},
{
"code": null,
"e": 24517,
"s": 24464,
"text": "Below is the code to illustrate getDefault() method:"
},
{
"code": null,
"e": 24528,
"s": 24517,
"text": "Program 1:"
},
{
"code": "// Java code to demonstrate// getLocale() method in Locale import java.util.Locale;public class GfG { // main method public static void main(String[] args) { // declaring object of Locale Locale locale; // calling the getDefault method locale = Locale.getDefault(); // printing the locale System.out.println(locale); }}",
"e": 24909,
"s": 24528,
"text": null
},
{
"code": null,
"e": 24916,
"s": 24909,
"text": "en_US\n"
},
{
"code": null,
"e": 25098,
"s": 24916,
"text": "This method returns default Locale set by the Java Virtual Machine for the specified category. This is static method so it can be called without creating object of the class Locale."
},
{
"code": null,
"e": 25106,
"s": 25098,
"text": "Syntax:"
},
{
"code": null,
"e": 25150,
"s": 25106,
"text": "Locale.getDefault(Locale.Category category)"
},
{
"code": null,
"e": 25227,
"s": 25150,
"text": "Parameters: It takes a mandatory parameter category of type Locale.Category."
},
{
"code": null,
"e": 25323,
"s": 25227,
"text": "Return Value: The method returns default Locale set of type Locale, for the specified category."
},
{
"code": null,
"e": 25441,
"s": 25323,
"text": "Exceptions: If the category passed in the parameter is null, the getDefault() method will throw NullPointerException."
},
{
"code": null,
"e": 25511,
"s": 25441,
"text": "Below is the code to illustrate getDefault(Locale.Category category):"
},
{
"code": null,
"e": 25522,
"s": 25511,
"text": "Program 1:"
},
{
"code": "// Java code to demonstrate// getLocale() method in Locale import java.util.Locale; public class GfG { // main method public static void main(String[] args) { // declaring object of Locale Locale locale; // Specified category. Locale.Category category = Locale.Category.DISPLAY; // calling the getDefault method locale = Locale.getDefault(category); // printing the locale System.out.println(locale); }}",
"e": 26004,
"s": 25522,
"text": null
},
{
"code": null,
"e": 26011,
"s": 26004,
"text": "en_US\n"
},
{
"code": null,
"e": 26058,
"s": 26011,
"text": "Program 2: To demonstrate NullPointerException"
},
{
"code": "// Java code to demonstrate// getLocale() method in Locale import java.util.*; public class GfG { // main method public static void main(String[] args) { // declaring object of Locale Locale locale; try { // Specified category = null Locale.Category category = null; // calling the getDefault method // This will throw exception // as the category passed is null locale = Locale.getDefault(category); // printing the locale System.out.println(locale); } catch (Exception e) { System.out.println(\"Exception: \" + e); } }}",
"e": 26741,
"s": 26058,
"text": null
},
{
"code": null,
"e": 26784,
"s": 26741,
"text": "Exception: java.lang.NullPointerException\n"
},
{
"code": null,
"e": 26804,
"s": 26784,
"text": "Java - util package"
},
{
"code": null,
"e": 26819,
"s": 26804,
"text": "Java-Functions"
},
{
"code": null,
"e": 26824,
"s": 26819,
"text": "Java"
},
{
"code": null,
"e": 26829,
"s": 26824,
"text": "Java"
},
{
"code": null,
"e": 26927,
"s": 26829,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26936,
"s": 26927,
"text": "Comments"
},
{
"code": null,
"e": 26949,
"s": 26936,
"text": "Old Comments"
},
{
"code": null,
"e": 26979,
"s": 26949,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 26998,
"s": 26979,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 27030,
"s": 26998,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 27081,
"s": 27030,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 27099,
"s": 27081,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 27130,
"s": 27099,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 27162,
"s": 27130,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 27181,
"s": 27162,
"text": "Overriding in Java"
},
{
"code": null,
"e": 27201,
"s": 27181,
"text": "Stack Class in Java"
}
] |
Delete elements in range in Python
|
Deleting a single element from a python is straight forward by using the index of the element and the del function. But there may be scenarios when we need to delete elements for a group of indices. This article explores the approaches to delete only those elements form the list which are specified in the index list.
In this approach we create a list containing the index values where deletion has to happen. The we sort and reverse them to preserve the original order of the elements of the list. Finally we apply the del function to the original given list for those specific index points.
Live Demo
Alist = [11,6, 8, 3, 2]
# The indices list
idx_list = [1, 3, 0]
# printing the original list
print("Given list is : ", Alist)
# printing the indices list
print("The indices list is : ", idx_list)
# Use del and sorted()
for i in sorted(idx_list, reverse=True):
del Alist[i]
# Print result
print("List after deleted elements : " ,Alist)
Running the above code gives us the following result −
Given list is : [11, 6, 8, 3, 2]
The indices list is : [1, 3, 0]
List after deleted elements : [8, 2]
idx_list after sorting and reverse becomes [0,1,3]. So only the elements from these positions get deleted.
We can also approach the above program by using enumerate and a not in clause inside a for loop. The result is same as above.
Live Demo
Alist = [11,6, 8, 3, 2]
# The indices list
idx_list = [1, 3, 0]
# printing the original list
print("Given list is : ", Alist)
# printing the indices list
print("The indices list is : ", idx_list)
# Use slicing and not in
Alist[:] = [ j for i, j in enumerate(Alist)
if i not in idx_list ]
# Print result
print("List after deleted elements : " ,Alist)
Running the above code gives us the following result −
Given list is : [11, 6, 8, 3, 2]
The indices list is : [1, 3, 0]
List after deleted elements : [8, 2]
|
[
{
"code": null,
"e": 1381,
"s": 1062,
"text": "Deleting a single element from a python is straight forward by using the index of the element and the del function. But there may be scenarios when we need to delete elements for a group of indices. This article explores the approaches to delete only those elements form the list which are specified in the index list."
},
{
"code": null,
"e": 1656,
"s": 1381,
"text": "In this approach we create a list containing the index values where deletion has to happen. The we sort and reverse them to preserve the original order of the elements of the list. Finally we apply the del function to the original given list for those specific index points."
},
{
"code": null,
"e": 1667,
"s": 1656,
"text": " Live Demo"
},
{
"code": null,
"e": 2007,
"s": 1667,
"text": "Alist = [11,6, 8, 3, 2]\n\n# The indices list\nidx_list = [1, 3, 0]\n\n# printing the original list\nprint(\"Given list is : \", Alist)\n\n# printing the indices list\nprint(\"The indices list is : \", idx_list)\n\n# Use del and sorted()\nfor i in sorted(idx_list, reverse=True):\ndel Alist[i]\n\n# Print result\nprint(\"List after deleted elements : \" ,Alist)"
},
{
"code": null,
"e": 2062,
"s": 2007,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2164,
"s": 2062,
"text": "Given list is : [11, 6, 8, 3, 2]\nThe indices list is : [1, 3, 0]\nList after deleted elements : [8, 2]"
},
{
"code": null,
"e": 2271,
"s": 2164,
"text": "idx_list after sorting and reverse becomes [0,1,3]. So only the elements from these positions get deleted."
},
{
"code": null,
"e": 2397,
"s": 2271,
"text": "We can also approach the above program by using enumerate and a not in clause inside a for loop. The result is same as above."
},
{
"code": null,
"e": 2408,
"s": 2397,
"text": " Live Demo"
},
{
"code": null,
"e": 2763,
"s": 2408,
"text": "Alist = [11,6, 8, 3, 2]\n\n# The indices list\nidx_list = [1, 3, 0]\n\n# printing the original list\nprint(\"Given list is : \", Alist)\n\n# printing the indices list\nprint(\"The indices list is : \", idx_list)\n\n# Use slicing and not in\nAlist[:] = [ j for i, j in enumerate(Alist)\nif i not in idx_list ]\n\n# Print result\nprint(\"List after deleted elements : \" ,Alist)"
},
{
"code": null,
"e": 2818,
"s": 2763,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2920,
"s": 2818,
"text": "Given list is : [11, 6, 8, 3, 2]\nThe indices list is : [1, 3, 0]\nList after deleted elements : [8, 2]"
}
] |
DOM - DOMException Object
|
The DOMException represents an abnormal event happening when a method or a property is used.
Below table lists the properties of the DOMException object
name
Returns a DOMString that contains one of the string associated with an error constant (as seen the table below).
IndexSizeError
The index is not in the allowed range. For example, this can be thrown by the Range object. (Legacy code value: 1 and legacy constant name: INDEX_SIZE_ERR)
HierarchyRequestError
The node tree hierarchy is not correct. (Legacy code value: 3 and legacy constant name: HIERARCHY_REQUEST_ERR)
WrongDocumentError
The object is in the wrong document. (Legacy code value: 4 and legacy constant name: WRONG_DOCUMENT_ERR)
InvalidCharacterError
The string contains invalid characters. (Legacy code value: 5 and legacy constant name: INVALID_CHARACTER_ERR)
NoModificationAllowedError
The object cannot be modified. (Legacy code value: 7 and legacy constant name: NO_MODIFICATION_ALLOWED_ERR)
NotFoundError
The object cannot be found here. (Legacy code value: 8 and legacy constant name: NOT_FOUND_ERR)
NotSupportedError
The operation is not supported. (Legacy code value: 9 and legacy constant name: NOT_SUPPORTED_ERR)
InvalidStateError
The object is in an invalid state. (Legacy code value: 11 and legacy constant name: INVALID_STATE_ERR)
SyntaxError
The string did not match the expected pattern. (Legacy code value: 12 and legacy constant name: SYNTAX_ERR)
InvalidModificationError
The object cannot be modified in this way. (Legacy code value: 13 and legacy constant name: INVALID_MODIFICATION_ERR)
NamespaceError
The operation is not allowed by Namespaces in XML. (Legacy code value: 14 and legacy constant name: NAMESPACE_ERR)
InvalidAccessError
The object does not support the operation or argument. (Legacy code value: 15 and legacy constant name: INVALID_ACCESS_ERR)
TypeMismatchError
The type of the object does not match the expected type. (Legacy code value: 17 and legacy constant name: TYPE_MISMATCH_ERR) This value is deprecated, the JavaScript TypeError exception is now raised instead of a DOMException with this value.
SecurityError
The operation is insecure. (Legacy code value: 18 and legacy constant name: SECURITY_ERR)
NetworkError
A network error occurred. (Legacy code value: 19 and legacy constant name: NETWORK_ERR)
AbortError
The operation was aborted. (Legacy code value: 20 and legacy constant name: ABORT_ERR)
URLMismatchError
The given URL does not match another URL. (Legacy code value: 21 and legacy constant name: URL_MISMATCH_ERR)
QuotaExceededError
The quota has been exceeded. (Legacy code value: 22 and legacy constant name: QUOTA_EXCEEDED_ERR)
TimeoutError
The operation timed out. (Legacy code value: 23 and legacy constant name: TIMEOUT_ERR)
InvalidNodeTypeError
The node is incorrect or has an incorrect ancestor for this operation. (Legacy code value: 24 and legacy constant name: INVALID_NODE_TYPE_ERR)
DataCloneError
The object cannot be cloned. (Legacy code value: 25 and legacy constant name: DATA_CLONE_ERR)
EncodingError
The encoding operation, being an encoding or a decoding one, failed (No legacy code value and constant name).
NotReadableError
The input/output read operation failed (No legacy code value and constant name).
Following example demonstrates how using a not well-formed XML document causes a DOMException.
error.xml contents are as below −
<?xml version = "1.0" encoding = "UTF-8" standalone = "no" ?>
<Company id = "companyid">
<Employee category = "Technical" id = "firstelement" type = "text/html">
<FirstName>Tanmay</first>
<LastName>Patil</LastName>
<ContactNo>1234567890</ContactNo>
<Email>tanmaypatil@xyz.com</Email>
</Employee>
</Company>
Following example demonstrates the usage of the name attribute −
<html>
<head>
<script>
function loadXMLDoc(filename) {
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else // code for IE5 and IE6 {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",filename,false);
xhttp.send();
return xhttp.responseXML;
}
</script>
</head>
<body>
<script>
try {
xmlDoc = loadXMLDoc("/dom/error.xml");
var node = xmlDoc.getElementsByTagName("to").item(0);
var refnode = node.nextSibling;
var newnode = xmlDoc.createTextNode('That is why you fail.');
node.insertBefore(newnode, refnode);
} catch(err) {
document.write(err.name);
}
</script>
</body>
</html>
Save this file as domexcption_name.html on the server path (this file and error.xml should be on the same path in your server). We will get the output as shown below −
TypeError
41 Lectures
5 hours
Abhishek And Pukhraj
33 Lectures
3.5 hours
Abhishek And Pukhraj
15 Lectures
1 hours
Zach Miller
15 Lectures
4 hours
Prof. Paul Cline, Ed.D
13 Lectures
4 hours
Prof. Paul Cline, Ed.D
17 Lectures
2 hours
Laurence Svekis
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2381,
"s": 2288,
"text": "The DOMException represents an abnormal event happening when a method or a property is used."
},
{
"code": null,
"e": 2441,
"s": 2381,
"text": "Below table lists the properties of the DOMException object"
},
{
"code": null,
"e": 2446,
"s": 2441,
"text": "name"
},
{
"code": null,
"e": 2559,
"s": 2446,
"text": "Returns a DOMString that contains one of the string associated with an error constant (as seen the table below)."
},
{
"code": null,
"e": 2574,
"s": 2559,
"text": "IndexSizeError"
},
{
"code": null,
"e": 2730,
"s": 2574,
"text": "The index is not in the allowed range. For example, this can be thrown by the Range object. (Legacy code value: 1 and legacy constant name: INDEX_SIZE_ERR)"
},
{
"code": null,
"e": 2752,
"s": 2730,
"text": "HierarchyRequestError"
},
{
"code": null,
"e": 2863,
"s": 2752,
"text": "The node tree hierarchy is not correct. (Legacy code value: 3 and legacy constant name: HIERARCHY_REQUEST_ERR)"
},
{
"code": null,
"e": 2882,
"s": 2863,
"text": "WrongDocumentError"
},
{
"code": null,
"e": 2987,
"s": 2882,
"text": "The object is in the wrong document. (Legacy code value: 4 and legacy constant name: WRONG_DOCUMENT_ERR)"
},
{
"code": null,
"e": 3009,
"s": 2987,
"text": "InvalidCharacterError"
},
{
"code": null,
"e": 3120,
"s": 3009,
"text": "The string contains invalid characters. (Legacy code value: 5 and legacy constant name: INVALID_CHARACTER_ERR)"
},
{
"code": null,
"e": 3147,
"s": 3120,
"text": "NoModificationAllowedError"
},
{
"code": null,
"e": 3255,
"s": 3147,
"text": "The object cannot be modified. (Legacy code value: 7 and legacy constant name: NO_MODIFICATION_ALLOWED_ERR)"
},
{
"code": null,
"e": 3269,
"s": 3255,
"text": "NotFoundError"
},
{
"code": null,
"e": 3365,
"s": 3269,
"text": "The object cannot be found here. (Legacy code value: 8 and legacy constant name: NOT_FOUND_ERR)"
},
{
"code": null,
"e": 3383,
"s": 3365,
"text": "NotSupportedError"
},
{
"code": null,
"e": 3482,
"s": 3383,
"text": "The operation is not supported. (Legacy code value: 9 and legacy constant name: NOT_SUPPORTED_ERR)"
},
{
"code": null,
"e": 3500,
"s": 3482,
"text": "InvalidStateError"
},
{
"code": null,
"e": 3603,
"s": 3500,
"text": "The object is in an invalid state. (Legacy code value: 11 and legacy constant name: INVALID_STATE_ERR)"
},
{
"code": null,
"e": 3615,
"s": 3603,
"text": "SyntaxError"
},
{
"code": null,
"e": 3723,
"s": 3615,
"text": "The string did not match the expected pattern. (Legacy code value: 12 and legacy constant name: SYNTAX_ERR)"
},
{
"code": null,
"e": 3748,
"s": 3723,
"text": "InvalidModificationError"
},
{
"code": null,
"e": 3866,
"s": 3748,
"text": "The object cannot be modified in this way. (Legacy code value: 13 and legacy constant name: INVALID_MODIFICATION_ERR)"
},
{
"code": null,
"e": 3881,
"s": 3866,
"text": "NamespaceError"
},
{
"code": null,
"e": 3996,
"s": 3881,
"text": "The operation is not allowed by Namespaces in XML. (Legacy code value: 14 and legacy constant name: NAMESPACE_ERR)"
},
{
"code": null,
"e": 4015,
"s": 3996,
"text": "InvalidAccessError"
},
{
"code": null,
"e": 4139,
"s": 4015,
"text": "The object does not support the operation or argument. (Legacy code value: 15 and legacy constant name: INVALID_ACCESS_ERR)"
},
{
"code": null,
"e": 4157,
"s": 4139,
"text": "TypeMismatchError"
},
{
"code": null,
"e": 4400,
"s": 4157,
"text": "The type of the object does not match the expected type. (Legacy code value: 17 and legacy constant name: TYPE_MISMATCH_ERR) This value is deprecated, the JavaScript TypeError exception is now raised instead of a DOMException with this value."
},
{
"code": null,
"e": 4414,
"s": 4400,
"text": "SecurityError"
},
{
"code": null,
"e": 4504,
"s": 4414,
"text": "The operation is insecure. (Legacy code value: 18 and legacy constant name: SECURITY_ERR)"
},
{
"code": null,
"e": 4517,
"s": 4504,
"text": "NetworkError"
},
{
"code": null,
"e": 4605,
"s": 4517,
"text": "A network error occurred. (Legacy code value: 19 and legacy constant name: NETWORK_ERR)"
},
{
"code": null,
"e": 4616,
"s": 4605,
"text": "AbortError"
},
{
"code": null,
"e": 4703,
"s": 4616,
"text": "The operation was aborted. (Legacy code value: 20 and legacy constant name: ABORT_ERR)"
},
{
"code": null,
"e": 4720,
"s": 4703,
"text": "URLMismatchError"
},
{
"code": null,
"e": 4829,
"s": 4720,
"text": "The given URL does not match another URL. (Legacy code value: 21 and legacy constant name: URL_MISMATCH_ERR)"
},
{
"code": null,
"e": 4848,
"s": 4829,
"text": "QuotaExceededError"
},
{
"code": null,
"e": 4946,
"s": 4848,
"text": "The quota has been exceeded. (Legacy code value: 22 and legacy constant name: QUOTA_EXCEEDED_ERR)"
},
{
"code": null,
"e": 4959,
"s": 4946,
"text": "TimeoutError"
},
{
"code": null,
"e": 5046,
"s": 4959,
"text": "The operation timed out. (Legacy code value: 23 and legacy constant name: TIMEOUT_ERR)"
},
{
"code": null,
"e": 5067,
"s": 5046,
"text": "InvalidNodeTypeError"
},
{
"code": null,
"e": 5210,
"s": 5067,
"text": "The node is incorrect or has an incorrect ancestor for this operation. (Legacy code value: 24 and legacy constant name: INVALID_NODE_TYPE_ERR)"
},
{
"code": null,
"e": 5225,
"s": 5210,
"text": "DataCloneError"
},
{
"code": null,
"e": 5319,
"s": 5225,
"text": "The object cannot be cloned. (Legacy code value: 25 and legacy constant name: DATA_CLONE_ERR)"
},
{
"code": null,
"e": 5333,
"s": 5319,
"text": "EncodingError"
},
{
"code": null,
"e": 5443,
"s": 5333,
"text": "The encoding operation, being an encoding or a decoding one, failed (No legacy code value and constant name)."
},
{
"code": null,
"e": 5460,
"s": 5443,
"text": "NotReadableError"
},
{
"code": null,
"e": 5541,
"s": 5460,
"text": "The input/output read operation failed (No legacy code value and constant name)."
},
{
"code": null,
"e": 5636,
"s": 5541,
"text": "Following example demonstrates how using a not well-formed XML document causes a DOMException."
},
{
"code": null,
"e": 5670,
"s": 5636,
"text": "error.xml contents are as below −"
},
{
"code": null,
"e": 6007,
"s": 5670,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\" standalone = \"no\" ?>\n<Company id = \"companyid\">\n <Employee category = \"Technical\" id = \"firstelement\" type = \"text/html\">\n <FirstName>Tanmay</first>\n <LastName>Patil</LastName>\n <ContactNo>1234567890</ContactNo>\n <Email>tanmaypatil@xyz.com</Email>\n </Employee>\n</Company>"
},
{
"code": null,
"e": 6072,
"s": 6007,
"text": "Following example demonstrates the usage of the name attribute −"
},
{
"code": null,
"e": 6934,
"s": 6072,
"text": "<html>\n <head>\n <script>\n function loadXMLDoc(filename) {\n if (window.XMLHttpRequest) {\n xhttp = new XMLHttpRequest();\n } else // code for IE5 and IE6 {\n xhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xhttp.open(\"GET\",filename,false);\n xhttp.send();\n return xhttp.responseXML;\n }\n </script>\n </head>\n <body>\n <script>\n try {\n xmlDoc = loadXMLDoc(\"/dom/error.xml\");\n var node = xmlDoc.getElementsByTagName(\"to\").item(0);\n var refnode = node.nextSibling;\n var newnode = xmlDoc.createTextNode('That is why you fail.');\n node.insertBefore(newnode, refnode);\n } catch(err) {\n document.write(err.name);\n }\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 7102,
"s": 6934,
"text": "Save this file as domexcption_name.html on the server path (this file and error.xml should be on the same path in your server). We will get the output as shown below −"
},
{
"code": null,
"e": 7113,
"s": 7102,
"text": "TypeError\n"
},
{
"code": null,
"e": 7146,
"s": 7113,
"text": "\n 41 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 7168,
"s": 7146,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 7203,
"s": 7168,
"text": "\n 33 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 7225,
"s": 7203,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 7258,
"s": 7225,
"text": "\n 15 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7271,
"s": 7258,
"text": " Zach Miller"
},
{
"code": null,
"e": 7304,
"s": 7271,
"text": "\n 15 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 7328,
"s": 7304,
"text": " Prof. Paul Cline, Ed.D"
},
{
"code": null,
"e": 7361,
"s": 7328,
"text": "\n 13 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 7385,
"s": 7361,
"text": " Prof. Paul Cline, Ed.D"
},
{
"code": null,
"e": 7418,
"s": 7385,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7435,
"s": 7418,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 7442,
"s": 7435,
"text": " Print"
},
{
"code": null,
"e": 7453,
"s": 7442,
"text": " Add Notes"
}
] |
Working with PDF files in Python?
|
Python is a very versatile language as it provides huge set of libraries to work on different requirements. We all work on Portable Document Format (PDF) files. Python provides different ways to work with pdf files. In this we are going to use python library called PyPDF2 to work with pdf file.
PyPDF2 is a pure-python PDF library capable of splitting, merging together, cropping, and transforming the pages of PDF files. It can also add custom data, viewing options, and passwords to PDF files. It can retrieve text and metadata from PDFs as well as merge entire files together.
As we can do multiple operations on PDFs with PyPDF2, so it acts like a Swiss-army knife.
Because pypdf2 is an standard python package, so we need to install it. Good thing is it’s very easy, we can use pip to install it. Simply run below command on your command terminal:
C:\Users\rajesh>pip install pypdf2
Collecting pypdf2
Downloading https://files.pythonhosted.org/packages/b4/01/68fcc0d43daf4c6bdbc6b33cc3f77bda531c86b174cac56ef0ffdb96faab/PyPDF2-1.26.0.tar.gz (77kB)
100% |████████████████████████████████| 81kB 83kB/s
Building wheels for collected packages: pypdf2
Building wheel for pypdf2 (setup.py) ... done
Stored in directory: C:\Users\rajesh\AppData\Local\pip\Cache\wheels\53\84\19\35bc977c8bf5f0c23a8a011aa958acd4da4bbd7a229315c1b7
Successfully built pypdf2
Installing collected packages: pypdf2
Successfully installed pypdf2-1.26.0
To verify, import pypdf2 from python shell
>>> import PyPDF2
>>>
Successful, Great.
We can extract some of the important useful data from any pdf. For example, we can extract the information on author of the document, its title, subject and the number of pages contained in the pdf file.
Below is the python program to extract useful information from the pdf file using pypdf2 package.
from PyPDF2 import PdfFileReader
def extract_pdfMeta(path):
with open(path, 'rb') as f:
pdf = PdfFileReader(f)
info = pdf.getDocumentInfo()
number_of_pages = pdf.getNumPages()
print("Author: \t", info.author)
print()
print("Creator: \t", info.creator)
print()
print("Producer: \t",info.producer)
print()
print("Subject: \t", info.subject)
print()
print("title: \t",info.title)
print()
print("Number of Pages in pdf: \t",number_of_pages)
if __name__ == '__main__':
path = 'DeepLearning.pdf'
extract_pdfMeta(path)
Author: Nikhil Buduma,Nicholas Locascio
Creator: AH CSS Formatter V6.2 MR4 for Linux64 : 6.2.6.18551 (2014/09/24 15:00JST)
Producer: Antenna House PDF Output Library 6.2.609 (Linux64)
Subject: None
title: Fundamentals of Deep Learning
Number of Pages in pdf: 298
So without opening pdf files, we are able to get some useful information from the pdf file.
We can extract text from the pdfs. Though it have built-in support for extracting images.
Let’s try to extract text from a particular page (for example: page 50) of the pdfs file we downloaded above.
#Import pypdf2
from PyPDF2 import PdfFileReader
def extract_pdfText(path):
with open(path, 'rb') as f:
pdf = PdfFileReader(f)
# get the 50th page
page = pdf.getPage(50)
print(page)
print('Page type: {}'.format(str(type(page))))
#Extract text from the 50th page
text = page.extractText()
print(text)
if __name__ == '__main__':
path = 'DeepLearning.pdf'
extract_pdfText(path)
{'/Annots': IndirectObject(1421, 0),
'/Contents': IndirectObject(179, 0),
'/CropBox': [0, 0, 595.3, 841.9],
'/Group': {'/CS': '/DeviceRGB', '/S': '/Transparency', '/Type': '/Group'},
'/MediaBox': [0, 0, 504, 661.5],
'/Parent': IndirectObject(4863, 0),
'/Resources': IndirectObject(1423, 0),
'/Rotate': 0,
'/Type':
'/Page'
}
Page type: <class 'PyPDF2.pdf.PageObject'>
time. In inverted dropout, any neuron whose activation hasn†t been silenced has its
output divided by p before the value is propagated to the next layer. With this
fix, Eoutput=p⁄xp+1ƒ
p⁄0=
x, and we can avoid arbitrarily scaling neuronal
output at test time.
SummaryIn this chapter, we†ve learned all of the basics involved in training feed-forward neural
networks. We†ve talked about gradient descent, the backpropagation algorithm, as
well as various methods we can use to prevent overfitting. In the next chapter, we†ll
put these lessons into practice when we use the TensorFlow library to efficiently
implement our first neural networks. Then in
Chapter 4
, we†ll return to the problem
of optimizing objective functions for training neural networks and design algorithmsto significantly improve performance. These improvements will enable us to process
much more data, which means we†ll be able to build more comprehensive models.
Summary | 37
Though we are able to get some text from the page 50 but it’s not that clean. Unfortunately, pypdf2 has a very limited support for extracting text from pdfs.
>>> import PyPDF2
>>> deeplearningFile = open('DeepLearning.pdf', 'rb')
>>> pdfReader = PyPDF2.PdfFileReader(deeplearningFile)
>>> page = pdfReader.getPage(0)
>>> page.rotateClockwise(90)
{
'/Contents': [IndirectObject(4870, 0), IndirectObject(4871, 0), IndirectObject(4872, 0), IndirectObject(4873, 0), IndirectObject(4874, 0), IndirectObject(4875, 0), IndirectObject(4876, 0), IndirectObject(4877, 0)],
'/CropBox': [0, 0, 595.3, 841.9],
'/MediaBox': [0, 0, 504, 661.5], '/Parent': IndirectObject(4862, 0), '/Resources': IndirectObject(4889, 0),
'/Rotate': 90,
/Type': '/Page'
}
>>> pdfWriter = PyPDF2.PdfFileWriter()
>>> pdfWriter.addPage(page)
>>> resultPdfFile = open('rotatedPage.pdf', 'wb')
>>> pdfWriter.write(resultPdfFile)
>>> resultPdfFile.close()
>>> deeplearningFile.close()
|
[
{
"code": null,
"e": 1358,
"s": 1062,
"text": "Python is a very versatile language as it provides huge set of libraries to work on different requirements. We all work on Portable Document Format (PDF) files. Python provides different ways to work with pdf files. In this we are going to use python library called PyPDF2 to work with pdf file."
},
{
"code": null,
"e": 1643,
"s": 1358,
"text": "PyPDF2 is a pure-python PDF library capable of splitting, merging together, cropping, and transforming the pages of PDF files. It can also add custom data, viewing options, and passwords to PDF files. It can retrieve text and metadata from PDFs as well as merge entire files together."
},
{
"code": null,
"e": 1733,
"s": 1643,
"text": "As we can do multiple operations on PDFs with PyPDF2, so it acts like a Swiss-army knife."
},
{
"code": null,
"e": 1916,
"s": 1733,
"text": "Because pypdf2 is an standard python package, so we need to install it. Good thing is it’s very easy, we can use pip to install it. Simply run below command on your command terminal:"
},
{
"code": null,
"e": 2490,
"s": 1916,
"text": "C:\\Users\\rajesh>pip install pypdf2\nCollecting pypdf2\nDownloading https://files.pythonhosted.org/packages/b4/01/68fcc0d43daf4c6bdbc6b33cc3f77bda531c86b174cac56ef0ffdb96faab/PyPDF2-1.26.0.tar.gz (77kB)\n100% |████████████████████████████████| 81kB 83kB/s\nBuilding wheels for collected packages: pypdf2\nBuilding wheel for pypdf2 (setup.py) ... done\nStored in directory: C:\\Users\\rajesh\\AppData\\Local\\pip\\Cache\\wheels\\53\\84\\19\\35bc977c8bf5f0c23a8a011aa958acd4da4bbd7a229315c1b7\nSuccessfully built pypdf2\nInstalling collected packages: pypdf2\nSuccessfully installed pypdf2-1.26.0"
},
{
"code": null,
"e": 2533,
"s": 2490,
"text": "To verify, import pypdf2 from python shell"
},
{
"code": null,
"e": 2574,
"s": 2533,
"text": ">>> import PyPDF2\n>>>\nSuccessful, Great."
},
{
"code": null,
"e": 2778,
"s": 2574,
"text": "We can extract some of the important useful data from any pdf. For example, we can extract the information on author of the document, its title, subject and the number of pages contained in the pdf file."
},
{
"code": null,
"e": 2876,
"s": 2778,
"text": "Below is the python program to extract useful information from the pdf file using pypdf2 package."
},
{
"code": null,
"e": 3448,
"s": 2876,
"text": "from PyPDF2 import PdfFileReader\ndef extract_pdfMeta(path):\n with open(path, 'rb') as f:\n pdf = PdfFileReader(f)\n info = pdf.getDocumentInfo()\n number_of_pages = pdf.getNumPages()\n print(\"Author: \\t\", info.author)\n print()\n print(\"Creator: \\t\", info.creator)\n print()\n print(\"Producer: \\t\",info.producer)\n print()\n print(\"Subject: \\t\", info.subject)\n print()\n print(\"title: \\t\",info.title)\n print()\n print(\"Number of Pages in pdf: \\t\",number_of_pages)\nif __name__ == '__main__':\n path = 'DeepLearning.pdf'\n extract_pdfMeta(path)"
},
{
"code": null,
"e": 3716,
"s": 3448,
"text": "Author: Nikhil Buduma,Nicholas Locascio\n\nCreator: AH CSS Formatter V6.2 MR4 for Linux64 : 6.2.6.18551 (2014/09/24 15:00JST)\n\nProducer: Antenna House PDF Output Library 6.2.609 (Linux64)\n\nSubject: None\n\ntitle: Fundamentals of Deep Learning\n\nNumber of Pages in pdf: 298"
},
{
"code": null,
"e": 3808,
"s": 3716,
"text": "So without opening pdf files, we are able to get some useful information from the pdf file."
},
{
"code": null,
"e": 3898,
"s": 3808,
"text": "We can extract text from the pdfs. Though it have built-in support for extracting images."
},
{
"code": null,
"e": 4008,
"s": 3898,
"text": "Let’s try to extract text from a particular page (for example: page 50) of the pdfs file we downloaded above."
},
{
"code": null,
"e": 4439,
"s": 4008,
"text": "#Import pypdf2\nfrom PyPDF2 import PdfFileReader\ndef extract_pdfText(path):\n with open(path, 'rb') as f:\n pdf = PdfFileReader(f)\n # get the 50th page\n page = pdf.getPage(50)\n print(page)\n print('Page type: {}'.format(str(type(page))))\n #Extract text from the 50th page\n text = page.extractText()\n print(text)\nif __name__ == '__main__':\n path = 'DeepLearning.pdf'\n extract_pdfText(path)"
},
{
"code": null,
"e": 5758,
"s": 4439,
"text": "{'/Annots': IndirectObject(1421, 0),\n'/Contents': IndirectObject(179, 0),\n'/CropBox': [0, 0, 595.3, 841.9],\n'/Group': {'/CS': '/DeviceRGB', '/S': '/Transparency', '/Type': '/Group'},\n'/MediaBox': [0, 0, 504, 661.5],\n'/Parent': IndirectObject(4863, 0),\n'/Resources': IndirectObject(1423, 0),\n'/Rotate': 0,\n'/Type':\n'/Page'\n}\n\nPage type: <class 'PyPDF2.pdf.PageObject'>\ntime. In inverted dropout, any neuron whose activation hasn†t been silenced has its\noutput divided by p before the value is propagated to the next layer. With this\nfix, Eoutput=p⁄xp+1ƒ\np⁄0=\nx, and we can avoid arbitrarily scaling neuronal\noutput at test time.\n\nSummaryIn this chapter, we†ve learned all of the basics involved in training feed-forward neural\nnetworks. We†ve talked about gradient descent, the backpropagation algorithm, as\nwell as various methods we can use to prevent overfitting. In the next chapter, we†ll\nput these lessons into practice when we use the TensorFlow library to efficiently\nimplement our first neural networks. Then in\nChapter 4\n\n, we†ll return to the problem\nof optimizing objective functions for training neural networks and design algorithmsto significantly improve performance. These improvements will enable us to process\nmuch more data, which means we†ll be able to build more comprehensive models.\nSummary | 37"
},
{
"code": null,
"e": 5916,
"s": 5758,
"text": "Though we are able to get some text from the page 50 but it’s not that clean. Unfortunately, pypdf2 has a very limited support for extracting text from pdfs."
},
{
"code": null,
"e": 6705,
"s": 5916,
"text": ">>> import PyPDF2\n>>> deeplearningFile = open('DeepLearning.pdf', 'rb')\n>>> pdfReader = PyPDF2.PdfFileReader(deeplearningFile)\n>>> page = pdfReader.getPage(0)\n>>> page.rotateClockwise(90)\n{\n'/Contents': [IndirectObject(4870, 0), IndirectObject(4871, 0), IndirectObject(4872, 0), IndirectObject(4873, 0), IndirectObject(4874, 0), IndirectObject(4875, 0), IndirectObject(4876, 0), IndirectObject(4877, 0)],\n\n'/CropBox': [0, 0, 595.3, 841.9],\n\n'/MediaBox': [0, 0, 504, 661.5], '/Parent': IndirectObject(4862, 0), '/Resources': IndirectObject(4889, 0),\n'/Rotate': 90,\n/Type': '/Page'\n}\n>>> pdfWriter = PyPDF2.PdfFileWriter()\n>>> pdfWriter.addPage(page)\n>>> resultPdfFile = open('rotatedPage.pdf', 'wb')\n>>> pdfWriter.write(resultPdfFile)\n>>> resultPdfFile.close()\n>>> deeplearningFile.close()"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.