title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Binomial Random Variables and Binomial Distribution - Probability | Class 12 Maths - GeeksforGeeks
|
02 Aug, 2021
A Binomial random variable can be defined by two possible outcomes such as “success” and a “failure”. For instance, consider rolling a fair six-sided die and recording the value of the face. The binomial distribution formula can be put into use to calculate the probability of success for binomial distributions. Often it states “plugin” the numbers to the formula and calculates the requisite values.
The binomial distribution is based upon the following characteristics:
The experiment contains n identical trials.
Each trial results in one of the two outcomes either success or failure.
The probability of success, denoted p, remains the same from trial to trial.
All the n trials are independent.
In order to recognize the binomial variable, the following conditions are applicable:-
Fixed number of trials.
Every trial is independent of one another.
Each trail has two possibilities.SuccessFailure
Success
Failure
Probability for success is defined by (p) and probability for failure is defined by (1-q).
For Example, consider the following instance
A fair coin is flipped 20 times; X represents the number of heads.
X is binomial with n = 20 and p = 0.5.
If the above four conditions are satisfied then the random variable (n)=number of successes(p) in trials is a binomial random variable with
The Mean (Expected Value) is: μ = Σxp
The Variance is: Var(X) = Σx2p − μ2
The Standard Deviation is: σ = √Var(X)
The 10% condition of assuming independence defines that sample sizes should be no more than 10% of the population.
The 10% Rule of Assuming Independence condition normally applies to the following cases:-
While drawing samples without replacement. For Example, In the Central Limit Theorem.
When proportions from two groups are there
Solving differences of means for very small populations or an extremely large sample.
While dealing with Bernoulli trials.
Note: Usually,10% of conditions mentioned won’t find statistical means. For means, the samples are usually smaller, making the condition necessary only if sampling from a very small population.
The condition applies in Bernoulli trials, where the vast majority of cases you sample without replacement.
A binomial distribution is defined as the probability of a SUCCESS or FAILURE outcome in an experiment that is repeated multiple times. For example, in a coin toss experiment heads or tails and taking a test could have two possible outcomes- Pass or Fail.
In the binomial formula, the number of times the experiment runs is denoted by n
The probability of one specific outcome is denoted by p.
For Example, In an experiment to know the probability of getting a 5 on a die roll. If you were to roll a die 10 times, the probability of rolling a one on any throw is 1/6. Roll ten times and you have a binomial distribution of (n = 10, p = 1/6).
SUCCESS = if the roll is 5 on a die.
FAILURE = if the roll on die is other than 5.
The binomial distribution formula is:
b(x; n, P) = nCx * Px * (1 – P)n – x
where:
b = defined as a binomial probability
x = It is the total number of “successes” (pass or fail, heads or tails, etc.)
P = The probability of success on an individual trial
n = Defines the number of trials
Note: The above mentioned Binomial Formula can also be written as :
nCx = n! / x!(n – x)!
Consider a trial of n Independent binomial distribution. SUCCESS in ‘n’ independent is trials is defined by probability ‘p’ in binomial distribution with parameters n and p.
For Instance, in an experiment of tossing a fair coin. The number of heads in 20 tosses of a coin has a binomial distribution with parameters
n = 20 and p = 50%.
The expected value of the binomial distribution is defined as follows:
n × p
The standard error of the binomial distribution is defined as
(n × p × (1 – p))1⁄2
If the following four conditions are met then the random variable is binomial:
Fixed number of trials = n
Each trial has two possible outcomes:successfailure.
success
failure.
The probability of success is stated = p
All the trials should be independent which means that one trail output should not depend on others.
In an experiment of tossing a fair coin 10 times, then the probability of getting exactly 6 heads can be calculated as:
b(x; n, P) – nCx * Px * (1 – P)n – x
Example:
The number of trials (n) = 10
Success (“tossing ahead”) = 0.5
q= 1 – p = 0.5, x = 6
Solution:
P(x = 6) = 10C6 * 0.5^6 * 0.5^4
= 210 * 0.015625 * 0.0625
P(x = 6) = 0.205078125
Binomial Probability Formula :
then solving the above results into,
It can also simply written as,
P(X = r) = Combinations × P(yes) × P(no)
The combinations, here’s the formula:
The outcomes of the binomial distributions are usually depicted as SUCCESS and FAILURE. The usual notations which are used to denote such notations are
p = probability of success,
q = probability of failure = 1 – p
Therefore, p + q = 1.
In a Bernoulli trial, each repetition of an experiment involves only 2 outcomes.
Independent – In this, the result of one trial does not affect the result of another trial.Repeated – In this, conditions remain the same in each trial. It states that p and q remain constant across trials.
Independent – In this, the result of one trial does not affect the result of another trial.
Repeated – In this, conditions remain the same in each trial. It states that p and q remain constant across trials.
In a binomial distribution,
The probabilities of interest are those of receiving a certain number of successes = r,
In n independent trials each having only two possible outcomes and the same probability, p, of success.
Following defined is the number of different ways which shows N distinct things may be arranged in order is
N! = (1)(2)(3)...(N-1)(N), (where 0! = 1)
Below mentioned are the number of ways of selecting r distinct combinations of N objects, irrespective of a valid order, is represented as
Let’s apply the formula binom{n-1}{k-1} to this expression and simplify the result is shown below:
Furthermore,
Following the properties of the factorial function as shown below:
Use the above formula to derive the property of the binomial coefficient,
now using the commutative property of multiplication (x . y = y . x), the right-hand side can be rewritten as,
Now, using the above equations we can equate,
Now, the final identity can be concluded as,
Consider a scenario to find the best free-throw shooter on your high school basketball team. To find a season free throw percentage, Free Throw Binomial Distribution is put into use
For this, consider an example of Graphing Binomial Distribution:
Consider variable p that will represent the free throw percentage of your best free throw shooter. If the accuracy of the shooting throw is 90%
Then p = 0.9, p represents the probability of a “success”
To find the probability the athlete will make 3 out of 10 shots if his free throw percentage is 90%.
Using the binomial formula:
b(x; n, P) – nCx * Px * (1 – P)n – x
Using the calculator: binompdf (10, 0.90, 3).
Example:
similarly, by calculating values from P(X = 2) to P(X = 10) following values are obtained :
Solution:
Considering the above values following graph is obtained:
Binomial distribution n=10, p=2
The binompdf function on TI 83 or 84 calculators is used for finding the probability of exactly some number of successes.
P(X = c) = binompdf(n, p, c)
where,
n = number of trails
p = number of success
c = probability of exactly c success, for number c.
Example: A fair coin is tossed 100 times. What is the binompdf probability that heads will appear exactly 52 times?
Solution: Using the Binomial formula
= binompdf (number of trials, probability of occurrence, number of specific events)
= binompdf (n, p, r)
The binomcdf function on the TI-84 calculator. It can be used to solve problems where probability is less than or equal to a number of successes out of a certain number of trials.
Example: To calculate the probability of less than or equal to 45 successes out of 100 trials, the following method is used;
P(X = c) = binomcdf(n, p, c)
where,
n = the number of trials
p = the probability of success for any particular trial
c = number of successes.
Example 4: A fair coin is tossed 100 times. What is the probability binomcdf there will be at most 52 heads?
Solution:
binomcdf (number of trials, probability of occurrence, number of specific events)
= binomcdf (n, p, r)
Example: In a burger shop 70% of people preferred to eat a non-veg burger while others prefer to eat something else. What is the probability of selling 2 non-veg burgers to the next 3 customers?
Solution:
The probabilities for “non-veg burger” all work out to be 0.147 because
0.147 = 0.7 × 0.7 × 0.3
Or, using exponents:= 0.72 × 0.31
The 0.7 is the probability of each choice we want, call it p
The 2 is the number of choices we want, call it k= pk × 0.31
The 0.3 is the probability of the opposite choice, so it is: 1−p
Using formula = pk(1 – p)(n – k)
Where p is the probability of each choice we want
k is the number of choices we want
n is the total number of choices
p = 0.7 (chance of non-veg burger)
k = 2 (non-veg burger choices)
n = 3 (total choices)
So we get: pk(1-p)(n-k) = 0.72(1-0.7)(3-2)
= 0.72(0.3)(1)
= 0.7 × 0.7 × 0.3
= 0.147
Three other possibilities are : (non-veg, non-veg, other) or (non-veg, other, non-veg) or (other, non-veg, non-veg)
n!k! / (n-k)! = 3!2!(3-2)!
= 3×2×12×1 × 1
= 3
3 (Number of outcomes we want ) × 0.147 (Probability of each outcome ) = 0.441
So, 70% choose non-veg burger, so 7 of the next 10 customers should choose non-veg burger
p = 0.7
n = 10
k = 7
And we get: pk(1-p)(n-k) = 0.77(1-0.7)(10-7)
= 0.77(0.3)(3)
= 0.0022235661
And the total number of those outcomes is:
n!k!/(n-k)! =10!7!/(10-7)!
= 10×9×8×7×6×5×4×3×2×17×6×5×4×3×2×1 × 3×2×1
= 10×9×83×2×1
=120
120 (Number of outcomes we want) × 0.0022235661(Probability of each outcome ) = 0.266827932
So the probability of 7 out of 10 choosing a non-veg burger is only about 27%
surinderdawra388
Picked
Class 12
School Learning
School Mathematics
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting Algorithms in Python
Cardinality in DBMS
SQL USE Database Statement
Querying Data from a Database using fetchone() and fetchall()
Intrinsic Semiconductors and Extrinsic Semiconductors
How to Align Text in HTML?
Cloud Deployment Models
Generations of Computers - Computer Fundamentals
Types of Computers
What is a Storage Device? Definition, Types, Examples
|
[
{
"code": null,
"e": 25829,
"s": 25801,
"text": "\n02 Aug, 2021"
},
{
"code": null,
"e": 26231,
"s": 25829,
"text": "A Binomial random variable can be defined by two possible outcomes such as “success” and a “failure”. For instance, consider rolling a fair six-sided die and recording the value of the face. The binomial distribution formula can be put into use to calculate the probability of success for binomial distributions. Often it states “plugin” the numbers to the formula and calculates the requisite values."
},
{
"code": null,
"e": 26302,
"s": 26231,
"text": "The binomial distribution is based upon the following characteristics:"
},
{
"code": null,
"e": 26346,
"s": 26302,
"text": "The experiment contains n identical trials."
},
{
"code": null,
"e": 26419,
"s": 26346,
"text": "Each trial results in one of the two outcomes either success or failure."
},
{
"code": null,
"e": 26496,
"s": 26419,
"text": "The probability of success, denoted p, remains the same from trial to trial."
},
{
"code": null,
"e": 26530,
"s": 26496,
"text": "All the n trials are independent."
},
{
"code": null,
"e": 26618,
"s": 26530,
"text": "In order to recognize the binomial variable, the following conditions are applicable:- "
},
{
"code": null,
"e": 26642,
"s": 26618,
"text": "Fixed number of trials."
},
{
"code": null,
"e": 26685,
"s": 26642,
"text": "Every trial is independent of one another."
},
{
"code": null,
"e": 26733,
"s": 26685,
"text": "Each trail has two possibilities.SuccessFailure"
},
{
"code": null,
"e": 26741,
"s": 26733,
"text": "Success"
},
{
"code": null,
"e": 26749,
"s": 26741,
"text": "Failure"
},
{
"code": null,
"e": 26840,
"s": 26749,
"text": "Probability for success is defined by (p) and probability for failure is defined by (1-q)."
},
{
"code": null,
"e": 26886,
"s": 26840,
"text": "For Example, consider the following instance "
},
{
"code": null,
"e": 26953,
"s": 26886,
"text": "A fair coin is flipped 20 times; X represents the number of heads."
},
{
"code": null,
"e": 26992,
"s": 26953,
"text": "X is binomial with n = 20 and p = 0.5."
},
{
"code": null,
"e": 27133,
"s": 26992,
"text": "If the above four conditions are satisfied then the random variable (n)=number of successes(p) in trials is a binomial random variable with "
},
{
"code": null,
"e": 27171,
"s": 27133,
"text": "The Mean (Expected Value) is: μ = Σxp"
},
{
"code": null,
"e": 27207,
"s": 27171,
"text": "The Variance is: Var(X) = Σx2p − μ2"
},
{
"code": null,
"e": 27246,
"s": 27207,
"text": "The Standard Deviation is: σ = √Var(X)"
},
{
"code": null,
"e": 27362,
"s": 27246,
"text": "The 10% condition of assuming independence defines that sample sizes should be no more than 10% of the population. "
},
{
"code": null,
"e": 27452,
"s": 27362,
"text": "The 10% Rule of Assuming Independence condition normally applies to the following cases:-"
},
{
"code": null,
"e": 27538,
"s": 27452,
"text": "While drawing samples without replacement. For Example, In the Central Limit Theorem."
},
{
"code": null,
"e": 27581,
"s": 27538,
"text": "When proportions from two groups are there"
},
{
"code": null,
"e": 27667,
"s": 27581,
"text": "Solving differences of means for very small populations or an extremely large sample."
},
{
"code": null,
"e": 27704,
"s": 27667,
"text": "While dealing with Bernoulli trials."
},
{
"code": null,
"e": 27898,
"s": 27704,
"text": "Note: Usually,10% of conditions mentioned won’t find statistical means. For means, the samples are usually smaller, making the condition necessary only if sampling from a very small population."
},
{
"code": null,
"e": 28006,
"s": 27898,
"text": "The condition applies in Bernoulli trials, where the vast majority of cases you sample without replacement."
},
{
"code": null,
"e": 28262,
"s": 28006,
"text": "A binomial distribution is defined as the probability of a SUCCESS or FAILURE outcome in an experiment that is repeated multiple times. For example, in a coin toss experiment heads or tails and taking a test could have two possible outcomes- Pass or Fail."
},
{
"code": null,
"e": 28343,
"s": 28262,
"text": "In the binomial formula, the number of times the experiment runs is denoted by n"
},
{
"code": null,
"e": 28400,
"s": 28343,
"text": "The probability of one specific outcome is denoted by p."
},
{
"code": null,
"e": 28649,
"s": 28400,
"text": "For Example, In an experiment to know the probability of getting a 5 on a die roll. If you were to roll a die 10 times, the probability of rolling a one on any throw is 1/6. Roll ten times and you have a binomial distribution of (n = 10, p = 1/6). "
},
{
"code": null,
"e": 28687,
"s": 28649,
"text": "SUCCESS = if the roll is 5 on a die. "
},
{
"code": null,
"e": 28733,
"s": 28687,
"text": "FAILURE = if the roll on die is other than 5."
},
{
"code": null,
"e": 28771,
"s": 28733,
"text": "The binomial distribution formula is:"
},
{
"code": null,
"e": 28810,
"s": 28771,
"text": "b(x; n, P) = nCx * Px * (1 – P)n – x "
},
{
"code": null,
"e": 28817,
"s": 28810,
"text": "where:"
},
{
"code": null,
"e": 28855,
"s": 28817,
"text": "b = defined as a binomial probability"
},
{
"code": null,
"e": 28934,
"s": 28855,
"text": "x = It is the total number of “successes” (pass or fail, heads or tails, etc.)"
},
{
"code": null,
"e": 28988,
"s": 28934,
"text": "P = The probability of success on an individual trial"
},
{
"code": null,
"e": 29021,
"s": 28988,
"text": "n = Defines the number of trials"
},
{
"code": null,
"e": 29089,
"s": 29021,
"text": "Note: The above mentioned Binomial Formula can also be written as :"
},
{
"code": null,
"e": 29113,
"s": 29089,
"text": "nCx = n! / x!(n – x)! "
},
{
"code": null,
"e": 29288,
"s": 29113,
"text": "Consider a trial of n Independent binomial distribution. SUCCESS in ‘n’ independent is trials is defined by probability ‘p’ in binomial distribution with parameters n and p. "
},
{
"code": null,
"e": 29430,
"s": 29288,
"text": "For Instance, in an experiment of tossing a fair coin. The number of heads in 20 tosses of a coin has a binomial distribution with parameters"
},
{
"code": null,
"e": 29450,
"s": 29430,
"text": "n = 20 and p = 50%."
},
{
"code": null,
"e": 29523,
"s": 29450,
"text": "The expected value of the binomial distribution is defined as follows: "
},
{
"code": null,
"e": 29530,
"s": 29523,
"text": "n × p "
},
{
"code": null,
"e": 29593,
"s": 29530,
"text": "The standard error of the binomial distribution is defined as "
},
{
"code": null,
"e": 29616,
"s": 29593,
"text": "(n × p × (1 – p))1⁄2 "
},
{
"code": null,
"e": 29696,
"s": 29616,
"text": " If the following four conditions are met then the random variable is binomial:"
},
{
"code": null,
"e": 29723,
"s": 29696,
"text": "Fixed number of trials = n"
},
{
"code": null,
"e": 29776,
"s": 29723,
"text": "Each trial has two possible outcomes:successfailure."
},
{
"code": null,
"e": 29784,
"s": 29776,
"text": "success"
},
{
"code": null,
"e": 29793,
"s": 29784,
"text": "failure."
},
{
"code": null,
"e": 29834,
"s": 29793,
"text": "The probability of success is stated = p"
},
{
"code": null,
"e": 29934,
"s": 29834,
"text": "All the trials should be independent which means that one trail output should not depend on others."
},
{
"code": null,
"e": 30054,
"s": 29934,
"text": "In an experiment of tossing a fair coin 10 times, then the probability of getting exactly 6 heads can be calculated as:"
},
{
"code": null,
"e": 30093,
"s": 30054,
"text": "b(x; n, P) – nCx * Px * (1 – P)n – x "
},
{
"code": null,
"e": 30102,
"s": 30093,
"text": "Example:"
},
{
"code": null,
"e": 30132,
"s": 30102,
"text": "The number of trials (n) = 10"
},
{
"code": null,
"e": 30164,
"s": 30132,
"text": "Success (“tossing ahead”) = 0.5"
},
{
"code": null,
"e": 30186,
"s": 30164,
"text": "q= 1 – p = 0.5, x = 6"
},
{
"code": null,
"e": 30196,
"s": 30186,
"text": "Solution:"
},
{
"code": null,
"e": 30229,
"s": 30196,
"text": "P(x = 6) = 10C6 * 0.5^6 * 0.5^4 "
},
{
"code": null,
"e": 30269,
"s": 30229,
"text": " = 210 * 0.015625 * 0.0625 "
},
{
"code": null,
"e": 30292,
"s": 30269,
"text": "P(x = 6) = 0.205078125"
},
{
"code": null,
"e": 30324,
"s": 30292,
"text": "Binomial Probability Formula : "
},
{
"code": null,
"e": 30363,
"s": 30326,
"text": "then solving the above results into,"
},
{
"code": null,
"e": 30397,
"s": 30365,
"text": "It can also simply written as, "
},
{
"code": null,
"e": 30438,
"s": 30397,
"text": "P(X = r) = Combinations × P(yes) × P(no)"
},
{
"code": null,
"e": 30476,
"s": 30438,
"text": "The combinations, here’s the formula:"
},
{
"code": null,
"e": 30629,
"s": 30476,
"text": "The outcomes of the binomial distributions are usually depicted as SUCCESS and FAILURE. The usual notations which are used to denote such notations are "
},
{
"code": null,
"e": 30657,
"s": 30629,
"text": "p = probability of success,"
},
{
"code": null,
"e": 30692,
"s": 30657,
"text": "q = probability of failure = 1 – p"
},
{
"code": null,
"e": 30714,
"s": 30692,
"text": "Therefore, p + q = 1."
},
{
"code": null,
"e": 30796,
"s": 30714,
"text": "In a Bernoulli trial, each repetition of an experiment involves only 2 outcomes. "
},
{
"code": null,
"e": 31003,
"s": 30796,
"text": "Independent – In this, the result of one trial does not affect the result of another trial.Repeated – In this, conditions remain the same in each trial. It states that p and q remain constant across trials."
},
{
"code": null,
"e": 31095,
"s": 31003,
"text": "Independent – In this, the result of one trial does not affect the result of another trial."
},
{
"code": null,
"e": 31211,
"s": 31095,
"text": "Repeated – In this, conditions remain the same in each trial. It states that p and q remain constant across trials."
},
{
"code": null,
"e": 31239,
"s": 31211,
"text": "In a binomial distribution,"
},
{
"code": null,
"e": 31327,
"s": 31239,
"text": "The probabilities of interest are those of receiving a certain number of successes = r,"
},
{
"code": null,
"e": 31431,
"s": 31327,
"text": "In n independent trials each having only two possible outcomes and the same probability, p, of success."
},
{
"code": null,
"e": 31539,
"s": 31431,
"text": "Following defined is the number of different ways which shows N distinct things may be arranged in order is"
},
{
"code": null,
"e": 31581,
"s": 31539,
"text": "N! = (1)(2)(3)...(N-1)(N), (where 0! = 1)"
},
{
"code": null,
"e": 31720,
"s": 31581,
"text": "Below mentioned are the number of ways of selecting r distinct combinations of N objects, irrespective of a valid order, is represented as"
},
{
"code": null,
"e": 31822,
"s": 31722,
"text": " Let’s apply the formula binom{n-1}{k-1} to this expression and simplify the result is shown below:"
},
{
"code": null,
"e": 31837,
"s": 31824,
"text": "Furthermore,"
},
{
"code": null,
"e": 31906,
"s": 31839,
"text": "Following the properties of the factorial function as shown below:"
},
{
"code": null,
"e": 31982,
"s": 31908,
"text": "Use the above formula to derive the property of the binomial coefficient,"
},
{
"code": null,
"e": 32095,
"s": 31984,
"text": "now using the commutative property of multiplication (x . y = y . x), the right-hand side can be rewritten as,"
},
{
"code": null,
"e": 32143,
"s": 32097,
"text": "Now, using the above equations we can equate,"
},
{
"code": null,
"e": 32190,
"s": 32145,
"text": "Now, the final identity can be concluded as,"
},
{
"code": null,
"e": 32375,
"s": 32192,
"text": "Consider a scenario to find the best free-throw shooter on your high school basketball team. To find a season free throw percentage, Free Throw Binomial Distribution is put into use "
},
{
"code": null,
"e": 32440,
"s": 32375,
"text": "For this, consider an example of Graphing Binomial Distribution:"
},
{
"code": null,
"e": 32585,
"s": 32440,
"text": "Consider variable p that will represent the free throw percentage of your best free throw shooter. If the accuracy of the shooting throw is 90% "
},
{
"code": null,
"e": 32644,
"s": 32585,
"text": "Then p = 0.9, p represents the probability of a “success”"
},
{
"code": null,
"e": 32747,
"s": 32644,
"text": "To find the probability the athlete will make 3 out of 10 shots if his free throw percentage is 90%. "
},
{
"code": null,
"e": 32775,
"s": 32747,
"text": "Using the binomial formula:"
},
{
"code": null,
"e": 32812,
"s": 32775,
"text": "b(x; n, P) – nCx * Px * (1 – P)n – x"
},
{
"code": null,
"e": 32859,
"s": 32812,
"text": "Using the calculator: binompdf (10, 0.90, 3)."
},
{
"code": null,
"e": 32868,
"s": 32859,
"text": "Example:"
},
{
"code": null,
"e": 32962,
"s": 32870,
"text": "similarly, by calculating values from P(X = 2) to P(X = 10) following values are obtained :"
},
{
"code": null,
"e": 32972,
"s": 32962,
"text": "Solution:"
},
{
"code": null,
"e": 33032,
"s": 32974,
"text": "Considering the above values following graph is obtained:"
},
{
"code": null,
"e": 33066,
"s": 33034,
"text": "Binomial distribution n=10, p=2"
},
{
"code": null,
"e": 33188,
"s": 33066,
"text": "The binompdf function on TI 83 or 84 calculators is used for finding the probability of exactly some number of successes."
},
{
"code": null,
"e": 33217,
"s": 33188,
"text": "P(X = c) = binompdf(n, p, c)"
},
{
"code": null,
"e": 33226,
"s": 33219,
"text": "where,"
},
{
"code": null,
"e": 33247,
"s": 33226,
"text": "n = number of trails"
},
{
"code": null,
"e": 33269,
"s": 33247,
"text": "p = number of success"
},
{
"code": null,
"e": 33321,
"s": 33269,
"text": "c = probability of exactly c success, for number c."
},
{
"code": null,
"e": 33437,
"s": 33321,
"text": "Example: A fair coin is tossed 100 times. What is the binompdf probability that heads will appear exactly 52 times?"
},
{
"code": null,
"e": 33474,
"s": 33437,
"text": "Solution: Using the Binomial formula"
},
{
"code": null,
"e": 33560,
"s": 33476,
"text": "= binompdf (number of trials, probability of occurrence, number of specific events)"
},
{
"code": null,
"e": 33581,
"s": 33560,
"text": "= binompdf (n, p, r)"
},
{
"code": null,
"e": 33766,
"s": 33585,
"text": "The binomcdf function on the TI-84 calculator. It can be used to solve problems where probability is less than or equal to a number of successes out of a certain number of trials. "
},
{
"code": null,
"e": 33891,
"s": 33766,
"text": "Example: To calculate the probability of less than or equal to 45 successes out of 100 trials, the following method is used;"
},
{
"code": null,
"e": 33922,
"s": 33893,
"text": "P(X = c) = binomcdf(n, p, c)"
},
{
"code": null,
"e": 33929,
"s": 33922,
"text": "where,"
},
{
"code": null,
"e": 33955,
"s": 33929,
"text": "n = the number of trials "
},
{
"code": null,
"e": 34011,
"s": 33955,
"text": "p = the probability of success for any particular trial"
},
{
"code": null,
"e": 34038,
"s": 34011,
"text": "c = number of successes. "
},
{
"code": null,
"e": 34147,
"s": 34038,
"text": "Example 4: A fair coin is tossed 100 times. What is the probability binomcdf there will be at most 52 heads?"
},
{
"code": null,
"e": 34158,
"s": 34147,
"text": "Solution: "
},
{
"code": null,
"e": 34240,
"s": 34158,
"text": "binomcdf (number of trials, probability of occurrence, number of specific events)"
},
{
"code": null,
"e": 34261,
"s": 34240,
"text": "= binomcdf (n, p, r)"
},
{
"code": null,
"e": 34457,
"s": 34261,
"text": " Example: In a burger shop 70% of people preferred to eat a non-veg burger while others prefer to eat something else. What is the probability of selling 2 non-veg burgers to the next 3 customers?"
},
{
"code": null,
"e": 34467,
"s": 34457,
"text": "Solution:"
},
{
"code": null,
"e": 34540,
"s": 34467,
"text": "The probabilities for “non-veg burger” all work out to be 0.147 because "
},
{
"code": null,
"e": 34564,
"s": 34540,
"text": "0.147 = 0.7 × 0.7 × 0.3"
},
{
"code": null,
"e": 34598,
"s": 34564,
"text": "Or, using exponents:= 0.72 × 0.31"
},
{
"code": null,
"e": 34659,
"s": 34598,
"text": "The 0.7 is the probability of each choice we want, call it p"
},
{
"code": null,
"e": 34720,
"s": 34659,
"text": "The 2 is the number of choices we want, call it k= pk × 0.31"
},
{
"code": null,
"e": 34785,
"s": 34720,
"text": "The 0.3 is the probability of the opposite choice, so it is: 1−p"
},
{
"code": null,
"e": 34818,
"s": 34785,
"text": "Using formula = pk(1 – p)(n – k)"
},
{
"code": null,
"e": 34868,
"s": 34818,
"text": "Where p is the probability of each choice we want"
},
{
"code": null,
"e": 34904,
"s": 34868,
"text": "k is the number of choices we want "
},
{
"code": null,
"e": 34937,
"s": 34904,
"text": "n is the total number of choices"
},
{
"code": null,
"e": 34972,
"s": 34937,
"text": "p = 0.7 (chance of non-veg burger)"
},
{
"code": null,
"e": 35003,
"s": 34972,
"text": "k = 2 (non-veg burger choices)"
},
{
"code": null,
"e": 35025,
"s": 35003,
"text": "n = 3 (total choices)"
},
{
"code": null,
"e": 35068,
"s": 35025,
"text": "So we get: pk(1-p)(n-k) = 0.72(1-0.7)(3-2)"
},
{
"code": null,
"e": 35083,
"s": 35068,
"text": "= 0.72(0.3)(1)"
},
{
"code": null,
"e": 35101,
"s": 35083,
"text": "= 0.7 × 0.7 × 0.3"
},
{
"code": null,
"e": 35109,
"s": 35101,
"text": "= 0.147"
},
{
"code": null,
"e": 35225,
"s": 35109,
"text": "Three other possibilities are : (non-veg, non-veg, other) or (non-veg, other, non-veg) or (other, non-veg, non-veg)"
},
{
"code": null,
"e": 35255,
"s": 35225,
"text": "n!k! / (n-k)! = 3!2!(3-2)! "
},
{
"code": null,
"e": 35292,
"s": 35255,
"text": " = 3×2×12×1 × 1 "
},
{
"code": null,
"e": 35319,
"s": 35292,
"text": " = 3 "
},
{
"code": null,
"e": 35407,
"s": 35319,
"text": "3 (Number of outcomes we want ) × 0.147 (Probability of each outcome ) = 0.441"
},
{
"code": null,
"e": 35497,
"s": 35407,
"text": "So, 70% choose non-veg burger, so 7 of the next 10 customers should choose non-veg burger"
},
{
"code": null,
"e": 35505,
"s": 35497,
"text": "p = 0.7"
},
{
"code": null,
"e": 35512,
"s": 35505,
"text": "n = 10"
},
{
"code": null,
"e": 35518,
"s": 35512,
"text": "k = 7"
},
{
"code": null,
"e": 35564,
"s": 35518,
"text": "And we get: pk(1-p)(n-k) = 0.77(1-0.7)(10-7)"
},
{
"code": null,
"e": 35579,
"s": 35564,
"text": "= 0.77(0.3)(3)"
},
{
"code": null,
"e": 35594,
"s": 35579,
"text": "= 0.0022235661"
},
{
"code": null,
"e": 35637,
"s": 35594,
"text": "And the total number of those outcomes is:"
},
{
"code": null,
"e": 35666,
"s": 35637,
"text": "n!k!/(n-k)! =10!7!/(10-7)! "
},
{
"code": null,
"e": 35712,
"s": 35666,
"text": "= 10×9×8×7×6×5×4×3×2×17×6×5×4×3×2×1 × 3×2×1 "
},
{
"code": null,
"e": 35728,
"s": 35712,
"text": "= 10×9×83×2×1 "
},
{
"code": null,
"e": 35733,
"s": 35728,
"text": "=120"
},
{
"code": null,
"e": 35825,
"s": 35733,
"text": "120 (Number of outcomes we want) × 0.0022235661(Probability of each outcome ) = 0.266827932"
},
{
"code": null,
"e": 35904,
"s": 35825,
"text": " So the probability of 7 out of 10 choosing a non-veg burger is only about 27%"
},
{
"code": null,
"e": 35923,
"s": 35906,
"text": "surinderdawra388"
},
{
"code": null,
"e": 35930,
"s": 35923,
"text": "Picked"
},
{
"code": null,
"e": 35939,
"s": 35930,
"text": "Class 12"
},
{
"code": null,
"e": 35955,
"s": 35939,
"text": "School Learning"
},
{
"code": null,
"e": 35974,
"s": 35955,
"text": "School Mathematics"
},
{
"code": null,
"e": 36072,
"s": 35974,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36101,
"s": 36072,
"text": "Sorting Algorithms in Python"
},
{
"code": null,
"e": 36121,
"s": 36101,
"text": "Cardinality in DBMS"
},
{
"code": null,
"e": 36148,
"s": 36121,
"text": "SQL USE Database Statement"
},
{
"code": null,
"e": 36210,
"s": 36148,
"text": "Querying Data from a Database using fetchone() and fetchall()"
},
{
"code": null,
"e": 36264,
"s": 36210,
"text": "Intrinsic Semiconductors and Extrinsic Semiconductors"
},
{
"code": null,
"e": 36291,
"s": 36264,
"text": "How to Align Text in HTML?"
},
{
"code": null,
"e": 36315,
"s": 36291,
"text": "Cloud Deployment Models"
},
{
"code": null,
"e": 36364,
"s": 36315,
"text": "Generations of Computers - Computer Fundamentals"
},
{
"code": null,
"e": 36383,
"s": 36364,
"text": "Types of Computers"
}
] |
7 Common File System Operations You Can Do With Python | by Frank Andrade | Towards Data Science
|
One of the coolest things that you can do in Python without installing any third-party library is to perform file system operations such as creating a folder, renaming a file, and working with directories. Although these tasks can be easily done manually, you can automate them with Python code to save some time.
In this article, we’ll see 7 file system operations you can do in Python with the os and Pathlib modules. Each operation includes practical examples so you can understand the difference between these 2 modules.
Knowing the current working directory is fundamental when dealing with paths in a Python script. There are two kinds of paths — relative and absolute paths. An absolute path refers to the same location in a file system relative to the root directory (/), whereas a relative path refers to a specific location in a file system relative to the current working directory.
The relative path gives flexibility to your script, so that’s why it’s sometimes preferred over absolute paths. We can use the current working directory to create a relative path.
For this and all the file system operations listed in this article, we’ll have to import os and Path.
import osIn [1]: os.getcwd()Out [1]: /Users/frank/PycharmProjects/DataScience
As you can see from the code above, I got the directory that contains all my scripts for my data science project. This is my working directory in Pycharm. We can obtain the same directory with the Pathlib library
from pathlib import PathIn [1]: Path.cwd()Out [1]: /Users/frank/PycharmProjects/DataScience
If we print either type(os.getcwd()) or the type(Path.cwd() we can see the main difference between the os and Pathlib modules. The first returns only a string, while the second returns a PosixPath object that can help us do extra operations.
Besides showing the current working directory, we can list all the files that are inside our directory.
In [1]: os.listdir()Out [1]: ['script1.py', 'script2.py', 'script3.py']
In my case, I only have 3 Python scripts in my “Data Science” folder. We can obtain the same results with Path().iterdir(), but we’ll obtain a generator object. To obtain a list directory content from this generator, we use list() as shown in the code below.
In [1]: list(Path().iterdir())Out [1]: [PosixPath('script1.py'), PosixPath('script2.py'), PosixPath('script3.py')]
We can even see the content within a specific folder. For example, my ‘Data Science’ folder has a folder named ‘Dataset.’ We can list the directory content inside the ‘Dataset’ folder with the following code.
# osos.listdir('Dataset')# pathliblist(Path('Dataset').iterdir())
Concatenating strings in Python is as easy as using the “+” sign between two words; however, when it comes to concatenating paths, things get a bit tricky. This happens because Mac OS uses forward slash “/”, while Windows uses backward slash “\” in the directory names, so you need a different approach if you want the Python code to be able to run cross-platform. Fortunately, the os and Pathlib modules can take care of that.
# osos.path.join(os.getcwd(), 'Dataset')# pathlibfrom pathlib import Path, PurePathPurePath.joinpath(Path.cwd(), 'Dataset')
If we print the code written above, we’ll get a path that contains the working directory plus “Dataset.” The Path will look like this /Users/frank/PycharmProjects/DataScience/Dataset. The OS library creates a string, while the Pathlib creates a PosixPath class. However, we haven’t created the “Dataset” folder. To create a directory check the next file system operation.
Although you can create a directory in some seconds, when it comes to task automation, writing some Python code will be the best solution. We can perform this task with both libraries with a slight difference. Let’s create a “Dataset” folder as an example.
# osos.mkdir('Dataset')# pathlibPath('Dataset').mkdir()
If the “Dataset” folder doesn’t exist, the folder will be created. However, Python will throw an error, if we try to create a directory that already exists. That is, the script will break if I already have a folder named Dataset. Fortunately, we can easily control this behavior with Pathlib.
Path('Dataset').mkdir(exist_ok=True)
By adding the exist_ok parameter, we can ignore errors, in case the directory already exists.
Similar to the creation of directories, renaming file names is a task we can automate with a Python script. With the OS library, we can rename files introducing the string name. For example, let’s rename the “Dataset” folder to “Data.”
os.rename('Dataset', 'Data')
We can also do this task with Pathlib. In this case, the target name can be either a string or another path object. Let’s rename the folder to “Dataset”
current_path = Path('Data')target_path = Path('Dataset')Path.rename(current_path, target_path)
You can even rename multiple files with a specific extension using a for loop. For example, I’m going to add the year 2021 in front of each .csv file in my working directory.
for i, file in os.listdir(): if file.endswith('.csv'): os.rename(file, f'2021_{file}')
If you want to take this one step further, you can use the time module to add the date the script is running to the file name and more!
You can check whether a file/directory exists or not with the OS and Pathlib modules. Let’s see if the folder Dataset exists in my working directory.
# osos.path.exists('Dataset')# pathlibcheck_path = Path('Dataset')check_path.exists()
If you print the code above, Python will return a True value when the folder exists or False when it doesn’t exist. Since I have a folder named “Dataset,” I got True.
Metadata is data that describes other data. For example, the date created, date modified, and file size. Let’s get the absolute path of a test.py script I have in my working directory.
# osos.path.abspath('test.py')# pathlibscript = Path('test.py')script.resolve()
I got the absolute path /Users/frank/PycharmProjects/DataScience/test.py after printing the code above.
With Pathlib we can easily get the stem, suffix of the file, file size, and birthtime.
In [1]: print(script.stem)In [2]: print(script.suffix)In [3]: print(script.stat().st_size)In [4]: print(script.stat().st_birthtime)Out [1]: testOut [2]: .pyOut [3]: 1060Out [4]: 1614190828.6
As you can see the birth time is in timestamp format. In case you want to get a datetime object, run the code below.
from datetime import datetimetimestamp = 1614190828.6dt_object = datetime.fromtimestamp(timestamp)print("dt_object =", dt_object)
That’s it! Now you know 7 file system operations you can do using Python, You can check more operations in the os and pathlib documentations.
Join my email list with 3k+ people to get my Python for Data Science Cheat Sheet I use in all my tutorials (Free PDF)
|
[
{
"code": null,
"e": 486,
"s": 172,
"text": "One of the coolest things that you can do in Python without installing any third-party library is to perform file system operations such as creating a folder, renaming a file, and working with directories. Although these tasks can be easily done manually, you can automate them with Python code to save some time."
},
{
"code": null,
"e": 697,
"s": 486,
"text": "In this article, we’ll see 7 file system operations you can do in Python with the os and Pathlib modules. Each operation includes practical examples so you can understand the difference between these 2 modules."
},
{
"code": null,
"e": 1066,
"s": 697,
"text": "Knowing the current working directory is fundamental when dealing with paths in a Python script. There are two kinds of paths — relative and absolute paths. An absolute path refers to the same location in a file system relative to the root directory (/), whereas a relative path refers to a specific location in a file system relative to the current working directory."
},
{
"code": null,
"e": 1246,
"s": 1066,
"text": "The relative path gives flexibility to your script, so that’s why it’s sometimes preferred over absolute paths. We can use the current working directory to create a relative path."
},
{
"code": null,
"e": 1348,
"s": 1246,
"text": "For this and all the file system operations listed in this article, we’ll have to import os and Path."
},
{
"code": null,
"e": 1426,
"s": 1348,
"text": "import osIn [1]: os.getcwd()Out [1]: /Users/frank/PycharmProjects/DataScience"
},
{
"code": null,
"e": 1639,
"s": 1426,
"text": "As you can see from the code above, I got the directory that contains all my scripts for my data science project. This is my working directory in Pycharm. We can obtain the same directory with the Pathlib library"
},
{
"code": null,
"e": 1731,
"s": 1639,
"text": "from pathlib import PathIn [1]: Path.cwd()Out [1]: /Users/frank/PycharmProjects/DataScience"
},
{
"code": null,
"e": 1973,
"s": 1731,
"text": "If we print either type(os.getcwd()) or the type(Path.cwd() we can see the main difference between the os and Pathlib modules. The first returns only a string, while the second returns a PosixPath object that can help us do extra operations."
},
{
"code": null,
"e": 2077,
"s": 1973,
"text": "Besides showing the current working directory, we can list all the files that are inside our directory."
},
{
"code": null,
"e": 2149,
"s": 2077,
"text": "In [1]: os.listdir()Out [1]: ['script1.py', 'script2.py', 'script3.py']"
},
{
"code": null,
"e": 2408,
"s": 2149,
"text": "In my case, I only have 3 Python scripts in my “Data Science” folder. We can obtain the same results with Path().iterdir(), but we’ll obtain a generator object. To obtain a list directory content from this generator, we use list() as shown in the code below."
},
{
"code": null,
"e": 2523,
"s": 2408,
"text": "In [1]: list(Path().iterdir())Out [1]: [PosixPath('script1.py'), PosixPath('script2.py'), PosixPath('script3.py')]"
},
{
"code": null,
"e": 2732,
"s": 2523,
"text": "We can even see the content within a specific folder. For example, my ‘Data Science’ folder has a folder named ‘Dataset.’ We can list the directory content inside the ‘Dataset’ folder with the following code."
},
{
"code": null,
"e": 2798,
"s": 2732,
"text": "# osos.listdir('Dataset')# pathliblist(Path('Dataset').iterdir())"
},
{
"code": null,
"e": 3226,
"s": 2798,
"text": "Concatenating strings in Python is as easy as using the “+” sign between two words; however, when it comes to concatenating paths, things get a bit tricky. This happens because Mac OS uses forward slash “/”, while Windows uses backward slash “\\” in the directory names, so you need a different approach if you want the Python code to be able to run cross-platform. Fortunately, the os and Pathlib modules can take care of that."
},
{
"code": null,
"e": 3350,
"s": 3226,
"text": "# osos.path.join(os.getcwd(), 'Dataset')# pathlibfrom pathlib import Path, PurePathPurePath.joinpath(Path.cwd(), 'Dataset')"
},
{
"code": null,
"e": 3722,
"s": 3350,
"text": "If we print the code written above, we’ll get a path that contains the working directory plus “Dataset.” The Path will look like this /Users/frank/PycharmProjects/DataScience/Dataset. The OS library creates a string, while the Pathlib creates a PosixPath class. However, we haven’t created the “Dataset” folder. To create a directory check the next file system operation."
},
{
"code": null,
"e": 3979,
"s": 3722,
"text": "Although you can create a directory in some seconds, when it comes to task automation, writing some Python code will be the best solution. We can perform this task with both libraries with a slight difference. Let’s create a “Dataset” folder as an example."
},
{
"code": null,
"e": 4035,
"s": 3979,
"text": "# osos.mkdir('Dataset')# pathlibPath('Dataset').mkdir()"
},
{
"code": null,
"e": 4328,
"s": 4035,
"text": "If the “Dataset” folder doesn’t exist, the folder will be created. However, Python will throw an error, if we try to create a directory that already exists. That is, the script will break if I already have a folder named Dataset. Fortunately, we can easily control this behavior with Pathlib."
},
{
"code": null,
"e": 4365,
"s": 4328,
"text": "Path('Dataset').mkdir(exist_ok=True)"
},
{
"code": null,
"e": 4459,
"s": 4365,
"text": "By adding the exist_ok parameter, we can ignore errors, in case the directory already exists."
},
{
"code": null,
"e": 4695,
"s": 4459,
"text": "Similar to the creation of directories, renaming file names is a task we can automate with a Python script. With the OS library, we can rename files introducing the string name. For example, let’s rename the “Dataset” folder to “Data.”"
},
{
"code": null,
"e": 4724,
"s": 4695,
"text": "os.rename('Dataset', 'Data')"
},
{
"code": null,
"e": 4877,
"s": 4724,
"text": "We can also do this task with Pathlib. In this case, the target name can be either a string or another path object. Let’s rename the folder to “Dataset”"
},
{
"code": null,
"e": 4972,
"s": 4877,
"text": "current_path = Path('Data')target_path = Path('Dataset')Path.rename(current_path, target_path)"
},
{
"code": null,
"e": 5147,
"s": 4972,
"text": "You can even rename multiple files with a specific extension using a for loop. For example, I’m going to add the year 2021 in front of each .csv file in my working directory."
},
{
"code": null,
"e": 5244,
"s": 5147,
"text": "for i, file in os.listdir(): if file.endswith('.csv'): os.rename(file, f'2021_{file}')"
},
{
"code": null,
"e": 5380,
"s": 5244,
"text": "If you want to take this one step further, you can use the time module to add the date the script is running to the file name and more!"
},
{
"code": null,
"e": 5530,
"s": 5380,
"text": "You can check whether a file/directory exists or not with the OS and Pathlib modules. Let’s see if the folder Dataset exists in my working directory."
},
{
"code": null,
"e": 5616,
"s": 5530,
"text": "# osos.path.exists('Dataset')# pathlibcheck_path = Path('Dataset')check_path.exists()"
},
{
"code": null,
"e": 5783,
"s": 5616,
"text": "If you print the code above, Python will return a True value when the folder exists or False when it doesn’t exist. Since I have a folder named “Dataset,” I got True."
},
{
"code": null,
"e": 5968,
"s": 5783,
"text": "Metadata is data that describes other data. For example, the date created, date modified, and file size. Let’s get the absolute path of a test.py script I have in my working directory."
},
{
"code": null,
"e": 6048,
"s": 5968,
"text": "# osos.path.abspath('test.py')# pathlibscript = Path('test.py')script.resolve()"
},
{
"code": null,
"e": 6152,
"s": 6048,
"text": "I got the absolute path /Users/frank/PycharmProjects/DataScience/test.py after printing the code above."
},
{
"code": null,
"e": 6239,
"s": 6152,
"text": "With Pathlib we can easily get the stem, suffix of the file, file size, and birthtime."
},
{
"code": null,
"e": 6430,
"s": 6239,
"text": "In [1]: print(script.stem)In [2]: print(script.suffix)In [3]: print(script.stat().st_size)In [4]: print(script.stat().st_birthtime)Out [1]: testOut [2]: .pyOut [3]: 1060Out [4]: 1614190828.6"
},
{
"code": null,
"e": 6547,
"s": 6430,
"text": "As you can see the birth time is in timestamp format. In case you want to get a datetime object, run the code below."
},
{
"code": null,
"e": 6677,
"s": 6547,
"text": "from datetime import datetimetimestamp = 1614190828.6dt_object = datetime.fromtimestamp(timestamp)print(\"dt_object =\", dt_object)"
},
{
"code": null,
"e": 6819,
"s": 6677,
"text": "That’s it! Now you know 7 file system operations you can do using Python, You can check more operations in the os and pathlib documentations."
}
] |
5 Must-Know SQL Functions for String Manipulation | by Soner Yıldırım | Towards Data Science
|
SQL is used for managing data in a relational database. However, it offers much more than querying a database. The SQL functions also allow for performing data analysis and manipulation operations efficiently.
Since a substantial amount of raw data comes in textual form, it is of great importance to have versatile ways to manipulate strings. Raw data is usually not in the most desired format. We manipulate them to create usable and informative features.
In this article, we will go over 5 SQL functions to work with strings. For the examples, I will be using a small part of the Melbourne housing dataset available on Kaggle.
I have created a table called melb. Let’s first take a look at the dataset.
The dataset contains some information about the houses that are for sale.
Note: There are several relational database management systems such as MySQL, SQL Server, PostgreSQL, and so on. Although they mostly adapt the same SQL syntax, there might be small differences. In this article, we will use PostgreSQL.
Concatenating a string is basically combining multiple strings into one. In our dataset, we can combine the address and region name columns to create a full address.
We can use the concat function to perform this task.
SELECT CONCAT(address, ', ' , regionname) AS full_address FROM melb LIMIT 5; full_address-----------------------------------------85 Turner St, Northern Metropolitan25 Bloomburg St, Northern Metropolitan5 Charles St, Northern Metropolitan40 Federation La, Northern Metropolitan55a Park St, Northern Metropolitan
We can also use the “||” operation for concatenating strings.
SELECT address || ', ' || regionname AS full_addressFROM melb LIMIT 5;
The limit keyword limits the number of rows to be displayed.
A string might contain multiple pieces of information. In such cases, we may need to extract a piece from a string and use it as a separate feature.
The address column contains the house numbers. Let’s use it to create a new column called house number.
SELECT SPLIT_PART(address, ' ', 1) AS house_number FROM melb LIMIT 5;house_number--------------852554055a
The split_part function takes 3 arguments. The first one is the column name. The second one is the character that defines the split point which is space in our case. The third argument indicates which part we need after the split. The house numbers are at the beginning of the address so we take the first part.
The replace function allows for replacing a part of string with a new set of characters. It comes in handy when we need to standardize some text.
As an example, we can replace the “st” characters in the address column with the word “street”.
SELECT address, REPLACE(address, 'St', 'Street') AS new_address FROM melb LIMIT 5; address | new_address-----------------+---------------------85 Turner St | 85 Turner Street25 Bloomburg St | 25 Bloomburg Street5 Charles St | 5 Charles Street40 Federation La | 40 Federation La55a Park St | 55a Park Street
The left and right functions can be used to take a part from a string. We define the part to be selected in terms of the number of characters. For instance, the left function with 5 will return the first 5 characters from the left (i.e. from the beginning).
SELECT LEFT(regionname, 5) AS region_5 FROM melb LIMIT 5;region_5----------NorthNorthNorthNorthNorth
The right function works similarly.
The like is actually an SQL operator, not a function. However, it is a highly useful tool when working with strings. We can use it to filter strings that are “like” another string or a sequence of characters.
For instance, we can filter the addresses that contain the string “Park”.
SELECT address FROM melb WHERE address LIKE '%Park%' LIMIT 5; address----------------55a Park St49 Park St159 Park St17 Parkhill Dr93 Parkmore Rd
The ‘%’ represents any character. Thus, we are filtering addresses that start and end with any character. It just has to contain “Park” somewhere.
The like operator is case-sensitive. We are likely to get different addresses with “park”. Let’s try.
SELECT address FROM melb WHERE address LIKE '%park%' LIMIT 5; address-----------------18 Spark St14 Riverpark Dr1 Riverpark Dr23 Oakpark Dr
Textual data is an essential part of data analysis. Thus, we need efficient methods and techniques to handle strings. What we have covered in this article help you manipulate or update strings. You can also extract a piece of information from a string using these functions.
Thank you for reading. Please let me know if you have any feedback.
|
[
{
"code": null,
"e": 382,
"s": 172,
"text": "SQL is used for managing data in a relational database. However, it offers much more than querying a database. The SQL functions also allow for performing data analysis and manipulation operations efficiently."
},
{
"code": null,
"e": 630,
"s": 382,
"text": "Since a substantial amount of raw data comes in textual form, it is of great importance to have versatile ways to manipulate strings. Raw data is usually not in the most desired format. We manipulate them to create usable and informative features."
},
{
"code": null,
"e": 802,
"s": 630,
"text": "In this article, we will go over 5 SQL functions to work with strings. For the examples, I will be using a small part of the Melbourne housing dataset available on Kaggle."
},
{
"code": null,
"e": 878,
"s": 802,
"text": "I have created a table called melb. Let’s first take a look at the dataset."
},
{
"code": null,
"e": 952,
"s": 878,
"text": "The dataset contains some information about the houses that are for sale."
},
{
"code": null,
"e": 1188,
"s": 952,
"text": "Note: There are several relational database management systems such as MySQL, SQL Server, PostgreSQL, and so on. Although they mostly adapt the same SQL syntax, there might be small differences. In this article, we will use PostgreSQL."
},
{
"code": null,
"e": 1354,
"s": 1188,
"text": "Concatenating a string is basically combining multiple strings into one. In our dataset, we can combine the address and region name columns to create a full address."
},
{
"code": null,
"e": 1407,
"s": 1354,
"text": "We can use the concat function to perform this task."
},
{
"code": null,
"e": 1732,
"s": 1407,
"text": "SELECT CONCAT(address, ', ' , regionname) AS full_address FROM melb LIMIT 5; full_address-----------------------------------------85 Turner St, Northern Metropolitan25 Bloomburg St, Northern Metropolitan5 Charles St, Northern Metropolitan40 Federation La, Northern Metropolitan55a Park St, Northern Metropolitan"
},
{
"code": null,
"e": 1794,
"s": 1732,
"text": "We can also use the “||” operation for concatenating strings."
},
{
"code": null,
"e": 1865,
"s": 1794,
"text": "SELECT address || ', ' || regionname AS full_addressFROM melb LIMIT 5;"
},
{
"code": null,
"e": 1926,
"s": 1865,
"text": "The limit keyword limits the number of rows to be displayed."
},
{
"code": null,
"e": 2075,
"s": 1926,
"text": "A string might contain multiple pieces of information. In such cases, we may need to extract a piece from a string and use it as a separate feature."
},
{
"code": null,
"e": 2179,
"s": 2075,
"text": "The address column contains the house numbers. Let’s use it to create a new column called house number."
},
{
"code": null,
"e": 2285,
"s": 2179,
"text": "SELECT SPLIT_PART(address, ' ', 1) AS house_number FROM melb LIMIT 5;house_number--------------852554055a"
},
{
"code": null,
"e": 2597,
"s": 2285,
"text": "The split_part function takes 3 arguments. The first one is the column name. The second one is the character that defines the split point which is space in our case. The third argument indicates which part we need after the split. The house numbers are at the beginning of the address so we take the first part."
},
{
"code": null,
"e": 2743,
"s": 2597,
"text": "The replace function allows for replacing a part of string with a new set of characters. It comes in handy when we need to standardize some text."
},
{
"code": null,
"e": 2839,
"s": 2743,
"text": "As an example, we can replace the “st” characters in the address column with the word “street”."
},
{
"code": null,
"e": 3172,
"s": 2839,
"text": "SELECT address, REPLACE(address, 'St', 'Street') AS new_address FROM melb LIMIT 5; address | new_address-----------------+---------------------85 Turner St | 85 Turner Street25 Bloomburg St | 25 Bloomburg Street5 Charles St | 5 Charles Street40 Federation La | 40 Federation La55a Park St | 55a Park Street"
},
{
"code": null,
"e": 3430,
"s": 3172,
"text": "The left and right functions can be used to take a part from a string. We define the part to be selected in terms of the number of characters. For instance, the left function with 5 will return the first 5 characters from the left (i.e. from the beginning)."
},
{
"code": null,
"e": 3531,
"s": 3430,
"text": "SELECT LEFT(regionname, 5) AS region_5 FROM melb LIMIT 5;region_5----------NorthNorthNorthNorthNorth"
},
{
"code": null,
"e": 3567,
"s": 3531,
"text": "The right function works similarly."
},
{
"code": null,
"e": 3776,
"s": 3567,
"text": "The like is actually an SQL operator, not a function. However, it is a highly useful tool when working with strings. We can use it to filter strings that are “like” another string or a sequence of characters."
},
{
"code": null,
"e": 3850,
"s": 3776,
"text": "For instance, we can filter the addresses that contain the string “Park”."
},
{
"code": null,
"e": 3998,
"s": 3850,
"text": "SELECT address FROM melb WHERE address LIKE '%Park%' LIMIT 5; address----------------55a Park St49 Park St159 Park St17 Parkhill Dr93 Parkmore Rd"
},
{
"code": null,
"e": 4145,
"s": 3998,
"text": "The ‘%’ represents any character. Thus, we are filtering addresses that start and end with any character. It just has to contain “Park” somewhere."
},
{
"code": null,
"e": 4247,
"s": 4145,
"text": "The like operator is case-sensitive. We are likely to get different addresses with “park”. Let’s try."
},
{
"code": null,
"e": 4390,
"s": 4247,
"text": "SELECT address FROM melb WHERE address LIKE '%park%' LIMIT 5; address-----------------18 Spark St14 Riverpark Dr1 Riverpark Dr23 Oakpark Dr"
},
{
"code": null,
"e": 4665,
"s": 4390,
"text": "Textual data is an essential part of data analysis. Thus, we need efficient methods and techniques to handle strings. What we have covered in this article help you manipulate or update strings. You can also extract a piece of information from a string using these functions."
}
] |
AI with Python â Supervised Learning: Classification
|
In this chapter, we will focus on implementing supervised learning − classification.
The classification technique or model attempts to get some conclusion from observed values. In classification problem, we have the categorized output such as “Black” or “white” or “Teaching” and “Non-Teaching”. While building the classification model, we need to have training dataset that contains data points and the corresponding labels. For example, if we want to check whether the image is of a car or not. For checking this, we will build a training dataset having the two classes related to “car” and “no car”. Then we need to train the model by using the training samples. The classification models are mainly used in face recognition, spam identification, etc.
For building a classifier in Python, we are going to use Python 3 and Scikit-learn which is a tool for machine learning. Follow these steps to build a classifier in Python −
This would be very first step for building a classifier in Python. In this step, we will install a Python package called Scikit-learn which is one of the best machine learning modules in Python. The following command will help us import the package −
Import Sklearn
In this step, we can begin working with the dataset for our machine learning model. Here, we are going to use the Breast Cancer Wisconsin Diagnostic Database. The dataset includes various information about breast cancer tumors, as well as classification labels of malignant or benign. The dataset has 569 instances, or data, on 569 tumors and includes information on 30 attributes, or features, such as the radius of the tumor, texture, smoothness, and area. With the help of the following command, we can import the Scikit-learn’s breast cancer dataset −
from sklearn.datasets import load_breast_cancer
Now, the following command will load the dataset.
data = load_breast_cancer()
Following is a list of important dictionary keys −
Classification label names(target_names)
The actual labels(target)
The attribute/feature names(feature_names)
The attribute (data)
Now, with the help of the following command, we can create new variables for each important set of information and assign the data. In other words, we can organize the data with the following commands −
label_names = data['target_names']
labels = data['target']
feature_names = data['feature_names']
features = data['data']
Now, to make it clearer we can print the class labels, the first data instance’s label, our feature names and the feature’s value with the help of the following commands −
print(label_names)
The above command will print the class names which are malignant and benign respectively. It is shown as the output below −
['malignant' 'benign']
Now, the command below will show that they are mapped to binary values 0 and 1. Here 0 represents malignant cancer and 1 represents benign cancer. You will receive the following output −
print(labels[0])
0
The two commands given below will produce the feature names and feature values.
print(feature_names[0])
mean radius
print(features[0])
[ 1.79900000e+01 1.03800000e+01 1.22800000e+02 1.00100000e+03
1.18400000e-01 2.77600000e-01 3.00100000e-01 1.47100000e-01
2.41900000e-01 7.87100000e-02 1.09500000e+00 9.05300000e-01
8.58900000e+00 1.53400000e+02 6.39900000e-03 4.90400000e-02
5.37300000e-02 1.58700000e-02 3.00300000e-02 6.19300000e-03
2.53800000e+01 1.73300000e+01 1.84600000e+02 2.01900000e+03
1.62200000e-01 6.65600000e-01 7.11900000e-01 2.65400000e-01
4.60100000e-01 1.18900000e-01]
From the above output, we can see that the first data instance is a malignant tumor the radius of which is 1.7990000e+01.
In this step, we will divide our data into two parts namely a training set and a test set. Splitting the data into these sets is very important because we have to test our model on the unseen data. To split the data into sets, sklearn has a function called the train_test_split() function. With the help of the following commands, we can split the data in these sets −
from sklearn.model_selection import train_test_split
The above command will import the train_test_split function from sklearn and the command below will split the data into training and test data. In the example given below, we are using 40 % of the data for testing and the remaining data would be used for training the model.
train, test, train_labels, test_labels = train_test_split(features,labels,test_size = 0.40, random_state = 42)
In this step, we will be building our model. We are going to use Naïve Bayes algorithm for building the model. Following commands can be used to build the model −
from sklearn.naive_bayes import GaussianNB
The above command will import the GaussianNB module. Now, the following command will help you initialize the model.
gnb = GaussianNB()
We will train the model by fitting it to the data by using gnb.fit().
model = gnb.fit(train, train_labels)
In this step, we are going to evaluate the model by making predictions on our test data. Then we will find out its accuracy also. For making predictions, we will use the predict() function. The following command will help you do this −
preds = gnb.predict(test)
print(preds)
[1 0 0 1 1 0 0 0 1 1 1 0 1 0 1 0 1 1 1 0 1 1 0 1 1 1 1 1 1
0 1 1 1 1 1 1 0 1 0 1 1 0 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 0
0 1 1 0 0 1 1 1 0 0 1 1 0 0 1 0 1 1 1 1 1 1 0 1 1 0 0 0 0
0 1 1 1 1 1 1 1 1 0 0 1 0 0 1 0 0 1 1 1 0 1 1 0 1 1 0 0 0
1 1 1 0 0 1 1 0 1 0 0 1 1 0 0 0 1 1 1 0 1 1 0 0 1 0 1 1 0
1 0 0 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 0
1 1 0 1 1 1 1 1 1 0 0 0 1 1 0 1 0 1 1 1 1 0 1 1 0 1 1 1 0
1 0 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 0 1 0 0 1 1 0 1]
The above series of 0s and 1s are the predicted values for the tumor classes – malignant and benign.
Now, by comparing the two arrays namely test_labels and preds, we can find out the accuracy of our model. We are going to use the accuracy_score() function to determine the accuracy. Consider the following command for this −
from sklearn.metrics import accuracy_score
print(accuracy_score(test_labels,preds))
0.951754385965
The result shows that the NaïveBayes classifier is 95.17% accurate.
In this way, with the help of the above steps we can build our classifier in Python.
In this section, we will learn how to build a classifier in Python.
Naïve Bayes is a classification technique used to build classifier using the Bayes theorem. The assumption is that the predictors are independent. In simple words, it assumes that the presence of a particular feature in a class is unrelated to the presence of any other feature. For building Naïve Bayes classifier we need to use the python library called scikit learn. There are three types of Naïve Bayes models named Gaussian, Multinomial and Bernoulli under scikit learn package.
To build a Naïve Bayes machine learning classifier model, we need the following &minus
We are going to use the dataset named Breast Cancer Wisconsin Diagnostic Database. The dataset includes various information about breast cancer tumors, as well as classification labels of malignant or benign. The dataset has 569 instances, or data, on 569 tumors and includes information on 30 attributes, or features, such as the radius of the tumor, texture, smoothness, and area. We can import this dataset from sklearn package.
For building Naïve Bayes classifier, we need a Naïve Bayes model. As told earlier, there are three types of Naïve Bayes models named Gaussian, Multinomial and Bernoulli under scikit learn package. Here, in the following example we are going to use the Gaussian Naïve Bayes model.
By using the above, we are going to build a Naïve Bayes machine learning model to use the tumor information to predict whether or not a tumor is malignant or benign.
To begin with, we need to install the sklearn module. It can be done with the help of the following command −
Import Sklearn
Now, we need to import the dataset named Breast Cancer Wisconsin Diagnostic Database.
from sklearn.datasets import load_breast_cancer
Now, the following command will load the dataset.
data = load_breast_cancer()
The data can be organized as follows −
label_names = data['target_names']
labels = data['target']
feature_names = data['feature_names']
features = data['data']
Now, to make it clearer we can print the class labels, the first data instance’s label, our feature names and the feature’s value with the help of following commands −
print(label_names)
The above command will print the class names which are malignant and benign respectively. It is shown as the output below −
['malignant' 'benign']
Now, the command given below will show that they are mapped to binary values 0 and 1. Here 0 represents malignant cancer and 1 represents benign cancer. It is shown as the output below −
print(labels[0])
0
The following two commands will produce the feature names and feature values.
print(feature_names[0])
mean radius
print(features[0])
[ 1.79900000e+01 1.03800000e+01 1.22800000e+02 1.00100000e+03
1.18400000e-01 2.77600000e-01 3.00100000e-01 1.47100000e-01
2.41900000e-01 7.87100000e-02 1.09500000e+00 9.05300000e-01
8.58900000e+00 1.53400000e+02 6.39900000e-03 4.90400000e-02
5.37300000e-02 1.58700000e-02 3.00300000e-02 6.19300000e-03
2.53800000e+01 1.73300000e+01 1.84600000e+02 2.01900000e+03
1.62200000e-01 6.65600000e-01 7.11900000e-01 2.65400000e-01
4.60100000e-01 1.18900000e-01]
From the above output, we can see that the first data instance is a malignant tumor the main radius of which is 1.7990000e+01.
For testing our model on unseen data, we need to split our data into training and testing data. It can be done with the help of the following code −
from sklearn.model_selection import train_test_split
The above command will import the train_test_split function from sklearn and the command below will split the data into training and test data. In the below example, we are using 40 % of the data for testing and the remining data would be used for training the model.
train, test, train_labels, test_labels =
train_test_split(features,labels,test_size = 0.40, random_state = 42)
Now, we are building the model with the following commands −
from sklearn.naive_bayes import GaussianNB
The above command will import the GaussianNB module. Now, with the command given below, we need to initialize the model.
gnb = GaussianNB()
We will train the model by fitting it to the data by using gnb.fit().
model = gnb.fit(train, train_labels)
Now, evaluate the model by making prediction on the test data and it can be done as follows −
preds = gnb.predict(test)
print(preds)
[1 0 0 1 1 0 0 0 1 1 1 0 1 0 1 0 1 1 1 0 1 1 0 1 1 1 1 1 1
0 1 1 1 1 1 1 0 1 0 1 1 0 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 0
0 1 1 0 0 1 1 1 0 0 1 1 0 0 1 0 1 1 1 1 1 1 0 1 1 0 0 0 0
0 1 1 1 1 1 1 1 1 0 0 1 0 0 1 0 0 1 1 1 0 1 1 0 1 1 0 0 0
1 1 1 0 0 1 1 0 1 0 0 1 1 0 0 0 1 1 1 0 1 1 0 0 1 0 1 1 0
1 0 0 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 0
1 1 0 1 1 1 1 1 1 0 0 0 1 1 0 1 0 1 1 1 1 0 1 1 0 1 1 1 0
1 0 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 0 1 0 0 1 1 0 1]
The above series of 0s and 1s are the predicted values for the tumor classes i.e. malignant
and benign.
Now, by comparing the two arrays namely test_labels and preds, we can find out the
accuracy of our model. We are going to use the accuracy_score() function to determine
the accuracy. Consider the following command −
from sklearn.metrics import accuracy_score
print(accuracy_score(test_labels,preds))
0.951754385965
The result shows that NaïveBayes classifier is 95.17% accurate.
That was machine learning classifier based on the Naïve Bayse Gaussian model.
Basically, Support vector machine (SVM) is a supervised machine learning algorithm that
can be used for both regression and classification. The main concept of SVM is to plot each
data item as a point in n-dimensional space with the value of each feature being the value
of a particular coordinate. Here n would be the features we would have. Following is a
simple graphical representation to understand the concept of SVM −
In the above diagram, we have two features. Hence, we first need to plot these two
variables in two dimensional space where each point has two co-ordinates, called support
vectors. The line splits the data into two different classified groups. This line would be the
classifier.
Here, we are going to build an SVM classifier by using scikit-learn and iris dataset. Scikitlearn
library has the sklearn.svm module and provides sklearn.svm.svc for classification.
The SVM classifier to predict the class of the iris plant based on 4 features are shown
below.
We will use the iris dataset which contains 3 classes of 50 instances each, where each class refers to a type of iris plant. Each instance has the four features namely sepal length, sepal width, petal length and petal width. The SVM classifier to predict the class of the iris plant based on 4 features is shown below.
It is a technique used by SVM. Basically these are the functions which take low-dimensional input space and transform it to a higher dimensional space. It converts non-separable problem to separable problem. The kernel function can be any one among linear, polynomial, rbf and sigmoid. In this example, we will use the linear kernel.
Let us now import the following packages −
import pandas as pd
import numpy as np
from sklearn import svm, datasets
import matplotlib.pyplot as plt
Now, load the input data −
iris = datasets.load_iris()
We are taking first two features −
X = iris.data[:, :2]
y = iris.target
We will plot the support vector machine boundaries with original data. We are creating a mesh to plot.
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
h = (x_max / x_min)/100
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
X_plot = np.c_[xx.ravel(), yy.ravel()]
We need to give the value of regularization parameter.
C = 1.0
We need to create the SVM classifier object.
Svc_classifier = svm_classifier.SVC(kernel='linear',
C=C, decision_function_shape = 'ovr').fit(X, y)
Z = svc_classifier.predict(X_plot)
Z = Z.reshape(xx.shape)
plt.figure(figsize = (15, 5))
plt.subplot(121)
plt.contourf(xx, yy, Z, cmap = plt.cm.tab10, alpha = 0.3)
plt.scatter(X[:, 0], X[:, 1], c = y, cmap = plt.cm.Set1)
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')
plt.xlim(xx.min(), xx.max())
plt.title('SVC with linear kernel')
Basically, logistic regression model is one of the members of supervised classification algorithm family. Logistic regression measures the relationship between dependent variables and independent variables by estimating the probabilities using a logistic function.
Here, if we talk about dependent and independent variables then dependent variable is the target class variable we are going to predict and on the other side the independent variables are the features we are going to use to predict the target class.
In logistic regression, estimating the probabilities means to predict the likelihood occurrence of the event. For example, the shop owner would like to predict the customer who entered into the shop will buy the play station (for example) or not. There would be many features of customer − gender, age, etc. which would be observed by the shop keeper to predict the likelihood occurrence, i.e., buying a play station or not. The logistic function is the sigmoid curve that is used to build the function with various parameters.
Before building the classifier using logistic regression, we need to install the Tkinter package on our system. It can be installed from https://docs.python.org/2/library/tkinter.html.
Now, with the help of the code given below, we can create a classifier using logistic regression −
First, we will import some packages −
import numpy as np
from sklearn import linear_model
import matplotlib.pyplot as plt
Now, we need to define the sample data which can be done as follows −
X = np.array([[2, 4.8], [2.9, 4.7], [2.5, 5], [3.2, 5.5], [6, 5], [7.6, 4],
[3.2, 0.9], [2.9, 1.9],[2.4, 3.5], [0.5, 3.4], [1, 4], [0.9, 5.9]])
y = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3])
Next, we need to create the logistic regression classifier, which can be done as follows −
Classifier_LR = linear_model.LogisticRegression(solver = 'liblinear', C = 75)
Last but not the least, we need to train this classifier −
Classifier_LR.fit(X, y)
Now, how we can visualize the output? It can be done by creating a function named Logistic_visualize() −
Def Logistic_visualize(Classifier_LR, X, y):
min_x, max_x = X[:, 0].min() - 1.0, X[:, 0].max() + 1.0
min_y, max_y = X[:, 1].min() - 1.0, X[:, 1].max() + 1.0
In the above line, we defined the minimum and maximum values X and Y to be used in mesh grid. In addition, we will define the step size for plotting the mesh grid.
mesh_step_size = 0.02
Let us define the mesh grid of X and Y values as follows −
x_vals, y_vals = np.meshgrid(np.arange(min_x, max_x, mesh_step_size),
np.arange(min_y, max_y, mesh_step_size))
With the help of following code, we can run the classifier on the mesh grid −
output = classifier.predict(np.c_[x_vals.ravel(), y_vals.ravel()])
output = output.reshape(x_vals.shape)
plt.figure()
plt.pcolormesh(x_vals, y_vals, output, cmap = plt.cm.gray)
plt.scatter(X[:, 0], X[:, 1], c = y, s = 75, edgecolors = 'black',
linewidth=1, cmap = plt.cm.Paired)
The following line of code will specify the boundaries of the plot
plt.xlim(x_vals.min(), x_vals.max())
plt.ylim(y_vals.min(), y_vals.max())
plt.xticks((np.arange(int(X[:, 0].min() - 1), int(X[:, 0].max() + 1), 1.0)))
plt.yticks((np.arange(int(X[:, 1].min() - 1), int(X[:, 1].max() + 1), 1.0)))
plt.show()
Now, after running the code we will get the following output, logistic regression classifier −
A decision tree is basically a binary tree flowchart where each node splits a group of observations according to some feature variable.
Here, we are building a Decision Tree classifier for predicting male or female. We will take a very small data set having 19 samples. These samples would consist of two features – ‘height’ and ‘length of hair’.
For building the following classifier, we need to install pydotplus and graphviz. Basically, graphviz is a tool for drawing graphics using dot files and pydotplus is a module to Graphviz’s Dot language. It can be installed with the package manager or pip.
Now, we can build the decision tree classifier with the help of the following Python code −
To begin with, let us import some important libraries as follows −
import pydotplus
from sklearn import tree
from sklearn.datasets import load_iris
from sklearn.metrics import classification_report
from sklearn import cross_validation
import collections
Now, we need to provide the dataset as follows −
X = [[165,19],[175,32],[136,35],[174,65],[141,28],[176,15],[131,32],
[166,6],[128,32],[179,10],[136,34],[186,2],[126,25],[176,28],[112,38],
[169,9],[171,36],[116,25],[196,25]]
Y = ['Man','Woman','Woman','Man','Woman','Man','Woman','Man','Woman',
'Man','Woman','Man','Woman','Woman','Woman','Man','Woman','Woman','Man']
data_feature_names = ['height','length of hair']
X_train, X_test, Y_train, Y_test = cross_validation.train_test_split
(X, Y, test_size=0.40, random_state=5)
After providing the dataset, we need to fit the model which can be done as follows −
clf = tree.DecisionTreeClassifier()
clf = clf.fit(X,Y)
Prediction can be made with the help of the following Python code −
prediction = clf.predict([[133,37]])
print(prediction)
We can visualize the decision tree with the help of the following Python code −
dot_data = tree.export_graphviz(clf,feature_names = data_feature_names,
out_file = None,filled = True,rounded = True)
graph = pydotplus.graph_from_dot_data(dot_data)
colors = ('orange', 'yellow')
edges = collections.defaultdict(list)
for edge in graph.get_edge_list():
edges[edge.get_source()].append(int(edge.get_destination()))
for edge in edges: edges[edge].sort()
for i in range(2):dest = graph.get_node(str(edges[edge][i]))[0]
dest.set_fillcolor(colors[i])
graph.write_png('Decisiontree16.png')
It will give the prediction for the above code as [‘Woman’] and create the following decision tree −
We can change the values of features in prediction to test it.
As we know that ensemble methods are the methods which combine machine learning models into a more powerful machine learning model. Random Forest, a collection of decision trees, is one of them. It is better than single decision tree because while retaining the predictive powers it can reduce over-fitting by averaging the results. Here, we are going to implement the random forest model on scikit learn cancer dataset.
Import the necessary packages −
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_breast_cancer
cancer = load_breast_cancer()
import matplotlib.pyplot as plt
import numpy as np
Now, we need to provide the dataset which can be done as follows &minus
cancer = load_breast_cancer()
X_train, X_test, y_train,
y_test = train_test_split(cancer.data, cancer.target, random_state = 0)
After providing the dataset, we need to fit the model which can be done as follows −
forest = RandomForestClassifier(n_estimators = 50, random_state = 0)
forest.fit(X_train,y_train)
Now, get the accuracy on training as well as testing subset: if we will increase the number of estimators then, the accuracy of testing subset would also be increased.
print('Accuracy on the training subset:(:.3f)',format(forest.score(X_train,y_train)))
print('Accuracy on the training subset:(:.3f)',format(forest.score(X_test,y_test)))
Accuracy on the training subset:(:.3f) 1.0
Accuracy on the training subset:(:.3f) 0.965034965034965
Now, like the decision tree, random forest has the feature_importance module which will provide a better view of feature weight than decision tree. It can be plot and visualize as follows −
n_features = cancer.data.shape[1]
plt.barh(range(n_features),forest.feature_importances_, align='center')
plt.yticks(np.arange(n_features),cancer.feature_names)
plt.xlabel('Feature Importance')
plt.ylabel('Feature')
plt.show()
After implementing a machine learning algorithm, we need to find out how effective the model is. The criteria for measuring the effectiveness may be based upon datasets and metric. For evaluating different machine learning algorithms, we can use different performance metrics. For example, suppose if a classifier is used to distinguish between images of different objects, we can use the classification performance metrics such as average accuracy, AUC, etc. In one or other sense, the metric we choose to evaluate our machine learning model is very important because the choice of metrics influences how the performance of a machine learning algorithm is measured and compared. Following are some of the metrics −
Basically it is used for classification problem where the output can be of two or more types of classes. It is the easiest way to measure the performance of a classifier. A confusion matrix is basically a table with two dimensions namely “Actual” and “Predicted”. Both the dimensions have “True Positives (TP)”, “True Negatives (TN)”, “False Positives (FP)”, “False Negatives (FN)”.
In the confusion matrix above, 1 is for positive class and 0 is for negative class.
Following are the terms associated with Confusion matrix −
True Positives − TPs are the cases when the actual class of data point was 1 and the predicted is also 1.
True Positives − TPs are the cases when the actual class of data point was 1 and the predicted is also 1.
True Negatives − TNs are the cases when the actual class of the data point was 0 and the predicted is also 0.
True Negatives − TNs are the cases when the actual class of the data point was 0 and the predicted is also 0.
False Positives − FPs are the cases when the actual class of data point was 0 and the predicted is also 1.
False Positives − FPs are the cases when the actual class of data point was 0 and the predicted is also 1.
False Negatives − FNs are the cases when the actual class of the data point was 1 and the predicted is also 0.
False Negatives − FNs are the cases when the actual class of the data point was 1 and the predicted is also 0.
The confusion matrix itself is not a performance measure as such but almost all the performance matrices are based on the confusion matrix. One of them is accuracy. In classification problems, it may be defined as the number of correct predictions made by the model over all kinds of predictions made. The formula for calculating the accuracy is as follows −
$$Accuracy = \frac{TP+TN}{TP+FP+FN+TN}$$
It is mostly used in document retrievals. It may be defined as how many of the returned documents are correct. Following is the formula for calculating the precision −
$$Precision = \frac{TP}{TP+FP}$$
It may be defined as how many of the positives do the model return. Following is the formula for calculating the recall/sensitivity of the model −
$$Recall = \frac{TP}{TP+FN}$$
It may be defined as how many of the negatives do the model return. It is exactly opposite to recall. Following is the formula for calculating the specificity of the model −
$$Specificity = \frac{TN}{TN+FP}$$
Class imbalance is the scenario where the number of observations belonging to one class is significantly lower than those belonging to the other classes. For example, this problem is prominent in the scenario where we need to identify the rare diseases, fraudulent transactions in bank etc.
Let us consider an example of fraud detection data set to understand the concept of imbalanced class −
Total observations = 5000
Fraudulent Observations = 50
Non-Fraudulent Observations = 4950
Event Rate = 1%
Balancing the classes’ acts as a solution to imbalanced classes. The main objective of balancing the classes is to either increase the frequency of the minority class or decrease the frequency of the majority class. Following are the approaches to solve the issue of imbalances classes −
Re-sampling is a series of methods used to reconstruct the sample data sets − both training sets and testing sets. Re-sampling is done to improve the accuracy of model. Following are some re-sampling techniques −
Random Under-Sampling − This technique aims to balance class distribution by randomly eliminating majority class examples. This is done until the majority and minority class instances are balanced out.
Random Under-Sampling − This technique aims to balance class distribution by randomly eliminating majority class examples. This is done until the majority and minority class instances are balanced out.
Total observations = 5000
Fraudulent Observations = 50
Non-Fraudulent Observations = 4950
Event Rate = 1%
In this case, we are taking 10% samples without replacement from non-fraud instances and then combine them with the fraud instances −
Non-fraudulent observations after random under sampling = 10% of 4950 = 495
Total observations after combining them with fraudulent observations = 50+495 = 545
Hence now, the event rate for new dataset after under sampling = 9%
The main advantage of this technique is that it can reduce run time and improve storage. But on the other side, it can discard useful information while reducing the number of training data samples.
Random Over-Sampling − This technique aims to balance class distribution by increasing the number of instances in the minority class by replicating them.
Random Over-Sampling − This technique aims to balance class distribution by increasing the number of instances in the minority class by replicating them.
Total observations = 5000
Fraudulent Observations = 50
Non-Fraudulent Observations = 4950
Event Rate = 1%
In case we are replicating 50 fraudulent observations 30 times then fraudulent observations after replicating the minority class observations would be 1500. And then total observations in the new data after oversampling would be 4950+1500 = 6450. Hence the event rate for the new data set would be 1500/6450 = 23%.
The main advantage of this method is that there would be no loss of useful information. But on the other hand, it has the increased chances of over-fitting because it replicates the minority class events.
This methodology basically is used to modify existing classification algorithms to make them appropriate for imbalanced data sets. In this approach we construct several two stage classifier from the original data and then aggregate their predictions. Random forest classifier is an example of ensemble based classifier.
78 Lectures
7 hours
Arnab Chakraborty
87 Lectures
9.5 hours
DigiFisk (Programming Is Fun)
10 Lectures
1 hours
Nikoloz Sanakoevi
15 Lectures
54 mins
Mukund Kumar Mishra
11 Lectures
1 hours
Gilad James, PhD
20 Lectures
2 hours
Gilad James, PhD
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2290,
"s": 2205,
"text": "In this chapter, we will focus on implementing supervised learning − classification."
},
{
"code": null,
"e": 2960,
"s": 2290,
"text": "The classification technique or model attempts to get some conclusion from observed values. In classification problem, we have the categorized output such as “Black” or “white” or “Teaching” and “Non-Teaching”. While building the classification model, we need to have training dataset that contains data points and the corresponding labels. For example, if we want to check whether the image is of a car or not. For checking this, we will build a training dataset having the two classes related to “car” and “no car”. Then we need to train the model by using the training samples. The classification models are mainly used in face recognition, spam identification, etc."
},
{
"code": null,
"e": 3134,
"s": 2960,
"text": "For building a classifier in Python, we are going to use Python 3 and Scikit-learn which is a tool for machine learning. Follow these steps to build a classifier in Python −"
},
{
"code": null,
"e": 3385,
"s": 3134,
"text": "This would be very first step for building a classifier in Python. In this step, we will install a Python package called Scikit-learn which is one of the best machine learning modules in Python. The following command will help us import the package −"
},
{
"code": null,
"e": 3401,
"s": 3385,
"text": "Import Sklearn\n"
},
{
"code": null,
"e": 3957,
"s": 3401,
"text": "In this step, we can begin working with the dataset for our machine learning model. Here, we are going to use the Breast Cancer Wisconsin Diagnostic Database. The dataset includes various information about breast cancer tumors, as well as classification labels of malignant or benign. The dataset has 569 instances, or data, on 569 tumors and includes information on 30 attributes, or features, such as the radius of the tumor, texture, smoothness, and area. With the help of the following command, we can import the Scikit-learn’s breast cancer dataset −"
},
{
"code": null,
"e": 4006,
"s": 3957,
"text": "from sklearn.datasets import load_breast_cancer\n"
},
{
"code": null,
"e": 4056,
"s": 4006,
"text": "Now, the following command will load the dataset."
},
{
"code": null,
"e": 4085,
"s": 4056,
"text": "data = load_breast_cancer()\n"
},
{
"code": null,
"e": 4136,
"s": 4085,
"text": "Following is a list of important dictionary keys −"
},
{
"code": null,
"e": 4177,
"s": 4136,
"text": "Classification label names(target_names)"
},
{
"code": null,
"e": 4203,
"s": 4177,
"text": "The actual labels(target)"
},
{
"code": null,
"e": 4246,
"s": 4203,
"text": "The attribute/feature names(feature_names)"
},
{
"code": null,
"e": 4267,
"s": 4246,
"text": "The attribute (data)"
},
{
"code": null,
"e": 4470,
"s": 4267,
"text": "Now, with the help of the following command, we can create new variables for each important set of information and assign the data. In other words, we can organize the data with the following commands −"
},
{
"code": null,
"e": 4592,
"s": 4470,
"text": "label_names = data['target_names']\nlabels = data['target']\nfeature_names = data['feature_names']\nfeatures = data['data']\n"
},
{
"code": null,
"e": 4764,
"s": 4592,
"text": "Now, to make it clearer we can print the class labels, the first data instance’s label, our feature names and the feature’s value with the help of the following commands −"
},
{
"code": null,
"e": 4784,
"s": 4764,
"text": "print(label_names)\n"
},
{
"code": null,
"e": 4908,
"s": 4784,
"text": "The above command will print the class names which are malignant and benign respectively. It is shown as the output below −"
},
{
"code": null,
"e": 4932,
"s": 4908,
"text": "['malignant' 'benign']\n"
},
{
"code": null,
"e": 5119,
"s": 4932,
"text": "Now, the command below will show that they are mapped to binary values 0 and 1. Here 0 represents malignant cancer and 1 represents benign cancer. You will receive the following output −"
},
{
"code": null,
"e": 5139,
"s": 5119,
"text": "print(labels[0])\n0\n"
},
{
"code": null,
"e": 5219,
"s": 5139,
"text": "The two commands given below will produce the feature names and feature values."
},
{
"code": null,
"e": 5742,
"s": 5219,
"text": "print(feature_names[0])\nmean radius\nprint(features[0])\n[ 1.79900000e+01 1.03800000e+01 1.22800000e+02 1.00100000e+03\n 1.18400000e-01 2.77600000e-01 3.00100000e-01 1.47100000e-01\n 2.41900000e-01 7.87100000e-02 1.09500000e+00 9.05300000e-01\n 8.58900000e+00 1.53400000e+02 6.39900000e-03 4.90400000e-02\n 5.37300000e-02 1.58700000e-02 3.00300000e-02 6.19300000e-03\n 2.53800000e+01 1.73300000e+01 1.84600000e+02 2.01900000e+03\n 1.62200000e-01 6.65600000e-01 7.11900000e-01 2.65400000e-01\n 4.60100000e-01 1.18900000e-01]\n"
},
{
"code": null,
"e": 5864,
"s": 5742,
"text": "From the above output, we can see that the first data instance is a malignant tumor the radius of which is 1.7990000e+01."
},
{
"code": null,
"e": 6233,
"s": 5864,
"text": "In this step, we will divide our data into two parts namely a training set and a test set. Splitting the data into these sets is very important because we have to test our model on the unseen data. To split the data into sets, sklearn has a function called the train_test_split() function. With the help of the following commands, we can split the data in these sets −"
},
{
"code": null,
"e": 6287,
"s": 6233,
"text": "from sklearn.model_selection import train_test_split\n"
},
{
"code": null,
"e": 6562,
"s": 6287,
"text": "The above command will import the train_test_split function from sklearn and the command below will split the data into training and test data. In the example given below, we are using 40 % of the data for testing and the remaining data would be used for training the model."
},
{
"code": null,
"e": 6673,
"s": 6562,
"text": "train, test, train_labels, test_labels = train_test_split(features,labels,test_size = 0.40, random_state = 42)"
},
{
"code": null,
"e": 6837,
"s": 6673,
"text": "In this step, we will be building our model. We are going to use Naïve Bayes algorithm for building the model. Following commands can be used to build the model −"
},
{
"code": null,
"e": 6881,
"s": 6837,
"text": "from sklearn.naive_bayes import GaussianNB\n"
},
{
"code": null,
"e": 6997,
"s": 6881,
"text": "The above command will import the GaussianNB module. Now, the following command will help you initialize the model."
},
{
"code": null,
"e": 7017,
"s": 6997,
"text": "gnb = GaussianNB()\n"
},
{
"code": null,
"e": 7087,
"s": 7017,
"text": "We will train the model by fitting it to the data by using gnb.fit()."
},
{
"code": null,
"e": 7124,
"s": 7087,
"text": "model = gnb.fit(train, train_labels)"
},
{
"code": null,
"e": 7360,
"s": 7124,
"text": "In this step, we are going to evaluate the model by making predictions on our test data. Then we will find out its accuracy also. For making predictions, we will use the predict() function. The following command will help you do this −"
},
{
"code": null,
"e": 7872,
"s": 7360,
"text": "preds = gnb.predict(test)\nprint(preds)\n\n[1 0 0 1 1 0 0 0 1 1 1 0 1 0 1 0 1 1 1 0 1 1 0 1 1 1 1 1 1\n 0 1 1 1 1 1 1 0 1 0 1 1 0 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 0 \n 0 1 1 0 0 1 1 1 0 0 1 1 0 0 1 0 1 1 1 1 1 1 0 1 1 0 0 0 0 \n 0 1 1 1 1 1 1 1 1 0 0 1 0 0 1 0 0 1 1 1 0 1 1 0 1 1 0 0 0 \n 1 1 1 0 0 1 1 0 1 0 0 1 1 0 0 0 1 1 1 0 1 1 0 0 1 0 1 1 0 \n 1 0 0 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 0 \n 1 1 0 1 1 1 1 1 1 0 0 0 1 1 0 1 0 1 1 1 1 0 1 1 0 1 1 1 0 \n 1 0 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 0 1 0 0 1 1 0 1]\n"
},
{
"code": null,
"e": 7973,
"s": 7872,
"text": "The above series of 0s and 1s are the predicted values for the tumor classes – malignant and benign."
},
{
"code": null,
"e": 8198,
"s": 7973,
"text": "Now, by comparing the two arrays namely test_labels and preds, we can find out the accuracy of our model. We are going to use the accuracy_score() function to determine the accuracy. Consider the following command for this −"
},
{
"code": null,
"e": 8298,
"s": 8198,
"text": "from sklearn.metrics import accuracy_score\nprint(accuracy_score(test_labels,preds))\n0.951754385965\n"
},
{
"code": null,
"e": 8367,
"s": 8298,
"text": "The result shows that the NaïveBayes classifier is 95.17% accurate."
},
{
"code": null,
"e": 8452,
"s": 8367,
"text": "In this way, with the help of the above steps we can build our classifier in Python."
},
{
"code": null,
"e": 8520,
"s": 8452,
"text": "In this section, we will learn how to build a classifier in Python."
},
{
"code": null,
"e": 9007,
"s": 8520,
"text": "Naïve Bayes is a classification technique used to build classifier using the Bayes theorem. The assumption is that the predictors are independent. In simple words, it assumes that the presence of a particular feature in a class is unrelated to the presence of any other feature. For building Naïve Bayes classifier we need to use the python library called scikit learn. There are three types of Naïve Bayes models named Gaussian, Multinomial and Bernoulli under scikit learn package."
},
{
"code": null,
"e": 9095,
"s": 9007,
"text": "To build a Naïve Bayes machine learning classifier model, we need the following &minus"
},
{
"code": null,
"e": 9527,
"s": 9095,
"text": "We are going to use the dataset named Breast Cancer Wisconsin Diagnostic Database. The dataset includes various information about breast cancer tumors, as well as classification labels of malignant or benign. The dataset has 569 instances, or data, on 569 tumors and includes information on 30 attributes, or features, such as the radius of the tumor, texture, smoothness, and area. We can import this dataset from sklearn package."
},
{
"code": null,
"e": 9811,
"s": 9527,
"text": "For building Naïve Bayes classifier, we need a Naïve Bayes model. As told earlier, there are three types of Naïve Bayes models named Gaussian, Multinomial and Bernoulli under scikit learn package. Here, in the following example we are going to use the Gaussian Naïve Bayes model."
},
{
"code": null,
"e": 9978,
"s": 9811,
"text": "By using the above, we are going to build a Naïve Bayes machine learning model to use the tumor information to predict whether or not a tumor is malignant or benign."
},
{
"code": null,
"e": 10088,
"s": 9978,
"text": "To begin with, we need to install the sklearn module. It can be done with the help of the following command −"
},
{
"code": null,
"e": 10104,
"s": 10088,
"text": "Import Sklearn\n"
},
{
"code": null,
"e": 10190,
"s": 10104,
"text": "Now, we need to import the dataset named Breast Cancer Wisconsin Diagnostic Database."
},
{
"code": null,
"e": 10238,
"s": 10190,
"text": "from sklearn.datasets import load_breast_cancer"
},
{
"code": null,
"e": 10288,
"s": 10238,
"text": "Now, the following command will load the dataset."
},
{
"code": null,
"e": 10317,
"s": 10288,
"text": "data = load_breast_cancer()\n"
},
{
"code": null,
"e": 10356,
"s": 10317,
"text": "The data can be organized as follows −"
},
{
"code": null,
"e": 10477,
"s": 10356,
"text": "label_names = data['target_names']\nlabels = data['target']\nfeature_names = data['feature_names']\nfeatures = data['data']"
},
{
"code": null,
"e": 10645,
"s": 10477,
"text": "Now, to make it clearer we can print the class labels, the first data instance’s label, our feature names and the feature’s value with the help of following commands −"
},
{
"code": null,
"e": 10665,
"s": 10645,
"text": "print(label_names)\n"
},
{
"code": null,
"e": 10789,
"s": 10665,
"text": "The above command will print the class names which are malignant and benign respectively. It is shown as the output below −"
},
{
"code": null,
"e": 10813,
"s": 10789,
"text": "['malignant' 'benign']\n"
},
{
"code": null,
"e": 11000,
"s": 10813,
"text": "Now, the command given below will show that they are mapped to binary values 0 and 1. Here 0 represents malignant cancer and 1 represents benign cancer. It is shown as the output below −"
},
{
"code": null,
"e": 11020,
"s": 11000,
"text": "print(labels[0])\n0\n"
},
{
"code": null,
"e": 11098,
"s": 11020,
"text": "The following two commands will produce the feature names and feature values."
},
{
"code": null,
"e": 11622,
"s": 11098,
"text": "print(feature_names[0])\nmean radius\nprint(features[0])\n\n[ 1.79900000e+01 1.03800000e+01 1.22800000e+02 1.00100000e+03\n 1.18400000e-01 2.77600000e-01 3.00100000e-01 1.47100000e-01\n 2.41900000e-01 7.87100000e-02 1.09500000e+00 9.05300000e-01\n 8.58900000e+00 1.53400000e+02 6.39900000e-03 4.90400000e-02\n 5.37300000e-02 1.58700000e-02 3.00300000e-02 6.19300000e-03\n 2.53800000e+01 1.73300000e+01 1.84600000e+02 2.01900000e+03\n 1.62200000e-01 6.65600000e-01 7.11900000e-01 2.65400000e-01\n 4.60100000e-01 1.18900000e-01]\n"
},
{
"code": null,
"e": 11749,
"s": 11622,
"text": "From the above output, we can see that the first data instance is a malignant tumor the main radius of which is 1.7990000e+01."
},
{
"code": null,
"e": 11898,
"s": 11749,
"text": "For testing our model on unseen data, we need to split our data into training and testing data. It can be done with the help of the following code −"
},
{
"code": null,
"e": 11952,
"s": 11898,
"text": "from sklearn.model_selection import train_test_split\n"
},
{
"code": null,
"e": 12220,
"s": 11952,
"text": "The above command will import the train_test_split function from sklearn and the command below will split the data into training and test data. In the below example, we are using 40 % of the data for testing and the remining data would be used for training the model."
},
{
"code": null,
"e": 12332,
"s": 12220,
"text": "train, test, train_labels, test_labels = \ntrain_test_split(features,labels,test_size = 0.40, random_state = 42)"
},
{
"code": null,
"e": 12393,
"s": 12332,
"text": "Now, we are building the model with the following commands −"
},
{
"code": null,
"e": 12437,
"s": 12393,
"text": "from sklearn.naive_bayes import GaussianNB\n"
},
{
"code": null,
"e": 12558,
"s": 12437,
"text": "The above command will import the GaussianNB module. Now, with the command given below, we need to initialize the model."
},
{
"code": null,
"e": 12577,
"s": 12558,
"text": "gnb = GaussianNB()"
},
{
"code": null,
"e": 12647,
"s": 12577,
"text": "We will train the model by fitting it to the data by using gnb.fit()."
},
{
"code": null,
"e": 12684,
"s": 12647,
"text": "model = gnb.fit(train, train_labels)"
},
{
"code": null,
"e": 12778,
"s": 12684,
"text": "Now, evaluate the model by making prediction on the test data and it can be done as follows −"
},
{
"code": null,
"e": 13289,
"s": 12778,
"text": "preds = gnb.predict(test)\nprint(preds)\n\n[1 0 0 1 1 0 0 0 1 1 1 0 1 0 1 0 1 1 1 0 1 1 0 1 1 1 1 1 1\n 0 1 1 1 1 1 1 0 1 0 1 1 0 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 0 \n 0 1 1 0 0 1 1 1 0 0 1 1 0 0 1 0 1 1 1 1 1 1 0 1 1 0 0 0 0 \n 0 1 1 1 1 1 1 1 1 0 0 1 0 0 1 0 0 1 1 1 0 1 1 0 1 1 0 0 0 \n 1 1 1 0 0 1 1 0 1 0 0 1 1 0 0 0 1 1 1 0 1 1 0 0 1 0 1 1 0 \n 1 0 0 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 0 \n 1 1 0 1 1 1 1 1 1 0 0 0 1 1 0 1 0 1 1 1 1 0 1 1 0 1 1 1 0 \n 1 0 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 0 1 0 0 1 1 0 1]"
},
{
"code": null,
"e": 13393,
"s": 13289,
"text": "The above series of 0s and 1s are the predicted values for the tumor classes i.e. malignant\nand benign."
},
{
"code": null,
"e": 13609,
"s": 13393,
"text": "Now, by comparing the two arrays namely test_labels and preds, we can find out the\naccuracy of our model. We are going to use the accuracy_score() function to determine\nthe accuracy. Consider the following command −"
},
{
"code": null,
"e": 13709,
"s": 13609,
"text": "from sklearn.metrics import accuracy_score\nprint(accuracy_score(test_labels,preds))\n0.951754385965\n"
},
{
"code": null,
"e": 13774,
"s": 13709,
"text": "The result shows that NaïveBayes classifier is 95.17% accurate."
},
{
"code": null,
"e": 13853,
"s": 13774,
"text": "That was machine learning classifier based on the Naïve Bayse Gaussian model."
},
{
"code": null,
"e": 14278,
"s": 13853,
"text": "Basically, Support vector machine (SVM) is a supervised machine learning algorithm that\ncan be used for both regression and classification. The main concept of SVM is to plot each\ndata item as a point in n-dimensional space with the value of each feature being the value\nof a particular coordinate. Here n would be the features we would have. Following is a\nsimple graphical representation to understand the concept of SVM −"
},
{
"code": null,
"e": 14557,
"s": 14278,
"text": "In the above diagram, we have two features. Hence, we first need to plot these two\nvariables in two dimensional space where each point has two co-ordinates, called support\nvectors. The line splits the data into two different classified groups. This line would be the\nclassifier."
},
{
"code": null,
"e": 14834,
"s": 14557,
"text": "Here, we are going to build an SVM classifier by using scikit-learn and iris dataset. Scikitlearn\nlibrary has the sklearn.svm module and provides sklearn.svm.svc for classification.\nThe SVM classifier to predict the class of the iris plant based on 4 features are shown\nbelow."
},
{
"code": null,
"e": 15153,
"s": 14834,
"text": "We will use the iris dataset which contains 3 classes of 50 instances each, where each class refers to a type of iris plant. Each instance has the four features namely sepal length, sepal width, petal length and petal width. The SVM classifier to predict the class of the iris plant based on 4 features is shown below."
},
{
"code": null,
"e": 15487,
"s": 15153,
"text": "It is a technique used by SVM. Basically these are the functions which take low-dimensional input space and transform it to a higher dimensional space. It converts non-separable problem to separable problem. The kernel function can be any one among linear, polynomial, rbf and sigmoid. In this example, we will use the linear kernel."
},
{
"code": null,
"e": 15530,
"s": 15487,
"text": "Let us now import the following packages −"
},
{
"code": null,
"e": 15635,
"s": 15530,
"text": "import pandas as pd\nimport numpy as np\nfrom sklearn import svm, datasets\nimport matplotlib.pyplot as plt"
},
{
"code": null,
"e": 15662,
"s": 15635,
"text": "Now, load the input data −"
},
{
"code": null,
"e": 15690,
"s": 15662,
"text": "iris = datasets.load_iris()"
},
{
"code": null,
"e": 15725,
"s": 15690,
"text": "We are taking first two features −"
},
{
"code": null,
"e": 15762,
"s": 15725,
"text": "X = iris.data[:, :2]\ny = iris.target"
},
{
"code": null,
"e": 15865,
"s": 15762,
"text": "We will plot the support vector machine boundaries with original data. We are creating a mesh to plot."
},
{
"code": null,
"e": 16109,
"s": 15865,
"text": "x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1\ny_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1\nh = (x_max / x_min)/100\nxx, yy = np.meshgrid(np.arange(x_min, x_max, h),\nnp.arange(y_min, y_max, h))\nX_plot = np.c_[xx.ravel(), yy.ravel()]"
},
{
"code": null,
"e": 16164,
"s": 16109,
"text": "We need to give the value of regularization parameter."
},
{
"code": null,
"e": 16172,
"s": 16164,
"text": "C = 1.0"
},
{
"code": null,
"e": 16217,
"s": 16172,
"text": "We need to create the SVM classifier object."
},
{
"code": null,
"e": 16658,
"s": 16217,
"text": "Svc_classifier = svm_classifier.SVC(kernel='linear', \nC=C, decision_function_shape = 'ovr').fit(X, y)\nZ = svc_classifier.predict(X_plot)\nZ = Z.reshape(xx.shape)\nplt.figure(figsize = (15, 5))\nplt.subplot(121)\nplt.contourf(xx, yy, Z, cmap = plt.cm.tab10, alpha = 0.3)\nplt.scatter(X[:, 0], X[:, 1], c = y, cmap = plt.cm.Set1)\nplt.xlabel('Sepal length')\nplt.ylabel('Sepal width')\nplt.xlim(xx.min(), xx.max())\nplt.title('SVC with linear kernel')"
},
{
"code": null,
"e": 16923,
"s": 16658,
"text": "Basically, logistic regression model is one of the members of supervised classification algorithm family. Logistic regression measures the relationship between dependent variables and independent variables by estimating the probabilities using a logistic function."
},
{
"code": null,
"e": 17173,
"s": 16923,
"text": "Here, if we talk about dependent and independent variables then dependent variable is the target class variable we are going to predict and on the other side the independent variables are the features we are going to use to predict the target class."
},
{
"code": null,
"e": 17701,
"s": 17173,
"text": "In logistic regression, estimating the probabilities means to predict the likelihood occurrence of the event. For example, the shop owner would like to predict the customer who entered into the shop will buy the play station (for example) or not. There would be many features of customer − gender, age, etc. which would be observed by the shop keeper to predict the likelihood occurrence, i.e., buying a play station or not. The logistic function is the sigmoid curve that is used to build the function with various parameters."
},
{
"code": null,
"e": 17886,
"s": 17701,
"text": "Before building the classifier using logistic regression, we need to install the Tkinter package on our system. It can be installed from https://docs.python.org/2/library/tkinter.html."
},
{
"code": null,
"e": 17985,
"s": 17886,
"text": "Now, with the help of the code given below, we can create a classifier using logistic regression −"
},
{
"code": null,
"e": 18023,
"s": 17985,
"text": "First, we will import some packages −"
},
{
"code": null,
"e": 18107,
"s": 18023,
"text": "import numpy as np\nfrom sklearn import linear_model\nimport matplotlib.pyplot as plt"
},
{
"code": null,
"e": 18177,
"s": 18107,
"text": "Now, we need to define the sample data which can be done as follows −"
},
{
"code": null,
"e": 18386,
"s": 18177,
"text": "X = np.array([[2, 4.8], [2.9, 4.7], [2.5, 5], [3.2, 5.5], [6, 5], [7.6, 4],\n [3.2, 0.9], [2.9, 1.9],[2.4, 3.5], [0.5, 3.4], [1, 4], [0.9, 5.9]])\ny = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3])"
},
{
"code": null,
"e": 18477,
"s": 18386,
"text": "Next, we need to create the logistic regression classifier, which can be done as follows −"
},
{
"code": null,
"e": 18555,
"s": 18477,
"text": "Classifier_LR = linear_model.LogisticRegression(solver = 'liblinear', C = 75)"
},
{
"code": null,
"e": 18614,
"s": 18555,
"text": "Last but not the least, we need to train this classifier −"
},
{
"code": null,
"e": 18638,
"s": 18614,
"text": "Classifier_LR.fit(X, y)"
},
{
"code": null,
"e": 18743,
"s": 18638,
"text": "Now, how we can visualize the output? It can be done by creating a function named Logistic_visualize() −"
},
{
"code": null,
"e": 18907,
"s": 18743,
"text": "Def Logistic_visualize(Classifier_LR, X, y):\n min_x, max_x = X[:, 0].min() - 1.0, X[:, 0].max() + 1.0\n min_y, max_y = X[:, 1].min() - 1.0, X[:, 1].max() + 1.0\n"
},
{
"code": null,
"e": 19071,
"s": 18907,
"text": "In the above line, we defined the minimum and maximum values X and Y to be used in mesh grid. In addition, we will define the step size for plotting the mesh grid."
},
{
"code": null,
"e": 19093,
"s": 19071,
"text": "mesh_step_size = 0.02"
},
{
"code": null,
"e": 19152,
"s": 19093,
"text": "Let us define the mesh grid of X and Y values as follows −"
},
{
"code": null,
"e": 19280,
"s": 19152,
"text": "x_vals, y_vals = np.meshgrid(np.arange(min_x, max_x, mesh_step_size),\n np.arange(min_y, max_y, mesh_step_size))"
},
{
"code": null,
"e": 19358,
"s": 19280,
"text": "With the help of following code, we can run the classifier on the mesh grid −"
},
{
"code": null,
"e": 19640,
"s": 19358,
"text": "output = classifier.predict(np.c_[x_vals.ravel(), y_vals.ravel()])\noutput = output.reshape(x_vals.shape)\nplt.figure()\nplt.pcolormesh(x_vals, y_vals, output, cmap = plt.cm.gray)\n \nplt.scatter(X[:, 0], X[:, 1], c = y, s = 75, edgecolors = 'black', \nlinewidth=1, cmap = plt.cm.Paired)"
},
{
"code": null,
"e": 19707,
"s": 19640,
"text": "The following line of code will specify the boundaries of the plot"
},
{
"code": null,
"e": 19946,
"s": 19707,
"text": "plt.xlim(x_vals.min(), x_vals.max())\nplt.ylim(y_vals.min(), y_vals.max())\nplt.xticks((np.arange(int(X[:, 0].min() - 1), int(X[:, 0].max() + 1), 1.0)))\nplt.yticks((np.arange(int(X[:, 1].min() - 1), int(X[:, 1].max() + 1), 1.0)))\nplt.show()"
},
{
"code": null,
"e": 20041,
"s": 19946,
"text": "Now, after running the code we will get the following output, logistic regression classifier −"
},
{
"code": null,
"e": 20177,
"s": 20041,
"text": "A decision tree is basically a binary tree flowchart where each node splits a group of observations according to some feature variable."
},
{
"code": null,
"e": 20388,
"s": 20177,
"text": "Here, we are building a Decision Tree classifier for predicting male or female. We will take a very small data set having 19 samples. These samples would consist of two features – ‘height’ and ‘length of hair’."
},
{
"code": null,
"e": 20644,
"s": 20388,
"text": "For building the following classifier, we need to install pydotplus and graphviz. Basically, graphviz is a tool for drawing graphics using dot files and pydotplus is a module to Graphviz’s Dot language. It can be installed with the package manager or pip."
},
{
"code": null,
"e": 20736,
"s": 20644,
"text": "Now, we can build the decision tree classifier with the help of the following Python code −"
},
{
"code": null,
"e": 20803,
"s": 20736,
"text": "To begin with, let us import some important libraries as follows −"
},
{
"code": null,
"e": 20990,
"s": 20803,
"text": "import pydotplus\nfrom sklearn import tree\nfrom sklearn.datasets import load_iris\nfrom sklearn.metrics import classification_report\nfrom sklearn import cross_validation\nimport collections"
},
{
"code": null,
"e": 21039,
"s": 20990,
"text": "Now, we need to provide the dataset as follows −"
},
{
"code": null,
"e": 21517,
"s": 21039,
"text": "X = [[165,19],[175,32],[136,35],[174,65],[141,28],[176,15],[131,32],\n[166,6],[128,32],[179,10],[136,34],[186,2],[126,25],[176,28],[112,38],\n[169,9],[171,36],[116,25],[196,25]]\n\nY = ['Man','Woman','Woman','Man','Woman','Man','Woman','Man','Woman',\n'Man','Woman','Man','Woman','Woman','Woman','Man','Woman','Woman','Man']\ndata_feature_names = ['height','length of hair']\n\nX_train, X_test, Y_train, Y_test = cross_validation.train_test_split\n(X, Y, test_size=0.40, random_state=5)"
},
{
"code": null,
"e": 21602,
"s": 21517,
"text": "After providing the dataset, we need to fit the model which can be done as follows −"
},
{
"code": null,
"e": 21657,
"s": 21602,
"text": "clf = tree.DecisionTreeClassifier()\nclf = clf.fit(X,Y)"
},
{
"code": null,
"e": 21725,
"s": 21657,
"text": "Prediction can be made with the help of the following Python code −"
},
{
"code": null,
"e": 21781,
"s": 21725,
"text": "prediction = clf.predict([[133,37]])\nprint(prediction)\n"
},
{
"code": null,
"e": 21861,
"s": 21781,
"text": "We can visualize the decision tree with the help of the following Python code −"
},
{
"code": null,
"e": 22377,
"s": 21861,
"text": "dot_data = tree.export_graphviz(clf,feature_names = data_feature_names,\n out_file = None,filled = True,rounded = True)\ngraph = pydotplus.graph_from_dot_data(dot_data)\ncolors = ('orange', 'yellow')\nedges = collections.defaultdict(list)\n\nfor edge in graph.get_edge_list():\nedges[edge.get_source()].append(int(edge.get_destination()))\n\nfor edge in edges: edges[edge].sort()\n\nfor i in range(2):dest = graph.get_node(str(edges[edge][i]))[0]\ndest.set_fillcolor(colors[i])\ngraph.write_png('Decisiontree16.png')\n"
},
{
"code": null,
"e": 22478,
"s": 22377,
"text": "It will give the prediction for the above code as [‘Woman’] and create the following decision tree −"
},
{
"code": null,
"e": 22541,
"s": 22478,
"text": "We can change the values of features in prediction to test it."
},
{
"code": null,
"e": 22962,
"s": 22541,
"text": "As we know that ensemble methods are the methods which combine machine learning models into a more powerful machine learning model. Random Forest, a collection of decision trees, is one of them. It is better than single decision tree because while retaining the predictive powers it can reduce over-fitting by averaging the results. Here, we are going to implement the random forest model on scikit learn cancer dataset."
},
{
"code": null,
"e": 22994,
"s": 22962,
"text": "Import the necessary packages −"
},
{
"code": null,
"e": 23228,
"s": 22994,
"text": "from sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.datasets import load_breast_cancer\ncancer = load_breast_cancer()\nimport matplotlib.pyplot as plt\nimport numpy as np"
},
{
"code": null,
"e": 23300,
"s": 23228,
"text": "Now, we need to provide the dataset which can be done as follows &minus"
},
{
"code": null,
"e": 23428,
"s": 23300,
"text": "cancer = load_breast_cancer()\nX_train, X_test, y_train,\ny_test = train_test_split(cancer.data, cancer.target, random_state = 0)"
},
{
"code": null,
"e": 23513,
"s": 23428,
"text": "After providing the dataset, we need to fit the model which can be done as follows −"
},
{
"code": null,
"e": 23610,
"s": 23513,
"text": "forest = RandomForestClassifier(n_estimators = 50, random_state = 0)\nforest.fit(X_train,y_train)"
},
{
"code": null,
"e": 23778,
"s": 23610,
"text": "Now, get the accuracy on training as well as testing subset: if we will increase the number of estimators then, the accuracy of testing subset would also be increased."
},
{
"code": null,
"e": 23948,
"s": 23778,
"text": "print('Accuracy on the training subset:(:.3f)',format(forest.score(X_train,y_train)))\nprint('Accuracy on the training subset:(:.3f)',format(forest.score(X_test,y_test)))"
},
{
"code": null,
"e": 24049,
"s": 23948,
"text": "Accuracy on the training subset:(:.3f) 1.0\nAccuracy on the training subset:(:.3f) 0.965034965034965\n"
},
{
"code": null,
"e": 24239,
"s": 24049,
"text": "Now, like the decision tree, random forest has the feature_importance module which will provide a better view of feature weight than decision tree. It can be plot and visualize as follows −"
},
{
"code": null,
"e": 24466,
"s": 24239,
"text": "n_features = cancer.data.shape[1]\nplt.barh(range(n_features),forest.feature_importances_, align='center')\nplt.yticks(np.arange(n_features),cancer.feature_names)\nplt.xlabel('Feature Importance')\nplt.ylabel('Feature')\nplt.show()"
},
{
"code": null,
"e": 25182,
"s": 24466,
"text": "After implementing a machine learning algorithm, we need to find out how effective the model is. The criteria for measuring the effectiveness may be based upon datasets and metric. For evaluating different machine learning algorithms, we can use different performance metrics. For example, suppose if a classifier is used to distinguish between images of different objects, we can use the classification performance metrics such as average accuracy, AUC, etc. In one or other sense, the metric we choose to evaluate our machine learning model is very important because the choice of metrics influences how the performance of a machine learning algorithm is measured and compared. Following are some of the metrics −"
},
{
"code": null,
"e": 25565,
"s": 25182,
"text": "Basically it is used for classification problem where the output can be of two or more types of classes. It is the easiest way to measure the performance of a classifier. A confusion matrix is basically a table with two dimensions namely “Actual” and “Predicted”. Both the dimensions have “True Positives (TP)”, “True Negatives (TN)”, “False Positives (FP)”, “False Negatives (FN)”."
},
{
"code": null,
"e": 25649,
"s": 25565,
"text": "In the confusion matrix above, 1 is for positive class and 0 is for negative class."
},
{
"code": null,
"e": 25708,
"s": 25649,
"text": "Following are the terms associated with Confusion matrix −"
},
{
"code": null,
"e": 25814,
"s": 25708,
"text": "True Positives − TPs are the cases when the actual class of data point was 1 and the predicted is also 1."
},
{
"code": null,
"e": 25920,
"s": 25814,
"text": "True Positives − TPs are the cases when the actual class of data point was 1 and the predicted is also 1."
},
{
"code": null,
"e": 26030,
"s": 25920,
"text": "True Negatives − TNs are the cases when the actual class of the data point was 0 and the predicted is also 0."
},
{
"code": null,
"e": 26140,
"s": 26030,
"text": "True Negatives − TNs are the cases when the actual class of the data point was 0 and the predicted is also 0."
},
{
"code": null,
"e": 26247,
"s": 26140,
"text": "False Positives − FPs are the cases when the actual class of data point was 0 and the predicted is also 1."
},
{
"code": null,
"e": 26354,
"s": 26247,
"text": "False Positives − FPs are the cases when the actual class of data point was 0 and the predicted is also 1."
},
{
"code": null,
"e": 26465,
"s": 26354,
"text": "False Negatives − FNs are the cases when the actual class of the data point was 1 and the predicted is also 0."
},
{
"code": null,
"e": 26576,
"s": 26465,
"text": "False Negatives − FNs are the cases when the actual class of the data point was 1 and the predicted is also 0."
},
{
"code": null,
"e": 26935,
"s": 26576,
"text": "The confusion matrix itself is not a performance measure as such but almost all the performance matrices are based on the confusion matrix. One of them is accuracy. In classification problems, it may be defined as the number of correct predictions made by the model over all kinds of predictions made. The formula for calculating the accuracy is as follows −"
},
{
"code": null,
"e": 26976,
"s": 26935,
"text": "$$Accuracy = \\frac{TP+TN}{TP+FP+FN+TN}$$"
},
{
"code": null,
"e": 27144,
"s": 26976,
"text": "It is mostly used in document retrievals. It may be defined as how many of the returned documents are correct. Following is the formula for calculating the precision −"
},
{
"code": null,
"e": 27177,
"s": 27144,
"text": "$$Precision = \\frac{TP}{TP+FP}$$"
},
{
"code": null,
"e": 27324,
"s": 27177,
"text": "It may be defined as how many of the positives do the model return. Following is the formula for calculating the recall/sensitivity of the model −"
},
{
"code": null,
"e": 27354,
"s": 27324,
"text": "$$Recall = \\frac{TP}{TP+FN}$$"
},
{
"code": null,
"e": 27528,
"s": 27354,
"text": "It may be defined as how many of the negatives do the model return. It is exactly opposite to recall. Following is the formula for calculating the specificity of the model −"
},
{
"code": null,
"e": 27563,
"s": 27528,
"text": "$$Specificity = \\frac{TN}{TN+FP}$$"
},
{
"code": null,
"e": 27854,
"s": 27563,
"text": "Class imbalance is the scenario where the number of observations belonging to one class is significantly lower than those belonging to the other classes. For example, this problem is prominent in the scenario where we need to identify the rare diseases, fraudulent transactions in bank etc."
},
{
"code": null,
"e": 27957,
"s": 27854,
"text": "Let us consider an example of fraud detection data set to understand the concept of imbalanced class −"
},
{
"code": null,
"e": 28063,
"s": 27957,
"text": "Total observations = 5000\nFraudulent Observations = 50\nNon-Fraudulent Observations = 4950\nEvent Rate = 1%"
},
{
"code": null,
"e": 28351,
"s": 28063,
"text": "Balancing the classes’ acts as a solution to imbalanced classes. The main objective of balancing the classes is to either increase the frequency of the minority class or decrease the frequency of the majority class. Following are the approaches to solve the issue of imbalances classes −"
},
{
"code": null,
"e": 28564,
"s": 28351,
"text": "Re-sampling is a series of methods used to reconstruct the sample data sets − both training sets and testing sets. Re-sampling is done to improve the accuracy of model. Following are some re-sampling techniques −"
},
{
"code": null,
"e": 28766,
"s": 28564,
"text": "Random Under-Sampling − This technique aims to balance class distribution by randomly eliminating majority class examples. This is done until the majority and minority class instances are balanced out."
},
{
"code": null,
"e": 28968,
"s": 28766,
"text": "Random Under-Sampling − This technique aims to balance class distribution by randomly eliminating majority class examples. This is done until the majority and minority class instances are balanced out."
},
{
"code": null,
"e": 29074,
"s": 28968,
"text": "Total observations = 5000\nFraudulent Observations = 50\nNon-Fraudulent Observations = 4950\nEvent Rate = 1%"
},
{
"code": null,
"e": 29208,
"s": 29074,
"text": "In this case, we are taking 10% samples without replacement from non-fraud instances and then combine them with the fraud instances −"
},
{
"code": null,
"e": 29284,
"s": 29208,
"text": "Non-fraudulent observations after random under sampling = 10% of 4950 = 495"
},
{
"code": null,
"e": 29368,
"s": 29284,
"text": "Total observations after combining them with fraudulent observations = 50+495 = 545"
},
{
"code": null,
"e": 29436,
"s": 29368,
"text": "Hence now, the event rate for new dataset after under sampling = 9%"
},
{
"code": null,
"e": 29634,
"s": 29436,
"text": "The main advantage of this technique is that it can reduce run time and improve storage. But on the other side, it can discard useful information while reducing the number of training data samples."
},
{
"code": null,
"e": 29788,
"s": 29634,
"text": "Random Over-Sampling − This technique aims to balance class distribution by increasing the number of instances in the minority class by replicating them."
},
{
"code": null,
"e": 29942,
"s": 29788,
"text": "Random Over-Sampling − This technique aims to balance class distribution by increasing the number of instances in the minority class by replicating them."
},
{
"code": null,
"e": 30048,
"s": 29942,
"text": "Total observations = 5000\nFraudulent Observations = 50\nNon-Fraudulent Observations = 4950\nEvent Rate = 1%"
},
{
"code": null,
"e": 30363,
"s": 30048,
"text": "In case we are replicating 50 fraudulent observations 30 times then fraudulent observations after replicating the minority class observations would be 1500. And then total observations in the new data after oversampling would be 4950+1500 = 6450. Hence the event rate for the new data set would be 1500/6450 = 23%."
},
{
"code": null,
"e": 30568,
"s": 30363,
"text": "The main advantage of this method is that there would be no loss of useful information. But on the other hand, it has the increased chances of over-fitting because it replicates the minority class events."
},
{
"code": null,
"e": 30888,
"s": 30568,
"text": "This methodology basically is used to modify existing classification algorithms to make them appropriate for imbalanced data sets. In this approach we construct several two stage classifier from the original data and then aggregate their predictions. Random forest classifier is an example of ensemble based classifier."
},
{
"code": null,
"e": 30921,
"s": 30888,
"text": "\n 78 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 30940,
"s": 30921,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 30975,
"s": 30940,
"text": "\n 87 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 31006,
"s": 30975,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 31039,
"s": 31006,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 31058,
"s": 31039,
"text": " Nikoloz Sanakoevi"
},
{
"code": null,
"e": 31090,
"s": 31058,
"text": "\n 15 Lectures \n 54 mins\n"
},
{
"code": null,
"e": 31111,
"s": 31090,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 31144,
"s": 31111,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 31162,
"s": 31144,
"text": " Gilad James, PhD"
},
{
"code": null,
"e": 31195,
"s": 31162,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 31213,
"s": 31195,
"text": " Gilad James, PhD"
},
{
"code": null,
"e": 31220,
"s": 31213,
"text": " Print"
},
{
"code": null,
"e": 31231,
"s": 31220,
"text": " Add Notes"
}
] |
How do I create and use a sequence in MySQL?
|
To create a sequence in MySQL, auto_increment can be used on the column. It starts from the
value 1 and increments by 1 for each record when it is inserted.
First, a table is created with the help of CREATE table. The query for that is as follows −
mysql> CREATE table SequenceDemo
-> (
-> SequenceId int auto_increment,
-> primary key(SequenceId)
-> );
Query OK, 0 rows affected (1.22 sec)
After creating the table, the records can be inserted with the help of the insert command which
is given as follows −
mysql> INSERT into SequenceDemo values();
Query OK, 1 row affected (0.19 sec)
mysql> INSERT into SequenceDemo values();
Query OK, 1 row affected (0.14 sec)
mysql> INSERT into SequenceDemo values();
Query OK, 1 row affected (0.10 sec)
mysql> INSERT into SequenceDemo values();
Query OK, 1 row affected (0.12 sec)
mysql> INSERT into SequenceDemo values();
Query OK, 1 row affected (0.09 sec)
After inserting the records, they can be displayed with the help of the select statement which is
given as follows −
mysql> SELECT * from SequenceDemo;
The following is the output obtained −
+------------+
| SequenceId |
+------------+
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
+------------+
5 rows in set (0.00 sec)
The sequence can be set with the help of the alter command.The syntax for this is given as
follows −
alter table yourTableName auto_increment=Somevalue;
Now, the above syntax is used in the following query to set the sequence value as follows −
mysql> alter table SequenceDemo auto_increment = 500;
Query OK, 0 rows affected (0.17 sec)
Records: 0 Duplicates: 0 Warnings: 0
After that, the records are inserted from the value 500 in the table. This is given below −
mysql> INSERT into SequenceDemo values();
Query OK, 1 row affected (0.15 sec)
mysql> INSERT into SequenceDemo values();
Query OK, 1 row affected (0.15 sec)
mysql> INSERT into SequenceDemo values();
Query OK, 1 row affected (0.05 sec)
All the records can be displayed with the select statement as follows −
mysql> SELECT * from SequenceDemo;
The output is given below
+------------+
| SequenceId |
+------------+
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 500 |
| 501 |
| 502 |
+------------+
8 rows in set (0.00 sec)
As can be seen from the above output, after 5 records the sequence id starts from 500 and is
incremented by 1.
|
[
{
"code": null,
"e": 1219,
"s": 1062,
"text": "To create a sequence in MySQL, auto_increment can be used on the column. It starts from the\nvalue 1 and increments by 1 for each record when it is inserted."
},
{
"code": null,
"e": 1311,
"s": 1219,
"text": "First, a table is created with the help of CREATE table. The query for that is as follows −"
},
{
"code": null,
"e": 1453,
"s": 1311,
"text": "mysql> CREATE table SequenceDemo\n-> (\n-> SequenceId int auto_increment,\n-> primary key(SequenceId)\n-> );\nQuery OK, 0 rows affected (1.22 sec)"
},
{
"code": null,
"e": 1571,
"s": 1453,
"text": "After creating the table, the records can be inserted with the help of the insert command which\nis given as follows −"
},
{
"code": null,
"e": 1965,
"s": 1571,
"text": "mysql> INSERT into SequenceDemo values();\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> INSERT into SequenceDemo values();\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> INSERT into SequenceDemo values();\nQuery OK, 1 row affected (0.10 sec)\n\nmysql> INSERT into SequenceDemo values();\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> INSERT into SequenceDemo values();\nQuery OK, 1 row affected (0.09 sec)"
},
{
"code": null,
"e": 2082,
"s": 1965,
"text": "After inserting the records, they can be displayed with the help of the select statement which is\ngiven as follows −"
},
{
"code": null,
"e": 2118,
"s": 2082,
"text": "mysql> SELECT * from SequenceDemo;\n"
},
{
"code": null,
"e": 2157,
"s": 2118,
"text": "The following is the output obtained −"
},
{
"code": null,
"e": 2317,
"s": 2157,
"text": "+------------+\n| SequenceId |\n+------------+\n| 1 |\n| 2 |\n| 3 |\n| 4 |\n| 5 |\n+------------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2418,
"s": 2317,
"text": "The sequence can be set with the help of the alter command.The syntax for this is given as\nfollows −"
},
{
"code": null,
"e": 2471,
"s": 2418,
"text": "alter table yourTableName auto_increment=Somevalue;\n"
},
{
"code": null,
"e": 2563,
"s": 2471,
"text": "Now, the above syntax is used in the following query to set the sequence value as follows −"
},
{
"code": null,
"e": 2691,
"s": 2563,
"text": "mysql> alter table SequenceDemo auto_increment = 500;\nQuery OK, 0 rows affected (0.17 sec)\nRecords: 0 Duplicates: 0 Warnings: 0"
},
{
"code": null,
"e": 2783,
"s": 2691,
"text": "After that, the records are inserted from the value 500 in the table. This is given below −"
},
{
"code": null,
"e": 3019,
"s": 2783,
"text": "mysql> INSERT into SequenceDemo values();\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> INSERT into SequenceDemo values();\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> INSERT into SequenceDemo values();\nQuery OK, 1 row affected (0.05 sec)"
},
{
"code": null,
"e": 3091,
"s": 3019,
"text": "All the records can be displayed with the select statement as follows −"
},
{
"code": null,
"e": 3127,
"s": 3091,
"text": "mysql> SELECT * from SequenceDemo;\n"
},
{
"code": null,
"e": 3153,
"s": 3127,
"text": "The output is given below"
},
{
"code": null,
"e": 3358,
"s": 3153,
"text": "+------------+\n| SequenceId |\n+------------+\n| 1 |\n| 2 |\n| 3 |\n| 4 |\n| 5 |\n| 500 |\n| 501 |\n| 502 |\n+------------+\n8 rows in set (0.00 sec)"
},
{
"code": null,
"e": 3469,
"s": 3358,
"text": "As can be seen from the above output, after 5 records the sequence id starts from 500 and is\nincremented by 1."
}
] |
SVM From Scratch — Python. Important Concepts Summarized | by Qandeel Abbassi | Towards Data Science
|
1. SVM Introduction2. Reading the Dataset3. Feature Engineering4. Splitting the Dataset5. Cost Function6. The Gradient of the Cost Function7. Train Model Using SGD8. Stoppage Criterion for SGD9. Testing the Model10. Feature Selection With Correlation & P-values11. Give Me the Code
Before diving right into the code or technical details, I would like to mention that while there are many libraries/frameworks available to implement SVM (Support Vector Machine) algorithm without writing a bunch of code, I decided to write the code with as few high-level libraries as possible so that you and I can get a good grasp of important components involved in training an SVM model (with 99% accuracy, 0.98 recall, and precision). If you are looking for a quick implementation of SVM, then you are better off using packages like scikit-learn, cvxopt, etc. Otherwise, let’s get started!
The SVM (Support Vector Machine) is a supervised machine learning algorithm typically used for binary classification problems. It’s trained by feeding a dataset with labeled examples (xi, yi). For instance, if your examples are email messages and your problem is spam detection, then:
An example email message xi is defined as an n-dimensional feature vector that can be plotted on n-dimensional space.
The feature vector, as the name explains, contains features (eg. word count, link count, etc.) of your email message in numerical form
Each feature vector is labeled with a class yi
The class yi can either be a +ve or -ve (eg. spam=1, not-spam=-1)
Using this dataset the algorithm finds a hyperplane (or decision boundary) which should ideally have the following properties:
It creates separation between examples of two classes with a maximum margin
Its equation (w.x + b = 0) yields a value ≥ 1 for examples from+ve class and ≤-1 for examples from -ve class
How does it find this hyperplane? By finding the optimal values w* (weights/normal) and b* (intercept) which define this hyperplane. The optimal values are found by minimizing a cost function. Once the algorithm identifies these optimal values, the SVM model f(x) is then defined as shown below:
Before we move any further let’s import the required packages for this tutorial and create a skeleton of our program svm.py:
# svm.pyimport numpy as np # for handling multi-dimensional array operationimport pandas as pd # for reading data from csv import statsmodels.api as sm # for finding the p-valuefrom sklearn.preprocessing import MinMaxScaler # for normalizationfrom sklearn.model_selection import train_test_split as ttsfrom sklearn.metrics import accuracy_score from sklearn.utils import shuffle# >> FEATURE SELECTION << #def remove_correlated_features(X):def remove_less_significant_features(X, Y):# >> MODEL TRAINING << #def compute_cost(W, X, Y):def calculate_cost_gradient(W, X_batch, Y_batch):def sgd(features, outputs):def init():
We’ll be working with a breast cancer dataset available on Kaggle. The features in the dataset are computed from a digitized image of a fine needle aspirate (FNA) of a breast mass. They describe the characteristics of the cell nuclei present in the image. Based on these features we will train our SVM model to detect if the mass is benign B (generally harmless) or malignant M (cancerous).
Download the dataset and place the data.csv file in the same folder as svm.py. Then add this code inside init() function:
def init(): data = pd.read_csv('./data.csv') # SVM only accepts numerical values. # Therefore, we will transform the categories M and B into # values 1 and -1 (or -1 and 1), respectively. diagnosis_map = {'M':1, 'B':-1} data['diagnosis'] = data['diagnosis'].map(diagnosis_map) # drop last column (extra column added by pd) # and unnecessary first column (id) data.drop(data.columns[[-1, 0]], axis=1, inplace=True)
read_csv() function of the Pandas package reads data from the .csv file and stores it in a DataFrame. Think of DataFrame as an implementation of a data structure that looks like a table with labeled columns and rows. Here’s how the data read from data.csv looks like inside DataFrame:
As you can see the labels and structure of our dataset are preserved and that’s what makes DataFrame intuitive.
Machine learning algorithms operate on a dataset that is a collection of labeled examples which consist of features and a label i.e. in our case diagnosis is a label, [radius_mean, structure_mean, texture_mean...] features, and each row is an example.
In most of the cases, the data you collect at first might be raw; its either incompatible with your model or hinders its performance. That’s when feature engineering comes to rescue. It encompasses preprocessing techniques to compile a dataset by extracting features from raw data. These techniques have two characteristics in common:
Preparing the data which is compatible with the model
Improving the performance of the machine learning algorithm
Normalization is one of the many feature engineering techniques that we are going to use. Normalization is the process of converting a range of values, into a standard range of values, typically in the interval [−1, 1] or [0, 1]. It’s not a strict requirement but it improves the speed of learning (e.g. faster convergence in gradient descent) and prevents numerical overflow. Add following code in init() functions to normalize all of your features:
# inside init()# put features & outputs in different DataFrames for convenienceY = data.loc[:, 'diagnosis'] # all rows of 'diagnosis' X = data.iloc[:, 1:] # all rows of column 1 and ahead (features)# normalize the features using MinMaxScalar from# sklearn.preprocessingX_normalized = MinMaxScaler().fit_transform(X.values)X = pd.DataFrame(X_normalized)
We’ll split the dataset into train and test set using the train_test_split() function from sklearn.model_selection. We need a separate dataset for testing because we need to see how our model will perform on unseen observations. Add this code in init():
# inside init()# first insert 1 in every row for intercept bX.insert(loc=len(X.columns), column='intercept', value=1)# test_size is the portion of data that will go into test set# random_state is the seed used by the random number generatorprint("splitting dataset into train and test sets...")X_train, X_test, y_train, y_test = tts(X, Y, test_size=0.2, random_state=42)
If you are confused about why we added 1 in every row then don’t worry. You will get the answer in the next section.
Also known as the Objective Function. One of the building blocks of every machine learning algorithm, it’s the function we try to minimize or maximize to achieve our objective.
What’s our objective in SVM? Our objective is to find a hyperplane that separates +ve and -ve examples with the largest margin while keeping the misclassification as low as possible (see Figure 3).
How do we achieve this objective? We will minimize the cost/objective function shown below:
You might have seen another version of a cost function that looks like this:
In this cost function, λ is essentially equal to 1/C and has the opposite effect i.e larger λ gives a wider margin and vice versa. We can use any of the above cost functions keeping in mind what each regularization parameter (C and λ) does and then tuning them accordingly. Let’s see how can we calculate the total cost as given in (1) and then we will move on to its gradient which will be used in the training phase to minimize it:
def compute_cost(W, X, Y): # calculate hinge loss N = X.shape[0] distances = 1 - Y * (np.dot(X, W)) distances[distances < 0] = 0 # equivalent to max(0, distance) hinge_loss = reg_strength * (np.sum(distances) / N) # calculate cost cost = 1 / 2 * np.dot(W, W) + hinge_loss return cost
As you might have noticed that the intercept term b is missing. That’s because we have pushed it into the weight vector like this:
That’s why we added an extra column with all 1s before splitting our dataset. Keep this in mind for the rest of the tutorial.
As you would have noticed there are some changes in cost function in equation (4). Don’t worry, if you solve it analytically it’s the same. Now let’s implement the calculate_cost_gradient() function using equation (5):
# I haven't tested it but this same function should work for# vanilla and mini-batch gradient descent as welldef calculate_cost_gradient(W, X_batch, Y_batch): # if only one example is passed (eg. in case of SGD) if type(Y_batch) == np.float64: Y_batch = np.array([Y_batch]) X_batch = np.array([X_batch]) distance = 1 - (Y_batch * np.dot(X_batch, W)) dw = np.zeros(len(W)) for ind, d in enumerate(distance): if max(0, d) == 0: di = W else: di = W - (reg_strength * Y_batch[ind] * X_batch[ind]) dw += di dw = dw/len(Y_batch) # average return dw
Remember I said above, “To achieve our objective we try to minimize or maximize the cost function”. In the SVM algorithm, we minimize the cost function.
Why do we minimize the cost function? Because the cost function is essentially a measure of how bad our model is doing at achieving the objective. If you look closely at J(w), to find it’s minimum, we have to:
Minimize ∣∣w∣∣2 which maximizes margin (2/∣∣w∣∣)Minimize the sum of hinge loss which minimizes misclassifications.
Minimize ∣∣w∣∣2 which maximizes margin (2/∣∣w∣∣)
Minimize the sum of hinge loss which minimizes misclassifications.
Because both of our SVM objectives are achieved by minimizing the cost function, that’s why we minimize it.
How do we minimize it? Well, there are multiple ways but the one we will use is called Stochastic Gradient Descent or SGD. Before diving into SGD, I will briefly explain how Gradient Descent works in the first place.
Gradient descent algorithm works as follows:
Find the gradient of cost function i.e. ∇J(w’)Move opposite to the gradient by a certain rate i.e. w’ = w’ — ∝(∇J(w’))Repeat step 1–3 until convergence i.e we found w’ where J(w) is smallest
Find the gradient of cost function i.e. ∇J(w’)
Move opposite to the gradient by a certain rate i.e. w’ = w’ — ∝(∇J(w’))
Repeat step 1–3 until convergence i.e we found w’ where J(w) is smallest
Why does it move opposite to the direction of the gradient? Because gradient is the direction of the fastest increase of the function. We need to move opposite to that direction to minimize our function J(w). Hence, the word “descent” in Gradient Descent is used.
In typical gradient descent (a.k.a vanilla gradient descent) the step 1 above is calculated using all the examples (1...N). In SGD, however, only 1 example is used at a time. I won’t discuss the benefits of SGD here but you can find some useful links at the end of this blog. Here’s how to implement the SGD in code:
def sgd(features, outputs): max_epochs = 5000 weights = np.zeros(features.shape[1]) # stochastic gradient descent for epoch in range(1, max_epochs): # shuffle to prevent repeating update cycles X, Y = shuffle(features, outputs) for ind, x in enumerate(X): ascent = calculate_cost_gradient(weights, x, Y[ind]) weights = weights - (learning_rate * ascent) return weights
Let’s call it inside init() function by adding this code:
# inside init()# train the modelprint("training started...")W = sgd(X_train.to_numpy(), y_train.to_numpy())print("training finished.")print("weights are: {}".format(W))
In the above implementation of sgd() we are running the loop 5000 times (could have been any number). Each iteration costs us time and extra computations. We don’t need to complete all the iterations. We can terminate the loop when our stoppage criterion is met.
What should be the stoppage criterion? There are multiple options, but we will use the simplest one. We will stop the training when the current cost hasn’t decreased much as compared to the previous cost. Here is how we will define sgd() with stoppage criterion:
def sgd(features, outputs): max_epochs = 5000 weights = np.zeros(features.shape[1]) nth = 0 prev_cost = float("inf") cost_threshold = 0.01 # in percent # stochastic gradient descent for epoch in range(1, max_epochs): # shuffle to prevent repeating update cycles X, Y = shuffle(features, outputs) for ind, x in enumerate(X): ascent = calculate_cost_gradient(weights, x, Y[ind]) weights = weights - (learning_rate * ascent) # convergence check on 2^nth epoch if epoch == 2 ** nth or epoch == max_epochs - 1: cost = compute_cost(weights, features, outputs) print("Epoch is:{} and Cost is: {}".format(epoch, cost)) # stoppage criterion if abs(prev_cost - cost) < cost_threshold * prev_cost: return weights prev_cost = cost nth += 1 return weights
After training the model using SGD we finally got the optimal weights w* which defines the best possible hyperplane separating two classes. Let’s test our model using this hyperplane. Add this code in init() function:
# inside init()# testing the model on test sety_test_predicted = np.array([])for i in range(X_test.shape[0]): yp = np.sign(np.dot(W, X_test.to_numpy()[i])) #model y_test_predicted = np.append(y_test_predicted, yp)print("accuracy on test dataset: {}".format(accuracy_score(y_test.to_numpy(), y_test_predicted)))print("recall on test dataset: {}".format(recall_score(y_test.to_numpy(), y_test_predicted)))print("precision on test dataset: {}".format(recall_score(y_test.to_numpy(), y_test_predicted)))
Now let’s call init() function:
# set hyper-parameters and call init# hyper-parameters are normally tuned using cross-validation# but following work good enoughreg_strength = 10000 # regularization strengthlearning_rate = 0.000001init()
Here’s the output:
# OUTPUTreading dataset...applying feature engineering...splitting dataset into train and test sets...training started...Epoch is: 1 and Cost is: 5333.266133501857Epoch is: 2 and Cost is: 3421.9128432834573Epoch is: 4 and Cost is: 2437.2790231100216Epoch is: 8 and Cost is: 1880.2998267933792Epoch is: 16 and Cost is: 1519.5578612139725Epoch is: 32 and Cost is: 1234.642324549297Epoch is: 64 and Cost is: 977.3285621274708Epoch is: 128 and Cost is: 804.8893546235923Epoch is: 256 and Cost is: 703.407799431284Epoch is: 512 and Cost is: 645.8275191300031Epoch is: 1024 and Cost is: 631.6024252740094Epoch is: 2048 and Cost is: 615.8378582171482Epoch is: 4096 and Cost is: 605.0990964730645Epoch is: 4999 and Cost is: 606.8186618758745training finished.weights are: [ 1.32516553 0.83500639 1.12489803 2.16072054 -1.24845441 -3.24246498 3.27876342 6.83028706 -0.46562238 0.10063844 5.68881254 -1.93421932 3.27394523 3.77331751 1.67333278 -2.43170464 -1.7683188 0.84065607 -1.9612766 -1.84996828 2.69876618 5.32541102 1.0380137 3.0787769 2.2140083 -0.61998182 2.66514199 0.02348447 4.64797917 2.17249278 -9.27401088]testing the model...accuracy on test dataset: 0.9736842105263158recall on test dataset: 0.9534883720930233precision on test dataset: 0.9534883720930233
Note the accuracy, recall, and precision score of the model and epochs it took to complete. Now let’s try to improve it using feature selection.
Feature selection encompasses statistical techniques that help in filtering irrelevant or redundant features. Correlation & p-values are among these statistical techniques. Using them we will select a subset of relevant and important features from our original set of features
What is correlation? Correlation is a degree of linear dependence (or linear relationship) between two variables. Two features are said to be correlated if the values of one feature can be explained by some linear relationship of the second feature. The degree of this relationship is given by the correlation coefficient (or “r”). It ranges from -1.0 to +1.0. The closer r is to +1 or -1, the more closely the two variables are related.
Why do we remove one of the correlated features? There are multiple reasons but the simplest of them is that correlated features almost have the same effect on the dependent variable. Moreover, correlated features won’t improve our model and would most probably worsen it, therefore we are better off using only one of them. After all, fewer features result in improved learning speed and a simpler model (model with fewer features).
What are p-values? It’s too broad to cover in this blog. But, in the context of feature selection, p-values help us find the features which are most significant in explaining variation in the dependent variable (y).
A feature with a low p-value has more significance and a feature with a high p-value has less significance in explaining the variation. Usually, we set a Significance Level SL (threshold) and if a feature has a p-value above this level it is discarded. I will leave some links at the end of this blog for an in-depth study on p-values.
Why do we remove features with high p-values? Because they don’t tell much about the behavior of the dependent variable. So, why keep them and unnecessarily increase the complexity of our model when they are not helping us in predicting the result.
We have two functions named remove_correlated_features() remove_less_significant_features() for removing highly correlated features and less significant features (using p-values and backward elimination) respectively:
# >> FEATURE SELECTION << #def remove_correlated_features(X): corr_threshold = 0.9 corr = X.corr() drop_columns = np.full(corr.shape[0], False, dtype=bool) for i in range(corr.shape[0]): for j in range(i + 1, corr.shape[0]): if corr.iloc[i, j] >= corr_threshold: drop_columns[j] = True columns_dropped = X.columns[drop_columns] X.drop(columns_dropped, axis=1, inplace=True) return columns_droppeddef remove_less_significant_features(X, Y): sl = 0.05 regression_ols = None columns_dropped = np.array([]) for itr in range(0, len(X.columns)): regression_ols = sm.OLS(Y, X).fit() max_col = regression_ols.pvalues.idxmax() max_val = regression_ols.pvalues.max() if max_val > sl: X.drop(max_col, axis='columns', inplace=True) columns_dropped = np.append(columns_dropped, [max_col]) else: break regression_ols.summary() return columns_dropped
Let’s call these functions inside init() before we apply normalization:
# inside init()# filter featuresremove_correlated_features(X)remove_less_significant_features(X, Y)
Rerun the code and check the output:
# OUTPUT WITH FEATURE SELECTIONreading dataset...applying feature engineering...splitting dataset into train and test sets...training started...Epoch is: 1 and Cost is: 7198.889722245353Epoch is: 2 and Cost is: 6546.424590270085Epoch is: 4 and Cost is: 5448.724593530262Epoch is: 8 and Cost is: 3839.8660601754004Epoch is: 16 and Cost is: 2643.2493061396613Epoch is: 32 and Cost is: 2003.9830891013514Epoch is: 64 and Cost is: 1595.2499320295813Epoch is: 128 and Cost is: 1325.7502330505054Epoch is: 256 and Cost is: 1159.7928936478063Epoch is: 512 and Cost is: 1077.5846940303365Epoch is: 1024 and Cost is: 1047.208390340501Epoch is: 2048 and Cost is: 1040.2241600540974training finished.weights are: [ 3.53520254 11.03169318 -2.31444264 -7.89186867 10.14516174 -1.28905488 -6.4397589 2.26113987 -3.87318997 3.23075732 4.94607957 4.81819288 -4.72111236]testing the model...accuracy on test dataset: 0.9912280701754386recall on test dataset: 0.9767441860465116precision on test dataset: 0.9767441860465116
As you can see the accuracy (99%), precision (0.98), and recall (0.98) scores have improved. Moreover, SGD has converged faster; The training ended within 2048 epochs which is way less as compared to the previous one (5000 epochs)
You can get the complete code in this Github repository:
github.com
Useful Link
Why SGD works?
Benefits of SGD
P-values explained by a data scientist
Linear regression and p-values
|
[
{
"code": null,
"e": 453,
"s": 171,
"text": "1. SVM Introduction2. Reading the Dataset3. Feature Engineering4. Splitting the Dataset5. Cost Function6. The Gradient of the Cost Function7. Train Model Using SGD8. Stoppage Criterion for SGD9. Testing the Model10. Feature Selection With Correlation & P-values11. Give Me the Code"
},
{
"code": null,
"e": 1049,
"s": 453,
"text": "Before diving right into the code or technical details, I would like to mention that while there are many libraries/frameworks available to implement SVM (Support Vector Machine) algorithm without writing a bunch of code, I decided to write the code with as few high-level libraries as possible so that you and I can get a good grasp of important components involved in training an SVM model (with 99% accuracy, 0.98 recall, and precision). If you are looking for a quick implementation of SVM, then you are better off using packages like scikit-learn, cvxopt, etc. Otherwise, let’s get started!"
},
{
"code": null,
"e": 1334,
"s": 1049,
"text": "The SVM (Support Vector Machine) is a supervised machine learning algorithm typically used for binary classification problems. It’s trained by feeding a dataset with labeled examples (xi, yi). For instance, if your examples are email messages and your problem is spam detection, then:"
},
{
"code": null,
"e": 1452,
"s": 1334,
"text": "An example email message xi is defined as an n-dimensional feature vector that can be plotted on n-dimensional space."
},
{
"code": null,
"e": 1587,
"s": 1452,
"text": "The feature vector, as the name explains, contains features (eg. word count, link count, etc.) of your email message in numerical form"
},
{
"code": null,
"e": 1634,
"s": 1587,
"text": "Each feature vector is labeled with a class yi"
},
{
"code": null,
"e": 1700,
"s": 1634,
"text": "The class yi can either be a +ve or -ve (eg. spam=1, not-spam=-1)"
},
{
"code": null,
"e": 1827,
"s": 1700,
"text": "Using this dataset the algorithm finds a hyperplane (or decision boundary) which should ideally have the following properties:"
},
{
"code": null,
"e": 1903,
"s": 1827,
"text": "It creates separation between examples of two classes with a maximum margin"
},
{
"code": null,
"e": 2012,
"s": 1903,
"text": "Its equation (w.x + b = 0) yields a value ≥ 1 for examples from+ve class and ≤-1 for examples from -ve class"
},
{
"code": null,
"e": 2308,
"s": 2012,
"text": "How does it find this hyperplane? By finding the optimal values w* (weights/normal) and b* (intercept) which define this hyperplane. The optimal values are found by minimizing a cost function. Once the algorithm identifies these optimal values, the SVM model f(x) is then defined as shown below:"
},
{
"code": null,
"e": 2433,
"s": 2308,
"text": "Before we move any further let’s import the required packages for this tutorial and create a skeleton of our program svm.py:"
},
{
"code": null,
"e": 3057,
"s": 2433,
"text": "# svm.pyimport numpy as np # for handling multi-dimensional array operationimport pandas as pd # for reading data from csv import statsmodels.api as sm # for finding the p-valuefrom sklearn.preprocessing import MinMaxScaler # for normalizationfrom sklearn.model_selection import train_test_split as ttsfrom sklearn.metrics import accuracy_score from sklearn.utils import shuffle# >> FEATURE SELECTION << #def remove_correlated_features(X):def remove_less_significant_features(X, Y):# >> MODEL TRAINING << #def compute_cost(W, X, Y):def calculate_cost_gradient(W, X_batch, Y_batch):def sgd(features, outputs):def init():"
},
{
"code": null,
"e": 3448,
"s": 3057,
"text": "We’ll be working with a breast cancer dataset available on Kaggle. The features in the dataset are computed from a digitized image of a fine needle aspirate (FNA) of a breast mass. They describe the characteristics of the cell nuclei present in the image. Based on these features we will train our SVM model to detect if the mass is benign B (generally harmless) or malignant M (cancerous)."
},
{
"code": null,
"e": 3570,
"s": 3448,
"text": "Download the dataset and place the data.csv file in the same folder as svm.py. Then add this code inside init() function:"
},
{
"code": null,
"e": 4012,
"s": 3570,
"text": "def init(): data = pd.read_csv('./data.csv') # SVM only accepts numerical values. # Therefore, we will transform the categories M and B into # values 1 and -1 (or -1 and 1), respectively. diagnosis_map = {'M':1, 'B':-1} data['diagnosis'] = data['diagnosis'].map(diagnosis_map) # drop last column (extra column added by pd) # and unnecessary first column (id) data.drop(data.columns[[-1, 0]], axis=1, inplace=True)"
},
{
"code": null,
"e": 4297,
"s": 4012,
"text": "read_csv() function of the Pandas package reads data from the .csv file and stores it in a DataFrame. Think of DataFrame as an implementation of a data structure that looks like a table with labeled columns and rows. Here’s how the data read from data.csv looks like inside DataFrame:"
},
{
"code": null,
"e": 4409,
"s": 4297,
"text": "As you can see the labels and structure of our dataset are preserved and that’s what makes DataFrame intuitive."
},
{
"code": null,
"e": 4661,
"s": 4409,
"text": "Machine learning algorithms operate on a dataset that is a collection of labeled examples which consist of features and a label i.e. in our case diagnosis is a label, [radius_mean, structure_mean, texture_mean...] features, and each row is an example."
},
{
"code": null,
"e": 4996,
"s": 4661,
"text": "In most of the cases, the data you collect at first might be raw; its either incompatible with your model or hinders its performance. That’s when feature engineering comes to rescue. It encompasses preprocessing techniques to compile a dataset by extracting features from raw data. These techniques have two characteristics in common:"
},
{
"code": null,
"e": 5050,
"s": 4996,
"text": "Preparing the data which is compatible with the model"
},
{
"code": null,
"e": 5110,
"s": 5050,
"text": "Improving the performance of the machine learning algorithm"
},
{
"code": null,
"e": 5561,
"s": 5110,
"text": "Normalization is one of the many feature engineering techniques that we are going to use. Normalization is the process of converting a range of values, into a standard range of values, typically in the interval [−1, 1] or [0, 1]. It’s not a strict requirement but it improves the speed of learning (e.g. faster convergence in gradient descent) and prevents numerical overflow. Add following code in init() functions to normalize all of your features:"
},
{
"code": null,
"e": 5916,
"s": 5561,
"text": "# inside init()# put features & outputs in different DataFrames for convenienceY = data.loc[:, 'diagnosis'] # all rows of 'diagnosis' X = data.iloc[:, 1:] # all rows of column 1 and ahead (features)# normalize the features using MinMaxScalar from# sklearn.preprocessingX_normalized = MinMaxScaler().fit_transform(X.values)X = pd.DataFrame(X_normalized)"
},
{
"code": null,
"e": 6170,
"s": 5916,
"text": "We’ll split the dataset into train and test set using the train_test_split() function from sklearn.model_selection. We need a separate dataset for testing because we need to see how our model will perform on unseen observations. Add this code in init():"
},
{
"code": null,
"e": 6541,
"s": 6170,
"text": "# inside init()# first insert 1 in every row for intercept bX.insert(loc=len(X.columns), column='intercept', value=1)# test_size is the portion of data that will go into test set# random_state is the seed used by the random number generatorprint(\"splitting dataset into train and test sets...\")X_train, X_test, y_train, y_test = tts(X, Y, test_size=0.2, random_state=42)"
},
{
"code": null,
"e": 6658,
"s": 6541,
"text": "If you are confused about why we added 1 in every row then don’t worry. You will get the answer in the next section."
},
{
"code": null,
"e": 6835,
"s": 6658,
"text": "Also known as the Objective Function. One of the building blocks of every machine learning algorithm, it’s the function we try to minimize or maximize to achieve our objective."
},
{
"code": null,
"e": 7033,
"s": 6835,
"text": "What’s our objective in SVM? Our objective is to find a hyperplane that separates +ve and -ve examples with the largest margin while keeping the misclassification as low as possible (see Figure 3)."
},
{
"code": null,
"e": 7125,
"s": 7033,
"text": "How do we achieve this objective? We will minimize the cost/objective function shown below:"
},
{
"code": null,
"e": 7202,
"s": 7125,
"text": "You might have seen another version of a cost function that looks like this:"
},
{
"code": null,
"e": 7636,
"s": 7202,
"text": "In this cost function, λ is essentially equal to 1/C and has the opposite effect i.e larger λ gives a wider margin and vice versa. We can use any of the above cost functions keeping in mind what each regularization parameter (C and λ) does and then tuning them accordingly. Let’s see how can we calculate the total cost as given in (1) and then we will move on to its gradient which will be used in the training phase to minimize it:"
},
{
"code": null,
"e": 7949,
"s": 7636,
"text": "def compute_cost(W, X, Y): # calculate hinge loss N = X.shape[0] distances = 1 - Y * (np.dot(X, W)) distances[distances < 0] = 0 # equivalent to max(0, distance) hinge_loss = reg_strength * (np.sum(distances) / N) # calculate cost cost = 1 / 2 * np.dot(W, W) + hinge_loss return cost"
},
{
"code": null,
"e": 8080,
"s": 7949,
"text": "As you might have noticed that the intercept term b is missing. That’s because we have pushed it into the weight vector like this:"
},
{
"code": null,
"e": 8206,
"s": 8080,
"text": "That’s why we added an extra column with all 1s before splitting our dataset. Keep this in mind for the rest of the tutorial."
},
{
"code": null,
"e": 8425,
"s": 8206,
"text": "As you would have noticed there are some changes in cost function in equation (4). Don’t worry, if you solve it analytically it’s the same. Now let’s implement the calculate_cost_gradient() function using equation (5):"
},
{
"code": null,
"e": 9047,
"s": 8425,
"text": "# I haven't tested it but this same function should work for# vanilla and mini-batch gradient descent as welldef calculate_cost_gradient(W, X_batch, Y_batch): # if only one example is passed (eg. in case of SGD) if type(Y_batch) == np.float64: Y_batch = np.array([Y_batch]) X_batch = np.array([X_batch]) distance = 1 - (Y_batch * np.dot(X_batch, W)) dw = np.zeros(len(W)) for ind, d in enumerate(distance): if max(0, d) == 0: di = W else: di = W - (reg_strength * Y_batch[ind] * X_batch[ind]) dw += di dw = dw/len(Y_batch) # average return dw"
},
{
"code": null,
"e": 9200,
"s": 9047,
"text": "Remember I said above, “To achieve our objective we try to minimize or maximize the cost function”. In the SVM algorithm, we minimize the cost function."
},
{
"code": null,
"e": 9410,
"s": 9200,
"text": "Why do we minimize the cost function? Because the cost function is essentially a measure of how bad our model is doing at achieving the objective. If you look closely at J(w), to find it’s minimum, we have to:"
},
{
"code": null,
"e": 9525,
"s": 9410,
"text": "Minimize ∣∣w∣∣2 which maximizes margin (2/∣∣w∣∣)Minimize the sum of hinge loss which minimizes misclassifications."
},
{
"code": null,
"e": 9574,
"s": 9525,
"text": "Minimize ∣∣w∣∣2 which maximizes margin (2/∣∣w∣∣)"
},
{
"code": null,
"e": 9641,
"s": 9574,
"text": "Minimize the sum of hinge loss which minimizes misclassifications."
},
{
"code": null,
"e": 9749,
"s": 9641,
"text": "Because both of our SVM objectives are achieved by minimizing the cost function, that’s why we minimize it."
},
{
"code": null,
"e": 9966,
"s": 9749,
"text": "How do we minimize it? Well, there are multiple ways but the one we will use is called Stochastic Gradient Descent or SGD. Before diving into SGD, I will briefly explain how Gradient Descent works in the first place."
},
{
"code": null,
"e": 10011,
"s": 9966,
"text": "Gradient descent algorithm works as follows:"
},
{
"code": null,
"e": 10202,
"s": 10011,
"text": "Find the gradient of cost function i.e. ∇J(w’)Move opposite to the gradient by a certain rate i.e. w’ = w’ — ∝(∇J(w’))Repeat step 1–3 until convergence i.e we found w’ where J(w) is smallest"
},
{
"code": null,
"e": 10249,
"s": 10202,
"text": "Find the gradient of cost function i.e. ∇J(w’)"
},
{
"code": null,
"e": 10322,
"s": 10249,
"text": "Move opposite to the gradient by a certain rate i.e. w’ = w’ — ∝(∇J(w’))"
},
{
"code": null,
"e": 10395,
"s": 10322,
"text": "Repeat step 1–3 until convergence i.e we found w’ where J(w) is smallest"
},
{
"code": null,
"e": 10659,
"s": 10395,
"text": "Why does it move opposite to the direction of the gradient? Because gradient is the direction of the fastest increase of the function. We need to move opposite to that direction to minimize our function J(w). Hence, the word “descent” in Gradient Descent is used."
},
{
"code": null,
"e": 10976,
"s": 10659,
"text": "In typical gradient descent (a.k.a vanilla gradient descent) the step 1 above is calculated using all the examples (1...N). In SGD, however, only 1 example is used at a time. I won’t discuss the benefits of SGD here but you can find some useful links at the end of this blog. Here’s how to implement the SGD in code:"
},
{
"code": null,
"e": 11416,
"s": 10976,
"text": "def sgd(features, outputs): max_epochs = 5000 weights = np.zeros(features.shape[1]) # stochastic gradient descent for epoch in range(1, max_epochs): # shuffle to prevent repeating update cycles X, Y = shuffle(features, outputs) for ind, x in enumerate(X): ascent = calculate_cost_gradient(weights, x, Y[ind]) weights = weights - (learning_rate * ascent) return weights"
},
{
"code": null,
"e": 11474,
"s": 11416,
"text": "Let’s call it inside init() function by adding this code:"
},
{
"code": null,
"e": 11643,
"s": 11474,
"text": "# inside init()# train the modelprint(\"training started...\")W = sgd(X_train.to_numpy(), y_train.to_numpy())print(\"training finished.\")print(\"weights are: {}\".format(W))"
},
{
"code": null,
"e": 11906,
"s": 11643,
"text": "In the above implementation of sgd() we are running the loop 5000 times (could have been any number). Each iteration costs us time and extra computations. We don’t need to complete all the iterations. We can terminate the loop when our stoppage criterion is met."
},
{
"code": null,
"e": 12169,
"s": 11906,
"text": "What should be the stoppage criterion? There are multiple options, but we will use the simplest one. We will stop the training when the current cost hasn’t decreased much as compared to the previous cost. Here is how we will define sgd() with stoppage criterion:"
},
{
"code": null,
"e": 13075,
"s": 12169,
"text": "def sgd(features, outputs): max_epochs = 5000 weights = np.zeros(features.shape[1]) nth = 0 prev_cost = float(\"inf\") cost_threshold = 0.01 # in percent # stochastic gradient descent for epoch in range(1, max_epochs): # shuffle to prevent repeating update cycles X, Y = shuffle(features, outputs) for ind, x in enumerate(X): ascent = calculate_cost_gradient(weights, x, Y[ind]) weights = weights - (learning_rate * ascent) # convergence check on 2^nth epoch if epoch == 2 ** nth or epoch == max_epochs - 1: cost = compute_cost(weights, features, outputs) print(\"Epoch is:{} and Cost is: {}\".format(epoch, cost)) # stoppage criterion if abs(prev_cost - cost) < cost_threshold * prev_cost: return weights prev_cost = cost nth += 1 return weights"
},
{
"code": null,
"e": 13293,
"s": 13075,
"text": "After training the model using SGD we finally got the optimal weights w* which defines the best possible hyperplane separating two classes. Let’s test our model using this hyperplane. Add this code in init() function:"
},
{
"code": null,
"e": 13799,
"s": 13293,
"text": "# inside init()# testing the model on test sety_test_predicted = np.array([])for i in range(X_test.shape[0]): yp = np.sign(np.dot(W, X_test.to_numpy()[i])) #model y_test_predicted = np.append(y_test_predicted, yp)print(\"accuracy on test dataset: {}\".format(accuracy_score(y_test.to_numpy(), y_test_predicted)))print(\"recall on test dataset: {}\".format(recall_score(y_test.to_numpy(), y_test_predicted)))print(\"precision on test dataset: {}\".format(recall_score(y_test.to_numpy(), y_test_predicted)))"
},
{
"code": null,
"e": 13831,
"s": 13799,
"text": "Now let’s call init() function:"
},
{
"code": null,
"e": 14036,
"s": 13831,
"text": "# set hyper-parameters and call init# hyper-parameters are normally tuned using cross-validation# but following work good enoughreg_strength = 10000 # regularization strengthlearning_rate = 0.000001init()"
},
{
"code": null,
"e": 14055,
"s": 14036,
"text": "Here’s the output:"
},
{
"code": null,
"e": 15343,
"s": 14055,
"text": "# OUTPUTreading dataset...applying feature engineering...splitting dataset into train and test sets...training started...Epoch is: 1 and Cost is: 5333.266133501857Epoch is: 2 and Cost is: 3421.9128432834573Epoch is: 4 and Cost is: 2437.2790231100216Epoch is: 8 and Cost is: 1880.2998267933792Epoch is: 16 and Cost is: 1519.5578612139725Epoch is: 32 and Cost is: 1234.642324549297Epoch is: 64 and Cost is: 977.3285621274708Epoch is: 128 and Cost is: 804.8893546235923Epoch is: 256 and Cost is: 703.407799431284Epoch is: 512 and Cost is: 645.8275191300031Epoch is: 1024 and Cost is: 631.6024252740094Epoch is: 2048 and Cost is: 615.8378582171482Epoch is: 4096 and Cost is: 605.0990964730645Epoch is: 4999 and Cost is: 606.8186618758745training finished.weights are: [ 1.32516553 0.83500639 1.12489803 2.16072054 -1.24845441 -3.24246498 3.27876342 6.83028706 -0.46562238 0.10063844 5.68881254 -1.93421932 3.27394523 3.77331751 1.67333278 -2.43170464 -1.7683188 0.84065607 -1.9612766 -1.84996828 2.69876618 5.32541102 1.0380137 3.0787769 2.2140083 -0.61998182 2.66514199 0.02348447 4.64797917 2.17249278 -9.27401088]testing the model...accuracy on test dataset: 0.9736842105263158recall on test dataset: 0.9534883720930233precision on test dataset: 0.9534883720930233"
},
{
"code": null,
"e": 15488,
"s": 15343,
"text": "Note the accuracy, recall, and precision score of the model and epochs it took to complete. Now let’s try to improve it using feature selection."
},
{
"code": null,
"e": 15765,
"s": 15488,
"text": "Feature selection encompasses statistical techniques that help in filtering irrelevant or redundant features. Correlation & p-values are among these statistical techniques. Using them we will select a subset of relevant and important features from our original set of features"
},
{
"code": null,
"e": 16203,
"s": 15765,
"text": "What is correlation? Correlation is a degree of linear dependence (or linear relationship) between two variables. Two features are said to be correlated if the values of one feature can be explained by some linear relationship of the second feature. The degree of this relationship is given by the correlation coefficient (or “r”). It ranges from -1.0 to +1.0. The closer r is to +1 or -1, the more closely the two variables are related."
},
{
"code": null,
"e": 16637,
"s": 16203,
"text": "Why do we remove one of the correlated features? There are multiple reasons but the simplest of them is that correlated features almost have the same effect on the dependent variable. Moreover, correlated features won’t improve our model and would most probably worsen it, therefore we are better off using only one of them. After all, fewer features result in improved learning speed and a simpler model (model with fewer features)."
},
{
"code": null,
"e": 16853,
"s": 16637,
"text": "What are p-values? It’s too broad to cover in this blog. But, in the context of feature selection, p-values help us find the features which are most significant in explaining variation in the dependent variable (y)."
},
{
"code": null,
"e": 17189,
"s": 16853,
"text": "A feature with a low p-value has more significance and a feature with a high p-value has less significance in explaining the variation. Usually, we set a Significance Level SL (threshold) and if a feature has a p-value above this level it is discarded. I will leave some links at the end of this blog for an in-depth study on p-values."
},
{
"code": null,
"e": 17438,
"s": 17189,
"text": "Why do we remove features with high p-values? Because they don’t tell much about the behavior of the dependent variable. So, why keep them and unnecessarily increase the complexity of our model when they are not helping us in predicting the result."
},
{
"code": null,
"e": 17656,
"s": 17438,
"text": "We have two functions named remove_correlated_features() remove_less_significant_features() for removing highly correlated features and less significant features (using p-values and backward elimination) respectively:"
},
{
"code": null,
"e": 18632,
"s": 17656,
"text": "# >> FEATURE SELECTION << #def remove_correlated_features(X): corr_threshold = 0.9 corr = X.corr() drop_columns = np.full(corr.shape[0], False, dtype=bool) for i in range(corr.shape[0]): for j in range(i + 1, corr.shape[0]): if corr.iloc[i, j] >= corr_threshold: drop_columns[j] = True columns_dropped = X.columns[drop_columns] X.drop(columns_dropped, axis=1, inplace=True) return columns_droppeddef remove_less_significant_features(X, Y): sl = 0.05 regression_ols = None columns_dropped = np.array([]) for itr in range(0, len(X.columns)): regression_ols = sm.OLS(Y, X).fit() max_col = regression_ols.pvalues.idxmax() max_val = regression_ols.pvalues.max() if max_val > sl: X.drop(max_col, axis='columns', inplace=True) columns_dropped = np.append(columns_dropped, [max_col]) else: break regression_ols.summary() return columns_dropped"
},
{
"code": null,
"e": 18704,
"s": 18632,
"text": "Let’s call these functions inside init() before we apply normalization:"
},
{
"code": null,
"e": 18804,
"s": 18704,
"text": "# inside init()# filter featuresremove_correlated_features(X)remove_less_significant_features(X, Y)"
},
{
"code": null,
"e": 18841,
"s": 18804,
"text": "Rerun the code and check the output:"
},
{
"code": null,
"e": 19852,
"s": 18841,
"text": "# OUTPUT WITH FEATURE SELECTIONreading dataset...applying feature engineering...splitting dataset into train and test sets...training started...Epoch is: 1 and Cost is: 7198.889722245353Epoch is: 2 and Cost is: 6546.424590270085Epoch is: 4 and Cost is: 5448.724593530262Epoch is: 8 and Cost is: 3839.8660601754004Epoch is: 16 and Cost is: 2643.2493061396613Epoch is: 32 and Cost is: 2003.9830891013514Epoch is: 64 and Cost is: 1595.2499320295813Epoch is: 128 and Cost is: 1325.7502330505054Epoch is: 256 and Cost is: 1159.7928936478063Epoch is: 512 and Cost is: 1077.5846940303365Epoch is: 1024 and Cost is: 1047.208390340501Epoch is: 2048 and Cost is: 1040.2241600540974training finished.weights are: [ 3.53520254 11.03169318 -2.31444264 -7.89186867 10.14516174 -1.28905488 -6.4397589 2.26113987 -3.87318997 3.23075732 4.94607957 4.81819288 -4.72111236]testing the model...accuracy on test dataset: 0.9912280701754386recall on test dataset: 0.9767441860465116precision on test dataset: 0.9767441860465116"
},
{
"code": null,
"e": 20083,
"s": 19852,
"text": "As you can see the accuracy (99%), precision (0.98), and recall (0.98) scores have improved. Moreover, SGD has converged faster; The training ended within 2048 epochs which is way less as compared to the previous one (5000 epochs)"
},
{
"code": null,
"e": 20140,
"s": 20083,
"text": "You can get the complete code in this Github repository:"
},
{
"code": null,
"e": 20151,
"s": 20140,
"text": "github.com"
},
{
"code": null,
"e": 20163,
"s": 20151,
"text": "Useful Link"
},
{
"code": null,
"e": 20178,
"s": 20163,
"text": "Why SGD works?"
},
{
"code": null,
"e": 20194,
"s": 20178,
"text": "Benefits of SGD"
},
{
"code": null,
"e": 20233,
"s": 20194,
"text": "P-values explained by a data scientist"
}
] |
N-Gram Language Modelling with NLTK - GeeksforGeeks
|
31 Mar, 2022
Language modeling is the way of determining the probability of any sequence of words. Language modeling is used in a wide variety of applications such as Speech Recognition, Spam filtering, etc. In fact, language modeling is the key aim behind the implementation of many state-of-the-art Natural Language Processing models.
Methods of Language Modelings:
Two types of Language Modelings:
Statistical Language Modelings: Statistical Language Modeling, or Language Modeling, is the development of probabilistic models that are able to predict the next word in the sequence given the words that precede. Examples such as N-gram language modeling.
Neural Language Modelings: Neural network methods are achieving better results than classical methods both on standalone language models and when models are incorporated into larger models on challenging tasks like speech recognition and machine translation. A way of performing a neural language model is through word embeddings.
N-gram
N-gram can be defined as the contiguous sequence of n items from a given sample of text or speech. The items can be letters, words, or base pairs according to the application. The N-grams typically are collected from a text or speech corpus (A long text dataset).
N-gram Language Model:
An N-gram language model predicts the probability of a given N-gram within any sequence of words in the language. A good N-gram model can predict the next word in the sentence i.e the value of p(w|h)
Example of N-gram such as unigram (“This”, “article”, “is”, “on”, “NLP”) or bi-gram (‘This article’, ‘article is’, ‘is on’,’on NLP’).
Now, we will establish a relation on how to find the next word in the sentence using
. We need to calculate p(w|h), where is the candidate for the next word. For example in the above example, lets’ consider, we want to calculate what is the probability of the last word being “NLP” given the previous words:
After generalizing the above equation can be calculated as:
But how do we calculate it? The answer lies in the chain rule of probability:
Now generalize the above equation:
Simplifying the above formula using Markov assumptions:
For unigram:
For Bigram:
Python3
# importsimport stringimport randomimport nltknltk.download('punkt')nltk.download('stopwords')nltk.download('reuters')from nltk.corpus import reutersfrom nltk import FreqDist # input the reuters sentencessents =reuters.sents() # write the removal characters such as : Stopwords and punctuationstop_words = set(stopwords.words('english'))string.punctuation = string.punctuation +'"'+'"'+'-'+'''+'''+'—'string.punctuationremoval_list = list(stop_words) + list(string.punctuation)+ ['lt','rt']removal_list # generate unigrams bigrams trigramsunigram=[]bigram=[]trigram=[]tokenized_text=[]for sentence in sents: sentence = list(map(lambda x:x.lower(),sentence)) for word in sentence: if word== '.': sentence.remove(word) else: unigram.append(word) tokenized_text.append(sentence) bigram.extend(list(ngrams(sentence, 2,pad_left=True, pad_right=True))) trigram.extend(list(ngrams(sentence, 3, pad_left=True, pad_right=True))) # remove the n-grams with removable wordsdef remove_stopwords(x): y = [] for pair in x: count = 0 for word in pair: if word in removal_list: count = count or 0 else: count = count or 1 if (count==1): y.append(pair) return (y)unigram = remove_stopwords(unigram)bigram = remove_stopwords(bigram)trigram = remove_stopwords(trigram) # generate frequency of n-gramsfreq_bi = FreqDist(bigram)freq_tri = FreqDist(trigram) d = defaultdict(Counter)for a, b, c in freq_tri: if(a != None and b!= None and c!= None): d[a, b] += freq_tri[a, b, c] # Next word prediction s=''def pick_word(counter): "Chooses a random element." return random.choice(list(counter.elements()))prefix = "he", "said"print(" ".join(prefix))s = " ".join(prefix)for i in range(19): suffix = pick_word(d[prefix]) s=s+' '+suffix print(s) prefix = prefix[1], suffix
he said
he said kotc
he said kotc made
he said kotc made profits
he said kotc made profits of
he said kotc made profits of 265
he said kotc made profits of 265 ,
he said kotc made profits of 265 , 457
he said kotc made profits of 265 , 457 vs
he said kotc made profits of 265 , 457 vs loss
he said kotc made profits of 265 , 457 vs loss eight
he said kotc made profits of 265 , 457 vs loss eight cts
he said kotc made profits of 265 , 457 vs loss eight cts net
he said kotc made profits of 265 , 457 vs loss eight cts net loss
he said kotc made profits of 265 , 457 vs loss eight cts net loss 343
he said kotc made profits of 265 , 457 vs loss eight cts net loss 343 ,
he said kotc made profits of 265 , 457 vs loss eight cts net loss 343 , 266
he said kotc made profits of 265 , 457 vs loss eight cts net loss 343 , 266 ,
he said kotc made profits of 265 , 457 vs loss eight cts net loss 343 , 266 , 000
he said kotc made profits of 265 , 457 vs loss eight cts net loss 343 , 266 , 000 shares
Entropy: Entropy, as a measure of the amount of information conveyed by Claude Shannon. Below is the formula for representing entropy
H(p) is always greater than equal to 0.
Cross-Entropy: It measures the ability of the trained model to represent test data().
The cross-entropy is always greater than or equal to Entropy i.e the model uncertainty can be no less than the true uncertainty.
Perplexity: Perplexity is a measure of how good a probability distribution predicts a sample. It can be understood as a measure of uncertainty. The perplexity can be calculated by cross-entropy to the exponent of 2.
Following is the formula for the calculation of Probability of the test set assigned by the language model, normalized by the number of words:
For Example:
Let’s take an example of the sentence: ‘Natural Language Processing’. For predicting the first word, let’s say the word has the following probabilities:
Now, we know the probability of getting the first word as natural. But, what’s the probability of getting the next word after getting the word ‘Language‘ after the word ‘Natural‘.
After getting the probability of generating words ‘Natural Language’, what’s the probability of getting ‘Processing‘.
Now, the perplexity can be calculated as:
From that we can also calculate entropy:
*** QuickLaTeX cannot compile formula:
*** Error message:
Error: Nothing to show, formula is empty
To get a better context of the text, we need higher values of n, but this will also increase computational overhead.
The increasing value of n in n-gram can also lead to sparsity.
N-gram Language modeling Stanford Slides
kashishsoda
simranarora5sos
Natural-language-processing
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Informed and Uninformed Search in AI
Deploy Machine Learning Model using Flask
Support Vector Machine Algorithm
Types of Environments in AI
k-nearest neighbor algorithm in Python
Principal Component Analysis with Python
Python | Decision Tree Regression using sklearn
Python | Stemming words with NLTK
Normalization vs Standardization
Intuition of Adam Optimizer
|
[
{
"code": null,
"e": 23953,
"s": 23925,
"text": "\n31 Mar, 2022"
},
{
"code": null,
"e": 24277,
"s": 23953,
"text": "Language modeling is the way of determining the probability of any sequence of words. Language modeling is used in a wide variety of applications such as Speech Recognition, Spam filtering, etc. In fact, language modeling is the key aim behind the implementation of many state-of-the-art Natural Language Processing models."
},
{
"code": null,
"e": 24308,
"s": 24277,
"text": "Methods of Language Modelings:"
},
{
"code": null,
"e": 24341,
"s": 24308,
"text": "Two types of Language Modelings:"
},
{
"code": null,
"e": 24597,
"s": 24341,
"text": "Statistical Language Modelings: Statistical Language Modeling, or Language Modeling, is the development of probabilistic models that are able to predict the next word in the sequence given the words that precede. Examples such as N-gram language modeling."
},
{
"code": null,
"e": 24928,
"s": 24597,
"text": "Neural Language Modelings: Neural network methods are achieving better results than classical methods both on standalone language models and when models are incorporated into larger models on challenging tasks like speech recognition and machine translation. A way of performing a neural language model is through word embeddings."
},
{
"code": null,
"e": 24935,
"s": 24928,
"text": "N-gram"
},
{
"code": null,
"e": 25199,
"s": 24935,
"text": "N-gram can be defined as the contiguous sequence of n items from a given sample of text or speech. The items can be letters, words, or base pairs according to the application. The N-grams typically are collected from a text or speech corpus (A long text dataset)."
},
{
"code": null,
"e": 25222,
"s": 25199,
"text": "N-gram Language Model:"
},
{
"code": null,
"e": 25422,
"s": 25222,
"text": "An N-gram language model predicts the probability of a given N-gram within any sequence of words in the language. A good N-gram model can predict the next word in the sentence i.e the value of p(w|h)"
},
{
"code": null,
"e": 25557,
"s": 25422,
"text": "Example of N-gram such as unigram (“This”, “article”, “is”, “on”, “NLP”) or bi-gram (‘This article’, ‘article is’, ‘is on’,’on NLP’)."
},
{
"code": null,
"e": 25643,
"s": 25557,
"text": "Now, we will establish a relation on how to find the next word in the sentence using "
},
{
"code": null,
"e": 25866,
"s": 25643,
"text": ". We need to calculate p(w|h), where is the candidate for the next word. For example in the above example, lets’ consider, we want to calculate what is the probability of the last word being “NLP” given the previous words:"
},
{
"code": null,
"e": 25926,
"s": 25866,
"text": "After generalizing the above equation can be calculated as:"
},
{
"code": null,
"e": 26004,
"s": 25926,
"text": "But how do we calculate it? The answer lies in the chain rule of probability:"
},
{
"code": null,
"e": 26039,
"s": 26004,
"text": "Now generalize the above equation:"
},
{
"code": null,
"e": 26095,
"s": 26039,
"text": "Simplifying the above formula using Markov assumptions:"
},
{
"code": null,
"e": 26108,
"s": 26095,
"text": "For unigram:"
},
{
"code": null,
"e": 26120,
"s": 26108,
"text": "For Bigram:"
},
{
"code": null,
"e": 26128,
"s": 26120,
"text": "Python3"
},
{
"code": "# importsimport stringimport randomimport nltknltk.download('punkt')nltk.download('stopwords')nltk.download('reuters')from nltk.corpus import reutersfrom nltk import FreqDist # input the reuters sentencessents =reuters.sents() # write the removal characters such as : Stopwords and punctuationstop_words = set(stopwords.words('english'))string.punctuation = string.punctuation +'\"'+'\"'+'-'+'''+'''+'—'string.punctuationremoval_list = list(stop_words) + list(string.punctuation)+ ['lt','rt']removal_list # generate unigrams bigrams trigramsunigram=[]bigram=[]trigram=[]tokenized_text=[]for sentence in sents: sentence = list(map(lambda x:x.lower(),sentence)) for word in sentence: if word== '.': sentence.remove(word) else: unigram.append(word) tokenized_text.append(sentence) bigram.extend(list(ngrams(sentence, 2,pad_left=True, pad_right=True))) trigram.extend(list(ngrams(sentence, 3, pad_left=True, pad_right=True))) # remove the n-grams with removable wordsdef remove_stopwords(x): y = [] for pair in x: count = 0 for word in pair: if word in removal_list: count = count or 0 else: count = count or 1 if (count==1): y.append(pair) return (y)unigram = remove_stopwords(unigram)bigram = remove_stopwords(bigram)trigram = remove_stopwords(trigram) # generate frequency of n-gramsfreq_bi = FreqDist(bigram)freq_tri = FreqDist(trigram) d = defaultdict(Counter)for a, b, c in freq_tri: if(a != None and b!= None and c!= None): d[a, b] += freq_tri[a, b, c] # Next word prediction s=''def pick_word(counter): \"Chooses a random element.\" return random.choice(list(counter.elements()))prefix = \"he\", \"said\"print(\" \".join(prefix))s = \" \".join(prefix)for i in range(19): suffix = pick_word(d[prefix]) s=s+' '+suffix print(s) prefix = prefix[1], suffix",
"e": 28051,
"s": 26128,
"text": null
},
{
"code": null,
"e": 29045,
"s": 28051,
"text": "he said\nhe said kotc\nhe said kotc made\nhe said kotc made profits\nhe said kotc made profits of\nhe said kotc made profits of 265\nhe said kotc made profits of 265 ,\nhe said kotc made profits of 265 , 457\nhe said kotc made profits of 265 , 457 vs\nhe said kotc made profits of 265 , 457 vs loss\nhe said kotc made profits of 265 , 457 vs loss eight\nhe said kotc made profits of 265 , 457 vs loss eight cts\nhe said kotc made profits of 265 , 457 vs loss eight cts net\nhe said kotc made profits of 265 , 457 vs loss eight cts net loss\nhe said kotc made profits of 265 , 457 vs loss eight cts net loss 343\nhe said kotc made profits of 265 , 457 vs loss eight cts net loss 343 ,\nhe said kotc made profits of 265 , 457 vs loss eight cts net loss 343 , 266\nhe said kotc made profits of 265 , 457 vs loss eight cts net loss 343 , 266 ,\nhe said kotc made profits of 265 , 457 vs loss eight cts net loss 343 , 266 , 000\nhe said kotc made profits of 265 , 457 vs loss eight cts net loss 343 , 266 , 000 shares"
},
{
"code": null,
"e": 29179,
"s": 29045,
"text": "Entropy: Entropy, as a measure of the amount of information conveyed by Claude Shannon. Below is the formula for representing entropy"
},
{
"code": null,
"e": 29219,
"s": 29179,
"text": "H(p) is always greater than equal to 0."
},
{
"code": null,
"e": 29306,
"s": 29219,
"text": "Cross-Entropy: It measures the ability of the trained model to represent test data(). "
},
{
"code": null,
"e": 29435,
"s": 29306,
"text": "The cross-entropy is always greater than or equal to Entropy i.e the model uncertainty can be no less than the true uncertainty."
},
{
"code": null,
"e": 29652,
"s": 29435,
"text": "Perplexity: Perplexity is a measure of how good a probability distribution predicts a sample. It can be understood as a measure of uncertainty. The perplexity can be calculated by cross-entropy to the exponent of 2. "
},
{
"code": null,
"e": 29795,
"s": 29652,
"text": "Following is the formula for the calculation of Probability of the test set assigned by the language model, normalized by the number of words:"
},
{
"code": null,
"e": 29808,
"s": 29795,
"text": "For Example:"
},
{
"code": null,
"e": 29961,
"s": 29808,
"text": "Let’s take an example of the sentence: ‘Natural Language Processing’. For predicting the first word, let’s say the word has the following probabilities:"
},
{
"code": null,
"e": 30141,
"s": 29961,
"text": "Now, we know the probability of getting the first word as natural. But, what’s the probability of getting the next word after getting the word ‘Language‘ after the word ‘Natural‘."
},
{
"code": null,
"e": 30259,
"s": 30141,
"text": "After getting the probability of generating words ‘Natural Language’, what’s the probability of getting ‘Processing‘."
},
{
"code": null,
"e": 30301,
"s": 30259,
"text": "Now, the perplexity can be calculated as:"
},
{
"code": null,
"e": 30342,
"s": 30301,
"text": "From that we can also calculate entropy:"
},
{
"code": null,
"e": 30445,
"s": 30342,
"text": "*** QuickLaTeX cannot compile formula:\n \n\n*** Error message:\nError: Nothing to show, formula is empty\n"
},
{
"code": null,
"e": 30562,
"s": 30445,
"text": "To get a better context of the text, we need higher values of n, but this will also increase computational overhead."
},
{
"code": null,
"e": 30625,
"s": 30562,
"text": "The increasing value of n in n-gram can also lead to sparsity."
},
{
"code": null,
"e": 30666,
"s": 30625,
"text": "N-gram Language modeling Stanford Slides"
},
{
"code": null,
"e": 30678,
"s": 30666,
"text": "kashishsoda"
},
{
"code": null,
"e": 30694,
"s": 30678,
"text": "simranarora5sos"
},
{
"code": null,
"e": 30722,
"s": 30694,
"text": "Natural-language-processing"
},
{
"code": null,
"e": 30739,
"s": 30722,
"text": "Machine Learning"
},
{
"code": null,
"e": 30756,
"s": 30739,
"text": "Machine Learning"
},
{
"code": null,
"e": 30854,
"s": 30756,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30863,
"s": 30854,
"text": "Comments"
},
{
"code": null,
"e": 30876,
"s": 30863,
"text": "Old Comments"
},
{
"code": null,
"e": 30932,
"s": 30876,
"text": "Difference between Informed and Uninformed Search in AI"
},
{
"code": null,
"e": 30974,
"s": 30932,
"text": "Deploy Machine Learning Model using Flask"
},
{
"code": null,
"e": 31007,
"s": 30974,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 31035,
"s": 31007,
"text": "Types of Environments in AI"
},
{
"code": null,
"e": 31074,
"s": 31035,
"text": "k-nearest neighbor algorithm in Python"
},
{
"code": null,
"e": 31115,
"s": 31074,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 31163,
"s": 31115,
"text": "Python | Decision Tree Regression using sklearn"
},
{
"code": null,
"e": 31197,
"s": 31163,
"text": "Python | Stemming words with NLTK"
},
{
"code": null,
"e": 31230,
"s": 31197,
"text": "Normalization vs Standardization"
}
] |
Explain the stack by using linked list in C language
|
Stack over flow and stack under flow can be avoided by allocating memory dynamically.
Operations carried out under stack in C programming language are as follows −
Push
Pop
Following is the basic implementation of a linked list −
&item = 10
newnode = (node*) malloc (sizeof (node));
newnode ->data = item;
newnode ->link = NULL;
newnode ->link = start;
start = newnode;
The syntax is as follows −
if (start = = NULL)
printf("Deletion is not possible.List is empty")
else{
temp = start;
start = start link;
free (temp);
}
Following is the C program for stack by using linked lists −
#include <stdio.h>
#include <stdlib.h>
struct node{
int info;
struct node *ptr;
}*top,*top1,*temp;
int topelement();
void push(int data);
void pop();
void empty();
void display();
void destroy();
void stack_count();
void create();
int count = 0;
void main(){
int no, ch, e;
printf("\n 1 - Push");
printf("\n 2 - Pop");
printf("\n 3 - Top");
printf("\n 4 - Empty");
printf("\n 5 - Exit");
printf("\n 6 - Display");
printf("\n 7 - Stack Count");
printf("\n 8 - Destroy stack");
create();
while (1){
printf("\n Enter choice : ");
scanf("%d", &ch);
switch (ch){
case 1:
printf("Enter element : ");
scanf("%d", &no);
push(no);
break;
case 2:
pop();
break;
case 3:
if (top == NULL)
printf("stack is empty");
else{
e = topelement();
printf("\n Top element : %d", e);
}
break;
case 4:
empty();
break;
case 5:
exit(0);
case 6:
display();
break;
case 7:
stack_count();
break;
case 8:
destroy();
break;
default :
printf(" wrong choice:Try again ");
break;
}
}
}
//empty stack
void create(){
top = NULL;
}
void stack_count(){
printf("\n no: of elements in stack : %d", count);
}
//push data
void push(int data){
if (top == NULL){
top =(struct node *)malloc(1*sizeof(struct node));
top->ptr = NULL;
top->info = data;
}
else{
temp =(struct node *)malloc(1*sizeof(struct node));
temp->ptr = top;
temp->info = data;
top = temp;
}
count++;
}
void display(){
top1 = top;
if (top1 == NULL){
printf("empty stack");
return;
}
while (top1 != NULL){
printf("%d ", top1->info);
top1 = top1->ptr;
}
}
void pop(){
top1 = top;
if (top1 == NULL){
printf("\n error");
return;
}
else
top1 = top1->ptr;
printf("\n Popped value : %d", top->info);
free(top);
top = top1;
count--;
}
int topelement(){
return(top->info);
}
//check stack empty or not
void empty(){
if (top == NULL)
printf("\n empty stack");
else
printf("\n stack not empty with %d values", count);
}
void destroy(){
top1 = top;
while (top1 != NULL){
top1 = top->ptr;
free(top);
top = top1;
top1 = top1->ptr;
}
free(top1);
top = NULL;
printf("\n all are destroyed");
count = 0;
}
When the above program is executed, it produces the following result −
1 - Push
2 - Pop
3 - Top
4 - Empty
5 - Exit
6 - Display
7 - Stack Count
8 - Destroy stack
Enter choice: 1
Enter element: 23
Enter choice: 1
Enter element: 45
Enter choice: 1
Enter element: 56
Enter choice: 2
Popped value: 56
Enter choice: 6
45 23
Enter choice: 8
all are destroyed
Enter choice: 6
empty stack
Enter choice: 5
|
[
{
"code": null,
"e": 1148,
"s": 1062,
"text": "Stack over flow and stack under flow can be avoided by allocating memory dynamically."
},
{
"code": null,
"e": 1226,
"s": 1148,
"text": "Operations carried out under stack in C programming language are as follows −"
},
{
"code": null,
"e": 1231,
"s": 1226,
"text": "Push"
},
{
"code": null,
"e": 1235,
"s": 1231,
"text": "Pop"
},
{
"code": null,
"e": 1292,
"s": 1235,
"text": "Following is the basic implementation of a linked list −"
},
{
"code": null,
"e": 1432,
"s": 1292,
"text": "&item = 10\nnewnode = (node*) malloc (sizeof (node));\nnewnode ->data = item;\nnewnode ->link = NULL;\nnewnode ->link = start;\nstart = newnode;"
},
{
"code": null,
"e": 1459,
"s": 1432,
"text": "The syntax is as follows −"
},
{
"code": null,
"e": 1592,
"s": 1459,
"text": "if (start = = NULL)\nprintf(\"Deletion is not possible.List is empty\")\nelse{\n temp = start;\n start = start link;\n free (temp);\n}"
},
{
"code": null,
"e": 1653,
"s": 1592,
"text": "Following is the C program for stack by using linked lists −"
},
{
"code": null,
"e": 4344,
"s": 1653,
"text": "#include <stdio.h>\n#include <stdlib.h>\nstruct node{\n int info;\n struct node *ptr;\n}*top,*top1,*temp;\nint topelement();\nvoid push(int data);\nvoid pop();\nvoid empty();\nvoid display();\nvoid destroy();\nvoid stack_count();\nvoid create();\nint count = 0;\nvoid main(){\n int no, ch, e;\n printf(\"\\n 1 - Push\");\n printf(\"\\n 2 - Pop\");\n printf(\"\\n 3 - Top\");\n printf(\"\\n 4 - Empty\");\n printf(\"\\n 5 - Exit\");\n printf(\"\\n 6 - Display\");\n printf(\"\\n 7 - Stack Count\");\n printf(\"\\n 8 - Destroy stack\");\n create();\n while (1){\n printf(\"\\n Enter choice : \");\n scanf(\"%d\", &ch);\n switch (ch){\n case 1:\n printf(\"Enter element : \");\n scanf(\"%d\", &no);\n push(no);\n break;\n case 2:\n pop();\n break;\n case 3:\n if (top == NULL)\n printf(\"stack is empty\");\n else{\n e = topelement();\n printf(\"\\n Top element : %d\", e);\n }\n break;\n case 4:\n empty();\n break;\n case 5:\n exit(0);\n case 6:\n display();\n break;\n case 7:\n stack_count();\n break;\n case 8:\n destroy();\n break;\n default :\n printf(\" wrong choice:Try again \");\n break;\n }\n }\n}\n//empty stack\nvoid create(){\n top = NULL;\n}\nvoid stack_count(){\n printf(\"\\n no: of elements in stack : %d\", count);\n}\n//push data\nvoid push(int data){\n if (top == NULL){\n top =(struct node *)malloc(1*sizeof(struct node));\n top->ptr = NULL;\n top->info = data;\n }\n else{\n temp =(struct node *)malloc(1*sizeof(struct node));\n temp->ptr = top;\n temp->info = data;\n top = temp;\n }\n count++;\n}\nvoid display(){\n top1 = top;\n if (top1 == NULL){\n printf(\"empty stack\");\n return;\n }\n while (top1 != NULL){\n printf(\"%d \", top1->info);\n top1 = top1->ptr;\n }\n}\nvoid pop(){\n top1 = top;\n if (top1 == NULL){\n printf(\"\\n error\");\n return;\n }\n else\n top1 = top1->ptr;\n printf(\"\\n Popped value : %d\", top->info);\n free(top);\n top = top1;\n count--;\n }\n int topelement(){\n return(top->info);\n }\n //check stack empty or not\n void empty(){\n if (top == NULL)\n printf(\"\\n empty stack\");\n else\n printf(\"\\n stack not empty with %d values\", count);\n }\n void destroy(){\n top1 = top;\n while (top1 != NULL){\n top1 = top->ptr;\n free(top);\n top = top1;\n top1 = top1->ptr;\n }\n free(top1);\n top = NULL;\n printf(\"\\n all are destroyed\");\n count = 0;\n}"
},
{
"code": null,
"e": 4415,
"s": 4344,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 4740,
"s": 4415,
"text": "1 - Push\n2 - Pop\n3 - Top\n4 - Empty\n5 - Exit\n6 - Display\n7 - Stack Count\n8 - Destroy stack\nEnter choice: 1\nEnter element: 23\nEnter choice: 1\nEnter element: 45\nEnter choice: 1\nEnter element: 56\nEnter choice: 2\nPopped value: 56\nEnter choice: 6\n45 23\nEnter choice: 8\nall are destroyed\nEnter choice: 6\nempty stack\nEnter choice: 5"
}
] |
IDE | GeeksforGeeks | A computer science portal for geeks
|
Please enter your email address or userHandle.
12345678910111213141516171819202122232425import java.io.*;import java.lang.*;class GFG { public static int fun(int a[],int n, int l) { if(n==l-1) { System.out.println(a[n]); return a[n]; } else { System.out.println(Math.max(a[n], fun(a,n+1,l))); return a[n]; } } public static void main (String[] args) { int a[]={7,9,8,2,5,3}; fun(a,0,6); //code }}ההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
|
[
{
"code": null,
"e": 164,
"s": 117,
"text": "Please enter your email address or userHandle."
}
] |
Find sum of frequency of given elements in the list in Python
|
A given list has many repeated items. We are interested in finding out the sum of the frequency of some such items which are repeated in the list. Below are the approaches how we can achieve this.
We have two lists. One has the list of values and other has the values whose frequency needs to be checked from the first list. So we create a for loop to count the number of occurrences of the elements from the second list in the first list and then apply the sum function to get the final sum of frequency.
Live Demo
chk_list= ['Mon', 'Tue']
big_list = ['Mon','Tue', 'Wed', 'Mon','Mon','Tue']
# Apply sum
res = sum(big_list.count(elem) for elem in chk_list)
# Printing output
print("Given list to be analysed: \n", big_list)
print("Given list to with values to be analysed:\n", chk_list)
print("Sum of the frequency: ", res)
Running the above code gives us the following result −
Given list to be analysed:
['Mon', 'Tue', 'Wed', 'Mon', 'Mon', 'Tue']
Given list to with values to be analysed:
['Mon', 'Tue']
Sum of the frequency: 5
The Counter function from collections module can get the desired result by applying it to the list whose values have to be analysed while looping through the smaller list which has only the elements whose frequency needs to be established.
Live Demo
from collections import Counter
chk_list= ['Mon', 'Tue']
big_list = ['Mon','Tue', 'Wed', 'Mon','Mon','Tue']
# Apply Counter
res = sum(Counter(big_list)[x] for x in chk_list)
# Printing output
print("Given list to be analysed: \n", big_list)
print("Given list to with values to be analysed:\n", chk_list)
print("Sum of the frequency: ", res)
Running the above code gives us the following result −
Given list to be analysed:
['Mon', 'Tue', 'Wed', 'Mon', 'Mon', 'Tue']
Given list to with values to be analysed:
['Mon', 'Tue']
Sum of the frequency: 5
|
[
{
"code": null,
"e": 1259,
"s": 1062,
"text": "A given list has many repeated items. We are interested in finding out the sum of the frequency of some such items which are repeated in the list. Below are the approaches how we can achieve this."
},
{
"code": null,
"e": 1568,
"s": 1259,
"text": "We have two lists. One has the list of values and other has the values whose frequency needs to be checked from the first list. So we create a for loop to count the number of occurrences of the elements from the second list in the first list and then apply the sum function to get the final sum of frequency."
},
{
"code": null,
"e": 1579,
"s": 1568,
"text": " Live Demo"
},
{
"code": null,
"e": 1889,
"s": 1579,
"text": "chk_list= ['Mon', 'Tue']\nbig_list = ['Mon','Tue', 'Wed', 'Mon','Mon','Tue']\n\n# Apply sum\nres = sum(big_list.count(elem) for elem in chk_list)\n\n# Printing output\nprint(\"Given list to be analysed: \\n\", big_list)\nprint(\"Given list to with values to be analysed:\\n\", chk_list)\nprint(\"Sum of the frequency: \", res)"
},
{
"code": null,
"e": 1944,
"s": 1889,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2095,
"s": 1944,
"text": "Given list to be analysed:\n['Mon', 'Tue', 'Wed', 'Mon', 'Mon', 'Tue']\nGiven list to with values to be analysed:\n['Mon', 'Tue']\nSum of the frequency: 5"
},
{
"code": null,
"e": 2335,
"s": 2095,
"text": "The Counter function from collections module can get the desired result by applying it to the list whose values have to be analysed while looping through the smaller list which has only the elements whose frequency needs to be established."
},
{
"code": null,
"e": 2346,
"s": 2335,
"text": " Live Demo"
},
{
"code": null,
"e": 2691,
"s": 2346,
"text": "from collections import Counter\n\nchk_list= ['Mon', 'Tue']\nbig_list = ['Mon','Tue', 'Wed', 'Mon','Mon','Tue']\n\n# Apply Counter\n\nres = sum(Counter(big_list)[x] for x in chk_list)\n\n# Printing output\nprint(\"Given list to be analysed: \\n\", big_list)\nprint(\"Given list to with values to be analysed:\\n\", chk_list)\nprint(\"Sum of the frequency: \", res)"
},
{
"code": null,
"e": 2746,
"s": 2691,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2897,
"s": 2746,
"text": "Given list to be analysed:\n['Mon', 'Tue', 'Wed', 'Mon', 'Mon', 'Tue']\nGiven list to with values to be analysed:\n['Mon', 'Tue']\nSum of the frequency: 5"
}
] |
Get the Maximum element of an Object in R Programming - max() Function - GeeksforGeeks
|
05 Jun, 2020
max() function in R Language is used to find the maximum element present in an object. This object can be a Vector, a list, a matrix, a data frame, etc..
Syntax: max(object, na.rm)
Parameters:object: Vector, matrix, list, data frame, etc.na.rm: Boolean value to remove NA element.
Example 1:
# R program to illustrate # the use of max() function # Creating vectorsx1 <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)x2 <- c(1, 4, 2, 8, NA, 11) # Finding Maximum elementmax(x1)max(x2, na.rm = FALSE)max(x2, na.rm = TRUE)
Output:
[1] 9
[1] NA
[1] 11
Example 2:
# R program to illustrate # the use of max() function # Creating a matrixarr = array(2:13, dim = c(2, 3, 2)) print(arr) # Using max() functionmax(arr)
Output:
,, 1
[, 1] [, 2] [, 3]
[1, ] 2 4 6
[2, ] 3 5 7,, 2
[, 1] [, 2] [, 3]
[1, ] 8 10 12
[2, ] 9 11 13
[1] 13
R DataFrame-Function
R Matrix-Function
R Object-Function
R Vector-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
R - if statement
How to import an Excel File into R ?
Time Series Analysis in R
|
[
{
"code": null,
"e": 24851,
"s": 24823,
"text": "\n05 Jun, 2020"
},
{
"code": null,
"e": 25005,
"s": 24851,
"text": "max() function in R Language is used to find the maximum element present in an object. This object can be a Vector, a list, a matrix, a data frame, etc.."
},
{
"code": null,
"e": 25032,
"s": 25005,
"text": "Syntax: max(object, na.rm)"
},
{
"code": null,
"e": 25132,
"s": 25032,
"text": "Parameters:object: Vector, matrix, list, data frame, etc.na.rm: Boolean value to remove NA element."
},
{
"code": null,
"e": 25143,
"s": 25132,
"text": "Example 1:"
},
{
"code": "# R program to illustrate # the use of max() function # Creating vectorsx1 <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)x2 <- c(1, 4, 2, 8, NA, 11) # Finding Maximum elementmax(x1)max(x2, na.rm = FALSE)max(x2, na.rm = TRUE)",
"e": 25355,
"s": 25143,
"text": null
},
{
"code": null,
"e": 25363,
"s": 25355,
"text": "Output:"
},
{
"code": null,
"e": 25384,
"s": 25363,
"text": "[1] 9\n[1] NA\n[1] 11\n"
},
{
"code": null,
"e": 25395,
"s": 25384,
"text": "Example 2:"
},
{
"code": "# R program to illustrate # the use of max() function # Creating a matrixarr = array(2:13, dim = c(2, 3, 2)) print(arr) # Using max() functionmax(arr)",
"e": 25548,
"s": 25395,
"text": null
},
{
"code": null,
"e": 25556,
"s": 25548,
"text": "Output:"
},
{
"code": null,
"e": 25706,
"s": 25556,
"text": ",, 1\n\n [, 1] [, 2] [, 3]\n[1, ] 2 4 6\n[2, ] 3 5 7,, 2\n\n [, 1] [, 2] [, 3]\n[1, ] 8 10 12\n[2, ] 9 11 13\n\n[1] 13\n"
},
{
"code": null,
"e": 25727,
"s": 25706,
"text": "R DataFrame-Function"
},
{
"code": null,
"e": 25745,
"s": 25727,
"text": "R Matrix-Function"
},
{
"code": null,
"e": 25763,
"s": 25745,
"text": "R Object-Function"
},
{
"code": null,
"e": 25781,
"s": 25763,
"text": "R Vector-Function"
},
{
"code": null,
"e": 25792,
"s": 25781,
"text": "R Language"
},
{
"code": null,
"e": 25890,
"s": 25792,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25899,
"s": 25890,
"text": "Comments"
},
{
"code": null,
"e": 25912,
"s": 25899,
"text": "Old Comments"
},
{
"code": null,
"e": 25964,
"s": 25912,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 26002,
"s": 25964,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 26037,
"s": 26002,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 26095,
"s": 26037,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 26144,
"s": 26095,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 26187,
"s": 26144,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 26237,
"s": 26187,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 26254,
"s": 26237,
"text": "R - if statement"
},
{
"code": null,
"e": 26291,
"s": 26254,
"text": "How to import an Excel File into R ?"
}
] |
Callbacks in C
|
The callback is basically any executable code that is passed as an argument to other code, that is expected to call back or execute the argument at a given time. We can define it in other words like this: If the reference of a function is passed to another function argument for calling, then it is called the callback function.
In C we have to use a function pointer to call the callback function. The following code is showing how the callback function is doing its task.
#include<stdio.h>
void my_function() {
printf("This is a normal function.");
}
void my_callback_function(void (*ptr)()) {
printf("This is callback function.\n");
(*ptr)(); //calling the callback function
}
main() {
void (*ptr)() = &my_function;
my_callback_function(ptr);
}
This is callback function.
This is a normal function.
|
[
{
"code": null,
"e": 1391,
"s": 1062,
"text": "The callback is basically any executable code that is passed as an argument to other code, that is expected to call back or execute the argument at a given time. We can define it in other words like this: If the reference of a function is passed to another function argument for calling, then it is called the callback function."
},
{
"code": null,
"e": 1536,
"s": 1391,
"text": "In C we have to use a function pointer to call the callback function. The following code is showing how the callback function is doing its task."
},
{
"code": null,
"e": 1827,
"s": 1536,
"text": "#include<stdio.h>\nvoid my_function() {\n printf(\"This is a normal function.\");\n}\nvoid my_callback_function(void (*ptr)()) {\n printf(\"This is callback function.\\n\");\n (*ptr)(); //calling the callback function\n}\nmain() {\n void (*ptr)() = &my_function;\n my_callback_function(ptr);\n}"
},
{
"code": null,
"e": 1881,
"s": 1827,
"text": "This is callback function.\nThis is a normal function."
}
] |
Convert JS array into an object - JavaScript
|
Suppose, we have an array of objects like this −
const arr = [
{id: 1, name: "Mohan"},
{id: 2,name: "Sohan"},
{id: 3,name: "Rohan"}
];
We are required to write a function that takes one such array and constructs an object from it with the id property as key and name as value
The output for the above array should be −
const output = {1:{name:"Mohan"},2:{name:"Sohan"},3:{name:"Rohan"}}
Following is the code −
const arr = [
{id: 1, name: "Mohan"},
{id: 2,name: "Sohan"},
{id: 3,name: "Rohan"}
];
const arrayToObject = arr => {
const res = {};
for(let ind = 0; ind < arr.length; ind++){
res[ind + 1] = {
"name": arr[ind].name
};
};
return res;
};
console.log(arrayToObject(arr));
This will produce the following output in console −
{
'1': { name: 'Mohan' },
'2': { name: 'Sohan' },
'3': { name: 'Rohan' }
}
|
[
{
"code": null,
"e": 1111,
"s": 1062,
"text": "Suppose, we have an array of objects like this −"
},
{
"code": null,
"e": 1206,
"s": 1111,
"text": "const arr = [\n {id: 1, name: \"Mohan\"},\n {id: 2,name: \"Sohan\"},\n {id: 3,name: \"Rohan\"}\n];"
},
{
"code": null,
"e": 1347,
"s": 1206,
"text": "We are required to write a function that takes one such array and constructs an object from it with the id property as key and name as value"
},
{
"code": null,
"e": 1390,
"s": 1347,
"text": "The output for the above array should be −"
},
{
"code": null,
"e": 1458,
"s": 1390,
"text": "const output = {1:{name:\"Mohan\"},2:{name:\"Sohan\"},3:{name:\"Rohan\"}}"
},
{
"code": null,
"e": 1482,
"s": 1458,
"text": "Following is the code −"
},
{
"code": null,
"e": 1793,
"s": 1482,
"text": "const arr = [\n {id: 1, name: \"Mohan\"},\n {id: 2,name: \"Sohan\"},\n {id: 3,name: \"Rohan\"}\n];\nconst arrayToObject = arr => {\n const res = {};\n for(let ind = 0; ind < arr.length; ind++){\n res[ind + 1] = {\n \"name\": arr[ind].name\n };\n };\n return res;\n};\nconsole.log(arrayToObject(arr));"
},
{
"code": null,
"e": 1845,
"s": 1793,
"text": "This will produce the following output in console −"
},
{
"code": null,
"e": 1929,
"s": 1845,
"text": "{\n '1': { name: 'Mohan' },\n '2': { name: 'Sohan' },\n '3': { name: 'Rohan' }\n}"
}
] |
Java loops | Set 1 | Practice | GeeksforGeeks
|
For a given N, prints the sum of even and odd integers of the first N natural numbers.
Example 1:
Input:
N = 1
Output:
0 1
Explanation:
Natural numbers less than 1 are only 1.
So the sum of even number = 0.
and the sum of odd number = 1.
Example 2:
Input:
N = 6
Output:
12 9
Explanation:
Natural numbers less than 6 are
1 2 3 4 5 6
So the sum of even number = 2 + 4 + 6 = 12.
and the sum of odd number = 1 + 3 + 5 = 9.
Your Task:
You don't need to read input or print anything. Your task is to complete the function getSum() which takes an integer N as input parameter and return the sum of even and odd natural number less than equal to N.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1<= N <=104
-1
payalchaudhary4423 months ago
static ArrayList<Integer> getSum(int N){ // code here int evenSum=0; int oddSum=0; for(int i=1; i<=N;i++) { if(i%2==0) { evenSum=evenSum+i; } else { oddSum= oddSum+i; } } getSum.add(evenSum); getSum.add(oddSum); return getSum; } }
0
sonamnkumari3 months ago
class Solution{ static ArrayList<Integer> getSum(int N){ // code here int evenSum=0; int oddSum=0; for(int i=2;i<=N;i+=2){ evenSum=evenSum+i; } for(int i=1;i<=N;i+=2){ oddSum=oddSum+i; } ArrayList<Integer> numbers=new ArrayList<>(); numbers.add(evenSum); numbers.add(oddSum); return numbers; }}
0
gauravverma9918187053 months ago
import Java.util.Scanner;
class OddEven
{
public static void main(string[] args){
int n,sum=0;
System.out.print("Enter the Number:");
Scanner r=new Scanner(System.in);
n=r.nextInt();
if(n%2==0)
{
for(int i=0;i<=n;i=i+2)
{
sum=sum+i;
}
System.out.print("Sum of Even number:"+ sum);
}
else
{
for(int i=1;i<=n;i=i+2)
{
sum=sum+i;
}
System.out.print("Sum of Odd number :"+sum);
}
}
}
0
98pcjgbgt5a9ltq4d2c99y6scapx4ytypoz5t3pw4 months ago
public class Main{
public static void main(String args[]) { int sum=0,i,sumodd=0; for(i=0;i<=5;i++) { if(i%2==0) { sum=sum+i; } else { sumodd=sumodd+i; } } System.out.println(sum ); System.out.println(sumodd); } }
0
badgujarsachin835 months ago
static ArrayList<Integer> getSum(int N){
// code here
ArrayList<Integer> ans=new ArrayList<Integer>(2);
int even=0;
int odd=0;
for(int i=1;i<=N;i++){
if(i%2==0){
even+=i;
}else{
odd+=i;
}
}
ans.add(even);
ans.add(odd);
return ans;
}
-1
pankajkumarravi6 months ago
********************** Java Logic ****************
static ArrayList<Integer> getSum(int N){ // code here ArrayList<Integer> resp=new ArrayList<Integer>(2); int i=1; int evenSum=0; int oddSum=0; while (i<=N){ if (i%2 ==0) evenSum =evenSum+i; else oddSum = oddSum+i; i++; } resp.add(evenSum); resp.add(oddSum); return resp;}
-1
notaverageuser6 months ago
O(1) time compexity solution.
class Solution{
static ArrayList<Integer> getSum(int N) {
ArrayList<Integer> list = new ArrayList<>();
int sumEven = 0, sumOdd = 0;
int n = N / 2;
sumEven = (int) (n / 2.0 * (2 * 2 + (n - 1)*2));
n = (N + 1) / 2;
sumOdd = (int) (n / 2.0 * (2 * 1 + (n - 1)*2));
list.add(sumEven);
list.add(sumOdd);
return list;
}
}
-1
rawadaridi6 months ago
ArrayList<Integer> sum = new ArrayList<Integer>(); int even = 0; int odd = 0; for(int i = 1; i <= N; i++){ if(N <= 10000 && N >= 1){ if(i % 2 == 0){ even += i; } else{ odd += i; } } else{ System.out.println("Enter a number between 1 and 10000."); } } sum.add(even); sum.add(odd); return sum;
0
vikash katiyar7 months ago
vikash katiyar
ArrayList<integer> list = new ArrayList<integer>(); int count =0,sum=0; for(int i=1;i<=N;i++) {
if(i%2==0) { count=count+i; } else { sum=sum+i; } } list.add(count); list.add(sum);return list;
-1
ashay9 months ago
ashay
ArrayList<integer> list = new ArrayList<integer>(); int even=0,odd=0; for(int i=1; i<=N; i++)
if(i%2==0){ even=even+i;
} for(int i=1; i<=N; i++)
if(i%2!=0){ odd=odd+i;
}
list.add(even); list.add(odd); return list;
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 325,
"s": 238,
"text": "For a given N, prints the sum of even and odd integers of the first N natural numbers."
},
{
"code": null,
"e": 336,
"s": 325,
"text": "Example 1:"
},
{
"code": null,
"e": 476,
"s": 336,
"text": "Input:\nN = 1\nOutput:\n0 1\nExplanation:\nNatural numbers less than 1 are only 1.\nSo the sum of even number = 0.\nand the sum of odd number = 1."
},
{
"code": null,
"e": 487,
"s": 476,
"text": "Example 2:"
},
{
"code": null,
"e": 660,
"s": 487,
"text": "Input:\nN = 6\nOutput:\n12 9 \nExplanation:\nNatural numbers less than 6 are \n1 2 3 4 5 6\nSo the sum of even number = 2 + 4 + 6 = 12.\nand the sum of odd number = 1 + 3 + 5 = 9."
},
{
"code": null,
"e": 884,
"s": 660,
"text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function getSum() which takes an integer N as input parameter and return the sum of even and odd natural number less than equal to N."
},
{
"code": null,
"e": 946,
"s": 884,
"text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 972,
"s": 946,
"text": "Constraints: \n1<= N <=104"
},
{
"code": null,
"e": 975,
"s": 972,
"text": "-1"
},
{
"code": null,
"e": 1005,
"s": 975,
"text": "payalchaudhary4423 months ago"
},
{
"code": null,
"e": 1421,
"s": 1005,
"text": " static ArrayList<Integer> getSum(int N){ // code here int evenSum=0; int oddSum=0; for(int i=1; i<=N;i++) { if(i%2==0) { evenSum=evenSum+i; } else { oddSum= oddSum+i; } } getSum.add(evenSum); getSum.add(oddSum); return getSum; } }"
},
{
"code": null,
"e": 1423,
"s": 1421,
"text": "0"
},
{
"code": null,
"e": 1448,
"s": 1423,
"text": "sonamnkumari3 months ago"
},
{
"code": null,
"e": 1854,
"s": 1448,
"text": "class Solution{ static ArrayList<Integer> getSum(int N){ // code here int evenSum=0; int oddSum=0; for(int i=2;i<=N;i+=2){ evenSum=evenSum+i; } for(int i=1;i<=N;i+=2){ oddSum=oddSum+i; } ArrayList<Integer> numbers=new ArrayList<>(); numbers.add(evenSum); numbers.add(oddSum); return numbers; }}"
},
{
"code": null,
"e": 1856,
"s": 1854,
"text": "0"
},
{
"code": null,
"e": 1889,
"s": 1856,
"text": "gauravverma9918187053 months ago"
},
{
"code": null,
"e": 2270,
"s": 1889,
"text": "import Java.util.Scanner;\nclass OddEven\n{\npublic static void main(string[] args){\nint n,sum=0;\nSystem.out.print(\"Enter the Number:\");\nScanner r=new Scanner(System.in);\nn=r.nextInt();\nif(n%2==0)\n{\nfor(int i=0;i<=n;i=i+2)\n{\nsum=sum+i;\n}\nSystem.out.print(\"Sum of Even number:\"+ sum);\n}\nelse\n{\nfor(int i=1;i<=n;i=i+2)\n{\nsum=sum+i;\n}\nSystem.out.print(\"Sum of Odd number :\"+sum);\n}\n}\n}"
},
{
"code": null,
"e": 2272,
"s": 2270,
"text": "0"
},
{
"code": null,
"e": 2325,
"s": 2272,
"text": "98pcjgbgt5a9ltq4d2c99y6scapx4ytypoz5t3pw4 months ago"
},
{
"code": null,
"e": 2344,
"s": 2325,
"text": "public class Main{"
},
{
"code": null,
"e": 2707,
"s": 2344,
"text": " public static void main(String args[]) { int sum=0,i,sumodd=0; for(i=0;i<=5;i++) { if(i%2==0) { sum=sum+i; } else { sumodd=sumodd+i; } } System.out.println(sum ); System.out.println(sumodd); } } "
},
{
"code": null,
"e": 2709,
"s": 2707,
"text": "0"
},
{
"code": null,
"e": 2738,
"s": 2709,
"text": "badgujarsachin835 months ago"
},
{
"code": null,
"e": 2780,
"s": 2738,
"text": " static ArrayList<Integer> getSum(int N){"
},
{
"code": null,
"e": 2801,
"s": 2780,
"text": " // code here"
},
{
"code": null,
"e": 2859,
"s": 2801,
"text": " ArrayList<Integer> ans=new ArrayList<Integer>(2);"
},
{
"code": null,
"e": 2879,
"s": 2859,
"text": " int even=0;"
},
{
"code": null,
"e": 2898,
"s": 2879,
"text": " int odd=0;"
},
{
"code": null,
"e": 2929,
"s": 2898,
"text": " for(int i=1;i<=N;i++){"
},
{
"code": null,
"e": 2953,
"s": 2929,
"text": " if(i%2==0){"
},
{
"code": null,
"e": 2978,
"s": 2953,
"text": " even+=i;"
},
{
"code": null,
"e": 2997,
"s": 2978,
"text": " }else{"
},
{
"code": null,
"e": 3021,
"s": 2997,
"text": " odd+=i;"
},
{
"code": null,
"e": 3035,
"s": 3021,
"text": " }"
},
{
"code": null,
"e": 3045,
"s": 3035,
"text": " }"
},
{
"code": null,
"e": 3068,
"s": 3045,
"text": " ans.add(even);"
},
{
"code": null,
"e": 3090,
"s": 3068,
"text": " ans.add(odd);"
},
{
"code": null,
"e": 3110,
"s": 3090,
"text": " return ans;"
},
{
"code": null,
"e": 3116,
"s": 3110,
"text": " }"
},
{
"code": null,
"e": 3119,
"s": 3116,
"text": "-1"
},
{
"code": null,
"e": 3147,
"s": 3119,
"text": "pankajkumarravi6 months ago"
},
{
"code": null,
"e": 3198,
"s": 3147,
"text": "********************** Java Logic ****************"
},
{
"code": null,
"e": 3643,
"s": 3198,
"text": "static ArrayList<Integer> getSum(int N){ // code here ArrayList<Integer> resp=new ArrayList<Integer>(2); int i=1; int evenSum=0; int oddSum=0; while (i<=N){ if (i%2 ==0) evenSum =evenSum+i; else oddSum = oddSum+i; i++; } resp.add(evenSum); resp.add(oddSum); return resp;}"
},
{
"code": null,
"e": 3646,
"s": 3643,
"text": "-1"
},
{
"code": null,
"e": 3673,
"s": 3646,
"text": "notaverageuser6 months ago"
},
{
"code": null,
"e": 3703,
"s": 3673,
"text": "O(1) time compexity solution."
},
{
"code": null,
"e": 4110,
"s": 3703,
"text": "class Solution{\n static ArrayList<Integer> getSum(int N) {\n ArrayList<Integer> list = new ArrayList<>();\n\n int sumEven = 0, sumOdd = 0;\n int n = N / 2;\n sumEven = (int) (n / 2.0 * (2 * 2 + (n - 1)*2));\n\n n = (N + 1) / 2;\n\n sumOdd = (int) (n / 2.0 * (2 * 1 + (n - 1)*2));\n \n list.add(sumEven);\n list.add(sumOdd);\n return list;\n }\n}"
},
{
"code": null,
"e": 4113,
"s": 4110,
"text": "-1"
},
{
"code": null,
"e": 4136,
"s": 4113,
"text": "rawadaridi6 months ago"
},
{
"code": null,
"e": 4630,
"s": 4136,
"text": "ArrayList<Integer> sum = new ArrayList<Integer>(); int even = 0; int odd = 0; for(int i = 1; i <= N; i++){ if(N <= 10000 && N >= 1){ if(i % 2 == 0){ even += i; } else{ odd += i; } } else{ System.out.println(\"Enter a number between 1 and 10000.\"); } } sum.add(even); sum.add(odd); return sum;"
},
{
"code": null,
"e": 4632,
"s": 4630,
"text": "0"
},
{
"code": null,
"e": 4659,
"s": 4632,
"text": "vikash katiyar7 months ago"
},
{
"code": null,
"e": 4674,
"s": 4659,
"text": "vikash katiyar"
},
{
"code": null,
"e": 4791,
"s": 4674,
"text": "ArrayList<integer> list = new ArrayList<integer>(); int count =0,sum=0; for(int i=1;i<=N;i++) {"
},
{
"code": null,
"e": 5007,
"s": 4791,
"text": " if(i%2==0) { count=count+i; } else { sum=sum+i; } } list.add(count); list.add(sum);return list;"
},
{
"code": null,
"e": 5010,
"s": 5007,
"text": "-1"
},
{
"code": null,
"e": 5028,
"s": 5010,
"text": "ashay9 months ago"
},
{
"code": null,
"e": 5034,
"s": 5028,
"text": "ashay"
},
{
"code": null,
"e": 5142,
"s": 5034,
"text": "ArrayList<integer> list = new ArrayList<integer>(); int even=0,odd=0; for(int i=1; i<=N; i++)"
},
{
"code": null,
"e": 5192,
"s": 5142,
"text": " if(i%2==0){ even=even+i;"
},
{
"code": null,
"e": 5241,
"s": 5192,
"text": " } for(int i=1; i<=N; i++)"
},
{
"code": null,
"e": 5289,
"s": 5241,
"text": " if(i%2!=0){ odd=odd+i;"
},
{
"code": null,
"e": 5303,
"s": 5289,
"text": " }"
},
{
"code": null,
"e": 5369,
"s": 5303,
"text": " list.add(even); list.add(odd); return list;"
},
{
"code": null,
"e": 5515,
"s": 5369,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 5551,
"s": 5515,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5561,
"s": 5551,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5571,
"s": 5561,
"text": "\nContest\n"
},
{
"code": null,
"e": 5634,
"s": 5571,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5782,
"s": 5634,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 5990,
"s": 5782,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 6096,
"s": 5990,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
How to pop-up the first element from a Python tuple?
|
By definition, tuple object is immutable. Hence it is not possible to remove element from it. However, a workaround would be convert tuple to a list, remove desired element from list and convert it back to a tuple.
>>> T1=(1,2,3,4)
>>> L1=list(T1)
>>> L1.pop(0)
1
>>> L1
[2, 3, 4]
>>> T1=tuple(L1)
>>> T1
(2, 3, 4)
|
[
{
"code": null,
"e": 1277,
"s": 1062,
"text": "By definition, tuple object is immutable. Hence it is not possible to remove element from it. However, a workaround would be convert tuple to a list, remove desired element from list and convert it back to a tuple."
},
{
"code": null,
"e": 1377,
"s": 1277,
"text": ">>> T1=(1,2,3,4)\n>>> L1=list(T1)\n>>> L1.pop(0)\n1\n>>> L1\n[2, 3, 4]\n>>> T1=tuple(L1)\n>>> T1\n(2, 3, 4)"
}
] |
PL/SQL - WHILE LOOP Statement
|
A WHILE LOOP statement in PL/SQL programming language repeatedly executes a target statement as long as a given condition is true.
WHILE condition LOOP
sequence_of_statements
END LOOP;
DECLARE
a number(2) := 10;
BEGIN
WHILE a < 20 LOOP
dbms_output.put_line('value of a: ' || a);
a := a + 1;
END LOOP;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
PL/SQL procedure successfully completed.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2196,
"s": 2065,
"text": "A WHILE LOOP statement in PL/SQL programming language repeatedly executes a target statement as long as a given condition is true."
},
{
"code": null,
"e": 2257,
"s": 2196,
"text": "WHILE condition LOOP \n sequence_of_statements \nEND LOOP; \n"
},
{
"code": null,
"e": 2410,
"s": 2257,
"text": "DECLARE \n a number(2) := 10; \nBEGIN \n WHILE a < 20 LOOP \n dbms_output.put_line('value of a: ' || a); \n a := a + 1; \n END LOOP; \nEND; \n/ "
},
{
"code": null,
"e": 2496,
"s": 2410,
"text": "When the above code is executed at the SQL prompt, it produces the following result −"
},
{
"code": null,
"e": 2701,
"s": 2496,
"text": "value of a: 10 \nvalue of a: 11 \nvalue of a: 12 \nvalue of a: 13 \nvalue of a: 14 \nvalue of a: 15 \nvalue of a: 16 \nvalue of a: 17 \nvalue of a: 18 \nvalue of a: 19 \n\nPL/SQL procedure successfully completed. \n"
},
{
"code": null,
"e": 2708,
"s": 2701,
"text": " Print"
},
{
"code": null,
"e": 2719,
"s": 2708,
"text": " Add Notes"
}
] |
Tryit Editor v3.7
|
Tryit: JavaScript function
|
[] |
Tryit Editor v3.7
|
Tryit: Grey HSL color values
|
[] |
15 Awesome Python And Data Science Projects For 2021 And Beyond | by Bharath K | Towards Data Science
|
Implementation of awesome and cool projects to revolutionize the modern generation is the best part of Python and Data Science.
My favorite part about the fields of Python programming and Data Science is the numerous amounts of wonderful projects you can build with them. You can construct groundbreaking, innovative, and revolutionary projects which can benefit the entire society as well as change the landscape of the entire world to reach great feats.
Tech giants and major companies are heavily investing their resources in Data Science due to the vast potential the innovations of this subject possess. With a wide array of spectacular projects that are built each day by creative data scientists and programmers, it would great to have a look at what we as individuals can achieve.
In this article, we will discuss fifteen awesome Python and Data Science projects that you can enjoy implementing. These projects are guaranteed to provide you with the best possible experience for understanding most of the essential Python and Data Science concepts in further detail. Along with the immense knowledge and experience you gain from these projects, you can also showcase them in your resumes for better job opportunities or just as a sign of self-pride!
The article is divided into three major sections targeted at audiences of all levels. The categories are beginner, intermediate, and advanced. In each of these categories, we have exactly five projects mentioned. This adds up to a total of fifteen fabulous projects that you can build from scratch. You can pick which category or which particular project you want to choose. However, it is highly recommended that you glance through all the project ideas provided in this article for more innovative ideas.
So, without further ado, let us start looking at each one of these project ideas, and analyze them accordingly.
To start things off with a simple project that I recently covered in one of my articles is the reminder application that will consistently notify you about the various tasks you have to complete throughout the day. The notifications will be reminded according to the time scheduler which you have programmed the script to perform.
The project makes use of only two modules for the completion of the task. It utilizes the time module, which comes pre-installed with Python, and the plyer library, which will be used for alerting us about the timely notifications for the completion of the particular task at hand.
The following project is extremely simple for a beginner-level introduction to understanding Python and the basic concepts related to the subject. Despite its simplicity, it can be very useful for improving your overall productivity. The link provided guides you through the entire process of building this project from scratch.
towardsdatascience.com
The first project is fairly simple, and the estimated time to complete this project should range anywhere from 30 minutes to 2 hours, depending on the programmer’s interest and skill. However, the difficulty range from the next projects mentioned will gradually increase.
An important aspect of python and machine learning is understanding the math behind these concepts and knowing how some of the code in machine learning libraries. To have a better grasp of these concepts, it is essential to practice the ideas implemented in scientific modules like numpy and scikit-learn by ourselves. One such programming application is performing the matrix multiplication operation without using any ML libraries.
To perform this task, the main requirement is knowledge of how matrices works. The complete explanation and guide can be obtained from my article below. However, if you are just interested in the basic gist of this coding problem and want to try to solve this on your own, then use the next reference paragraphs to help you get started.
towardsdatascience.com
My approach to this problem is going to be to take all the inputs from the user. These are the number of rows and columns of both the first and second matrix. Also, based on the number of rows and columns of each matrix, we will respectively fill the alternative positions accordingly.
The first step, before doing any matrix multiplication is to check if this operation between the two matrices is actually possible. This can be done by checking if the columns of the first matrix matches the shape of the rows in the second matrix. This can be formulated as:
→ no. of columns in matrix 1 = no. of rows in matrix 2
This should be a great starting point for you to get started. From here you can compute the problem statement with various ways by utilizing your own techniques.
The house price prediction is one of the best ways for a beginner to get started with various machine learning algorithms. The best part about trying out this project is that you can gain a superior understanding of the scikit-learn (also referred to as sklearn) library, which is an extremely significant module for Machine Learning tasks.
The scikit-learn module is one of the best tools for machine learning and predictive data analysis. It offers a wide range of pre-built algorithms such as logistic regression, support vector machines (SVM’s), classification algorithms like K-means clustering, and a ton more operations. This is the best way for beginners to get started with machine learning algorithms because of the simple and efficient tools that this module grants access to.
Using this module you can access The Boston Housing Dataset. The Boston Housing Dataset is a derived from information collected by the U.S. Census Service concerning housing in the area of Boston MA. The dataset is small in size with only 506 cases. The following describes the dataset columns:
CRIM — per capita crime rate by town
ZN — proportion of residential land zoned for lots over 25,000 sq.ft.
INDUS — proportion of non-retail business acres per town.
CHAS — Charles River dummy variable (1 if tract bounds river; 0 otherwise)
NOX — nitric oxides concentration (parts per 10 million)
RM — average number of rooms per dwelling
AGE — proportion of owner-occupied units built prior to 1940
DIS — weighted distances to five Boston employment centres
RAD — index of accessibility to radial highways
TAX — full-value property-tax rate per $10,000
PTRATIO — pupil-teacher ratio by town
B — 1000(Bk — 0.63)2 where Bk is the proportion of blacks by town
LSTAT — % lower status of the population
MEDV — Median value of owner-occupied homes in $1000's
In the next few blocks of code, we will discuss how we can utilize this module to access the dataset as well as some of the additional libraries required for analyzing and solving this simple machine learning task. It will be a quick guide on how you can get started and will cover the basic requirement. After understanding these concepts, you should be able to implement some machine learning algorithms on the following dataset.
The first step is to import all the essential requirements for solving this task. It is recommended that you use the following modules while trying to implement the various machine learning algorithms. The block of code is a simple representation of some of the code lines that might be required to solve the task. (It is for trying a decision tree or a random forest approach.)
After importing all the essential libraries required for performing this task, you can load the Boston dataset and proceed to assign separate variables for the data and the target variable. The price which is to be predicted is the target variable, while the other important features are the information of the dataset. This converts the problem into a machine learning prediction task. You can do this from the code provided below.
Finally, we can quickly visualize this data using the pandas data frame structure. This can be constructed from the simple code block as mentioned below.
The above image is a representation of the dataset. You can add the feature names for the respective columns if you like. However, this should be a good starting point for most beginners to get started. Kaggle and GitHub are your best friends for solving these machine learning tasks. Check out the Kaggle Website for further information from the link here.
Email spam, also referred to as junk email, is unsolicited messages sent in bulk by email (spamming). Email filtering is the processing of email to organize it according to specified criteria. The term can apply to the intervention of human intelligence, but most often refers to the automatic processing of incoming messages with anti-spam techniques — to outgoing emails as well as those being received.
Various Classification Algorithms can be used for completing the email spam detection task. The various machine learning algorithms like Naive Bayes, support vector machines, K-nearest neighbors, and random forests among many other algorithms can be used for filtering spam messages and classifying if the received email is a spam or not.
Advanced spam detection can be performed using techniques like neural networks or optical character recognition (OCR) which is also used by companies like Gmail for spam filtering.
Assume we have a dataset of 30,000 emails out of which some are classified as spam and some are classified as not spam. The machine learning model will be trained on the dataset. Once the training process is complete, we can test it with a mail that was not included in our training dataset. The machine learning model can make predictions on the following input and classify it correctly if the input e-mail is spam or not.
Various anti-spam techniques are used to prevent email spam (unsolicited bulk email). No technique is a complete solution to the spam problem, and each has trade-offs between incorrectly rejecting legitimate email (false positives) as opposed to not rejecting all spam (false negatives) — and the associated costs in time, effort, and cost of wrongfully obstructing good mail.
As an example, the Naive Bayes classifiers are a popular statistical technique of e-mail filtering. They typically use bag of words features to identify spam e-mail, an approach commonly used in text classification. Naive Bayes classifiers work by correlating the use of tokens (typically words, or sometimes other things), with spam and non-spam e-mails and then using Bayes’ theorem to calculate a probability that an email is or is not spam.
Naive Bayes spam filtering is a baseline technique for dealing with spam that can tailor itself to the email needs of individual users and give low false positive spam detection rates that are generally acceptable to users. It is one of the oldest ways of doing spam filtering, with roots in the 1990s.
A quick guide for the following can be obtained from the link here.
Sentiment analysis (also known as opinion mining or emotion AI) refers to the use of natural language processing, text analysis, computational linguistics, and biometrics to systematically identify, extract, quantify, and study affective states and subjective information.
Sentiment analysis is widely applied to voice of the customer materials such as reviews and survey responses, online and social media, and healthcare materials for applications that range from marketing to customer service to clinical medicine.
A basic task in sentiment analysis is classifying the polarity of a given text at the document, sentence, or feature/aspect level — whether the expressed opinion in a document, a sentence or an entity feature/aspect is positive, negative, or neutral. Advanced, “beyond polarity” sentiment classification looks, for instance, at emotional states such as “angry”, “sad”, and “happy”.
However, you can choose to negate the other reviews and only classify them as good or bad. For example, for a movie review, anything rated 1–2 stars is marked as negative, a rating of 4–5 is marked as positive, while a neutral rating of 3 can be ignored accordingly.
Solving the Sentiment Analysis problem is one of the best beginner-level projects for you to start with due to the wide range of options that you have available to solve the following task. You can choose any method that you prefer for solving this question.
Machine learning Algorithms like logistic and Naive Bayes can be easily used to solve such kinds of tasks. Many approaches can be used for obtaining a solution to this problem, including methods of deep learning. However, even the simplest methods can be used to solve this task, depending on how complicated you decide to make the problem.
My suggestion for detailed understanding of the concepts of natural language processing and sentiment analysis is the link here. You can audit the course if you like. I would also recommend checking out the article below for further information on this topic.
towardsdatascience.com
The outdated GIF you guys can see above is one of my first projects I ever did with the help of pygame about three years ago. If you want a more concise guide on how you can build this from scratch with python then do let me know. But the main idea here is to build a game with python from scratch on your own. Start off with something simple like a snake game, or tic-tac-toe, and proceed towards a more advanced one like flappy birds with reinforcement learning.
The idea behind accomplishing this task is more of personal opinion and preference. I believe that one of the best ways to get a good hold of any programming language is to start with a project that is fun and enjoyable. I am also a bit of a gaming nerd. To get started with gaming projects related to python, I would highly recommend the use of the Pygame library module for the execution of such programs.
With the pygame module, you can build some simple, fun games with python. However, don’t expect anything too fancy as it has its limitations. Regardless, it is a fantastic way to get started, and below is the starter code to dive in. Just install pygame with a simple pip command and then use the following import pygame command. The following message will greet you upon the successful importing of the module.
pygame 1.9.6Hello from the pygame community. https://www.pygame.org/contribute.html
The versions might differ depending on the time on installation, so don’t worry too much. Just use the updated versions always in any scenario. I will go over some basic commands you should know and how they work. Below is the complete code block for all the important aspects you need to know to get started with pygame.
#imports the pygame library moduleimport pygame# initilize the pygame modulepygame.init()# Setting your screen size with a tuple of the screen width and screen heightdisplay_screen = pygame.display.set_mode((800,600)) # Setting a random caption title for your pygame graphical window.pygame.display.set_caption("pygame test")# Update your screen when requiredpygame.display.update()# quit the pygame initialization and modulepygame.quit()# End the programquit()
I would highly recommend you check out some YouTube videos for better understanding and learning to build some games. The documentation for the pygame module, albeit a little lengthy, is probably one the best resources to learn more about this module.
Computer vision is an interdisciplinary scientific field that deals with how computers can gain high-level understanding from digital images or videos. From the perspective of engineering, it seeks to understand and automate tasks that the human visual system can do.
RGB are the 3 most significant layers of coloring for computer vision tasks. The composition of these three colors, namely red, green, and blue can be used to compose almost any other color. Mixing them in the right proportion allows us to frame any other desired color. This concept has existed since the cathode ray televisions a few decades ago.
Each of these colors has an 8 bit integer value. This means a matrix of these could range from 0 to 255. The reasoning for this is because 28 is 256 and 0–255 consist of 256 values. Each of these colors will have a value of this range and since we have a 3-Dimensional image, we can stack each of these upon each other.
OpenCV module is by far the best library for the execution of complex machine learning, deep learning, and computer vision tasks. It offers simplicity and high standards for the analysis and performance of the models being built. It is an open-source library and can be integrated with other python modules such as NumPy to accomplish complicated real-time applications. It is supported for a wide range of programming languages and runs remarkably on most platforms such as Windows, Linux, and MacOS.
Working and dealing with images is an essential aspect of computer vision projects for AI and Data Science. The reading, displaying, and writing of images is an essential part of computer vision as you have to consistently deal with images. The best part about opencv apart from the previously mentioned advantages is that it grants you access to a variety of image formats as well. So, we can work on all these image formats without facing any major issues.
The article link mentioned below is a concise guide to master the basics of computer vision from scratch. I have covered all the essential aspects for a beginner to get started and achieve an overall detailed understanding of the OpenCV module and how you can operate on a variety of images.
towardsdatascience.com
The next intermediate level we will be focusing on is one of the coolest aspects of having python programming knowledge. Complicated tasks such as text-to-speech conversion and optical character recognition of python can be completed just with the help of understanding the python library modules created for this purpose.
The text-to-speech (TTS) is the process of converting words into a vocal audio form. The program, tool, or software takes an input text from the user, and using methods of natural language processing, understands the linguistics of the language being used, and performs logical inference on the text. This processed text is passed into the next block, where digital signal processing is performed on the processed text. With the use of the many algorithms and transformations, this processed text is finally converted into a speech format. This entire process involves the synthesizing of speech.
Optical Character Recognition is the conversion of 2-Dimensional text data into a form of machine-encoded text by the use of an electronic or mechanical device. The 2-Dimensional text data can be obtained from various sources such as scanned documents like PDF files, images with text data in formats such as .png or .jpeg, signposts like traffic posts, or any other images with any form of textual data. There is a wide range of interesting applications for optical character recognition.
Below is the list of two articles that will be extremely useful to get you acquainted with the Google Text-To-Speech module for speech translation and the pytesseract module for optical character recognition. Refer to these below articles for a comprehensive guide for getting started with them and perform a project using them together.
towardsdatascience.com
towardsdatascience.com
Face recognition is the procedural recognition of a human face along with the authorized name of the user. Face detection is a simpler task and can be considered as a beginner level project. Face detection is one of the steps that is required for face recognition. Face detection is a method of distinguishing the face of a human from the other parts of the body and the background.
The haar cascade classifier can be used for the purpose of face detection and accurately detect multiple faces in the frame. The haar cascade classifier for frontal face is usually an XML file that can be used with the open-cv module for reading the faces and then detecting the faces. A machine learning model such as the histogram of oriented gradients (H.O.G) which can be used with labeled data along with support vector machines (SVM’s) to perform this task as well.
The best approach for face recognition is to make use of the DNN’s (deep neural networks). After the detection of faces, we can use the approach of deep learning to solve face recognition tasks. There is a huge variety of transfer learning models like VGG-16 architecture, RESNET-50 architecture, face net architecture, etc. which can simplify the procedure to construct a deep learning model and allow users to build high-quality face recognition systems.
You can also build a custom deep learning model for solving the face recognition task. The modern models built for face recognition are highly accurate and provide an accuracy of almost over 99% for labeled datasets. The applications for the face recognition models can be used in security systems, surveillance, attendance systems, and a lot more.
Below is an example of a face recognition model built by me using the methods of VGG-16 transfer learning for face recognition after the face detection is performed by the haar cascade classifier. Check it out to learn a more detailed explanation of how exactly you can build your very own face recognition model.
towardsdatascience.com
The link above is an example for a high accuracy face recognition system using deep learning with transfer learning methods to grant access to authorized users and deny permission to unaccredited personnel. Using methods of image data augmentation and transfer learning models, the face recognition model on the authorized user’s faces predicts with a high accuracy level.
A unique aspect of working on Data Science projects is the ability to create awesome predictive type models. The Google search bar, WhatsApp messages, etc., among many other applications, use the methodology of Next Word Prediction to predict the appropriate suggestion after each new word has been typed.
This is similar to Autocomplete, or word completion, which is a feature in which an application predicts the rest of a word a user is typing. In Android smartphones, this is called predictive text. In graphical user interfaces, users can typically press the tab key to accept a suggestion or the down arrow key to accept one of several.
This project idea is a fantastic choice for transitioning from intermediate-level projects to fairly advanced ones. This project idea uses major concepts of natural language processing and will require a decent amount of skill to solve. You can use a variety of machine learning algorithms and techniques to solve this task. However, I would recommend and encourage all of you to try out some innovative deep learning methods for solving this project while aiming to achieve top-notch results.
The next word prediction for a particular user’s texting or typing can be awesome. It would save a lot of time by understanding the user’s patterns of texting. This could be also used to create a bigger virtual assistant project to complete certain sentences. Overall, the predictive search system and next-word prediction is a very fun concept to implement. You can check out my article below, which covers the deep learning methodology to predict the next words.
towardsdatascience.com
The resource mention above uses LSTM based deep learning model which takes an input word or sentence and predicts the next appropriate word. This deep learning model uses the concept of long short-term memory with natural language processing for the pre-processing of the corpus and text data. Uses a custom sequential model for the prediction of the appropriate next word. It has a wide array of applications in social media for the next word prediction.
This computer vision project could easily be considered a fairly advanced one but there are so many free tools and resources that are available that you could complete this task without any complications. The object detection task is the method of drawing a bounding box around the recognized object and identifying the recognized object according to the determined labels and predict these with specific accuracies. the object tracking is slightly different in comparison to the object detection, as you not only detect the particular object but also follow the object with the bounding box around it.
Object detection is a computer vision technique that allows us to identify and locate objects in an image or video. With this kind of identification and localization, object detection can be used to count objects in a scene and determine and track their precise locations, all while accurately labeling them. An example of this can be either following a particular vehicle on a road path or tracking a ball in any sports game like golf, cricket, baseball, etc.
The various algorithms to perform these tasks are R-CNN’s (Region-based convolutional neural networks), SSD (single shot detector), and YOLO (you only look once) among many others. I am going to mention 2 of the best resources by two talented programmers.
One method is more so for embedded systems like the raspberry pi and the other one is for PC related real-time webcam object detection. These two below resources are some of the best ways to get started with object detection/object tracking and they have YouTube videos explaining them in detail as well. Please do check out these resources to gain a better understanding of object detection.
github.com
github.com
The demand for high-quality chatbots is increasing every day. The main reason why chatbots are so popular now is because they can provide automated responses about the website or a particular topic. They can answer frequently asked questions and help new users on the website by welcoming them and briefing them about the particular site.
A well-trained chatbot can even converse with the user similar to how a human assistant would. Chatbots are also able to engage in conversations and help the user perceive what the site is about while promoting the website or social media web page. They can also advertise and garner better interaction from the user. All these factors make chatbots extremely important for any small start-up or any big website as it saves a lot of human effort and resources.
Deep Learning algorithms with neural networks and natural language processing (NLP) are the most popular chatbot methods which are being used today. There are a lot of other machine learning algorithms also which can be used. In deep learning, more popularly LSTMs are used and the sequence to sequence models with attention is preferred. Below is an example of an innovative chatbot built by me from scratch.
towardsdatascience.com
The resource mentioned above is for an Innovative Chatbot with 1-Dimensional Convolutional Layers.
A 1-Dimensional text classification-based chatbot that replies with sarcastic responses to commonly asked questions. This chatbot model is an integral component of the virtual assistant project that will respond to the user with witty responses and keep the user engaged in funny conversations. The chatbot model is also perfect for casual talks and appealing to a foreign audience. It also has a high-quality prediction system.
Machine translation, sometimes referred to by the abbreviation MT, is a sub-field of computational linguistics that investigates the use of software to translate text or speech from one language to another.
On a basic level, MT performs mechanical substitution of words in one language for words in another, but that alone rarely produces a good translation because recognition of whole phrases and their closest counterparts in the target language is needed. Not all words in one language have equivalent words in another language, and many words have more than one meaning.
These types of problems can be solved with AI and Data Science technologies. These usually work on concepts such as natural language processing, machine learning, and deep learning. A sequence to sequence (Seq2seq) mechanism with attention can be used to achieve higher accuracy and lower losses for these predictions. Seq2seq is a family of machine learning approaches used for language processing for applications that include language translation.
Seq2seq turns one sequence into another sequence. It does so by use of a recurrent neural network (RNN) or more often LSTM or GRU to avoid the problem of vanishing gradient. The context for each item is the output from the previous step. The primary components are one encoder and one decoder network. The encoder turns each item into a corresponding hidden vector containing the item and its context. The decoder reverses the process, turning the vector into an output item, using the previous output as the input context.
Zero-shot and one-shot learning methods even exist for natural language processing. The same methods can be used for better training of the model to improve the overall performance and avoid repeated training procedures which can be a really big hindrance in some real-life applications and scenarios. Hence, one-shot learning is a great alternative for deployment and working in other embedded systems with lower training capacities.
Machine Translation is an awesome advanced level project to try out and have fun with. A great resource for accomplishing this task is the official website of TensorFlow that deals with Neural machine translation with attention. They work on a toy dataset and provide great insides on how to perform the following complex problem. You can check out the link from here.
This project uses computer vision and deep learning to detect the various faces and classify the emotions of that particular face. Not only do the models classify the emotions but also detects and classifies the different hand gestures of the recognized fingers accordingly.
After distinguishing the human emotions or gestures a vocal response is provided by the trained model with the accurate prediction of the human emotion or gesture respectively. The best part about this project is the wide range of data set choices you have available to you.
The project is a fairly advanced computer vision task, which will be awesome to fit on your resume of widely accomplished projects. Working on this fabulous project will also provide you with some must needed experience to complete complicated and complex problems related to deep learning and computer vision.
The below links are a reference to one of the deep learning projects done by me by using methodologies of computer vision, data augmentation, and libraries such as TensorFlow and Keras to build deep learning models. I would highly recommend viewers to check the below 2-part series for a complete breakdown, analysis, and understanding of how to compute the following advanced computer vision task. Also, make sure to refer to the Google text-to-speech link provided in the previous section to understand how the vocal text conversion of text to speech works.
towardsdatascience.com
towardsdatascience.com
The links provided above represent a computer vision and deep learning model to recognize human emotions and gestures. The model also provides a vocal response and classifies the respective emotion or gesture accordingly. Uses deep learning technology with a custom-built sequential model to achieve high accuracy on human emotions, and transfer learning based on VGG-16 architecture for gesture recognition.
GANs developed and originated in 2014 by Ian Goodfellow, and his colleagues have gained immense popularity recently. GANs are perceived to be the future of deep learning with their amazing ability to create visuals and images that have never even existed. Generative Adversarial Networks are the current peak of deep learning with an exceedingly improving curve.
GANs are an undeniable future trend that will revolutionize artificial intelligence forever. GANs is a slightly complicated topic, and I will be covering it extensively in the upcoming article’s part by part. However, for the purpose of this post, it is essential to note that two networks, a generator, and a discriminator go to war against each other and have a small dispute.
The generator tries to create realistic fake images to bypass the elemental checking of the discriminator, while the role of the discriminator is to catch the fake copies. This cat and mouse chases leads to the development of unique samples that have never existed, and it is realistic, far beyond human imagination.
I am not going to mention any specific project with GANs as there is a wide variety of unique and awesome applications as well as other innovative projects you can create with them. The popularity of GANs is on the rise, and it can create new artistic and realistic images out of absolutely nothing. GANs are being even explored to generate music from various sub-fields and Genres. Hence, they are not limited to images only.
A famous example of Generative Adversarial Networks (GANs) can be observed from the website called “thispersondoesexist.com.” Upon refreshing or re-visiting this site, you will encounter new faces of individuals who actually don’t exist. This project is constructed and imagined by a type of GANs (generative adversarial network) called the StyleGAN2 (Dec 2019) developed by Karras et al. and Nvidia.
The construction of a variety of new projects with Python and Data Science will enable you to understand and grasp the concepts you have studied much better. The passion to build new applications with Python and Data Science is an important quality for being successful in this field.
Theoretical understanding of the intuition behind machine learning concepts and math for the various topics of data science is crucial. To appreciate the true beauty of data science, you need to try out lots of projects. The wide array of tasks and the problems you can solve are absolutely fantastic, which leads to a sense of accomplishment when you find their respective solutions.
However, you also need to know how you can implement the following projects in a real-life practical scenario. Don’t be afraid to get your hands dirty with some code and implement these projects on your own. Experiment with different parameters and try to achieve better solutions by trying out numerous algorithms and methods.
In this article, we discussed 15 awesome Python and Data Science projects that you can experiment with and try out. These ideas would fit perfectly for anyone’s resume as it includes a wide array of unique and cool projects that you have built. It will help you to improve your overall profile as well as help you in clearing the initial selection process more effectively.
With the implementation of these projects, you will also gain more practical knowledge and a deep understanding of the concepts that you work on. If you have any queries related to the topics discussed in this article, then feel free to let me know in the comments section below, and I will try to get back to you with a response as soon as possible.
Check out some of my other articles that you might enjoy reading!
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
Thank you all for sticking on till the end. I hope you guys enjoyed reading this article. I wish you all have a wonderful day ahead!
|
[
{
"code": null,
"e": 299,
"s": 171,
"text": "Implementation of awesome and cool projects to revolutionize the modern generation is the best part of Python and Data Science."
},
{
"code": null,
"e": 627,
"s": 299,
"text": "My favorite part about the fields of Python programming and Data Science is the numerous amounts of wonderful projects you can build with them. You can construct groundbreaking, innovative, and revolutionary projects which can benefit the entire society as well as change the landscape of the entire world to reach great feats."
},
{
"code": null,
"e": 960,
"s": 627,
"text": "Tech giants and major companies are heavily investing their resources in Data Science due to the vast potential the innovations of this subject possess. With a wide array of spectacular projects that are built each day by creative data scientists and programmers, it would great to have a look at what we as individuals can achieve."
},
{
"code": null,
"e": 1429,
"s": 960,
"text": "In this article, we will discuss fifteen awesome Python and Data Science projects that you can enjoy implementing. These projects are guaranteed to provide you with the best possible experience for understanding most of the essential Python and Data Science concepts in further detail. Along with the immense knowledge and experience you gain from these projects, you can also showcase them in your resumes for better job opportunities or just as a sign of self-pride!"
},
{
"code": null,
"e": 1936,
"s": 1429,
"text": "The article is divided into three major sections targeted at audiences of all levels. The categories are beginner, intermediate, and advanced. In each of these categories, we have exactly five projects mentioned. This adds up to a total of fifteen fabulous projects that you can build from scratch. You can pick which category or which particular project you want to choose. However, it is highly recommended that you glance through all the project ideas provided in this article for more innovative ideas."
},
{
"code": null,
"e": 2048,
"s": 1936,
"text": "So, without further ado, let us start looking at each one of these project ideas, and analyze them accordingly."
},
{
"code": null,
"e": 2379,
"s": 2048,
"text": "To start things off with a simple project that I recently covered in one of my articles is the reminder application that will consistently notify you about the various tasks you have to complete throughout the day. The notifications will be reminded according to the time scheduler which you have programmed the script to perform."
},
{
"code": null,
"e": 2661,
"s": 2379,
"text": "The project makes use of only two modules for the completion of the task. It utilizes the time module, which comes pre-installed with Python, and the plyer library, which will be used for alerting us about the timely notifications for the completion of the particular task at hand."
},
{
"code": null,
"e": 2990,
"s": 2661,
"text": "The following project is extremely simple for a beginner-level introduction to understanding Python and the basic concepts related to the subject. Despite its simplicity, it can be very useful for improving your overall productivity. The link provided guides you through the entire process of building this project from scratch."
},
{
"code": null,
"e": 3013,
"s": 2990,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3285,
"s": 3013,
"text": "The first project is fairly simple, and the estimated time to complete this project should range anywhere from 30 minutes to 2 hours, depending on the programmer’s interest and skill. However, the difficulty range from the next projects mentioned will gradually increase."
},
{
"code": null,
"e": 3719,
"s": 3285,
"text": "An important aspect of python and machine learning is understanding the math behind these concepts and knowing how some of the code in machine learning libraries. To have a better grasp of these concepts, it is essential to practice the ideas implemented in scientific modules like numpy and scikit-learn by ourselves. One such programming application is performing the matrix multiplication operation without using any ML libraries."
},
{
"code": null,
"e": 4056,
"s": 3719,
"text": "To perform this task, the main requirement is knowledge of how matrices works. The complete explanation and guide can be obtained from my article below. However, if you are just interested in the basic gist of this coding problem and want to try to solve this on your own, then use the next reference paragraphs to help you get started."
},
{
"code": null,
"e": 4079,
"s": 4056,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 4365,
"s": 4079,
"text": "My approach to this problem is going to be to take all the inputs from the user. These are the number of rows and columns of both the first and second matrix. Also, based on the number of rows and columns of each matrix, we will respectively fill the alternative positions accordingly."
},
{
"code": null,
"e": 4640,
"s": 4365,
"text": "The first step, before doing any matrix multiplication is to check if this operation between the two matrices is actually possible. This can be done by checking if the columns of the first matrix matches the shape of the rows in the second matrix. This can be formulated as:"
},
{
"code": null,
"e": 4695,
"s": 4640,
"text": "→ no. of columns in matrix 1 = no. of rows in matrix 2"
},
{
"code": null,
"e": 4857,
"s": 4695,
"text": "This should be a great starting point for you to get started. From here you can compute the problem statement with various ways by utilizing your own techniques."
},
{
"code": null,
"e": 5198,
"s": 4857,
"text": "The house price prediction is one of the best ways for a beginner to get started with various machine learning algorithms. The best part about trying out this project is that you can gain a superior understanding of the scikit-learn (also referred to as sklearn) library, which is an extremely significant module for Machine Learning tasks."
},
{
"code": null,
"e": 5645,
"s": 5198,
"text": "The scikit-learn module is one of the best tools for machine learning and predictive data analysis. It offers a wide range of pre-built algorithms such as logistic regression, support vector machines (SVM’s), classification algorithms like K-means clustering, and a ton more operations. This is the best way for beginners to get started with machine learning algorithms because of the simple and efficient tools that this module grants access to."
},
{
"code": null,
"e": 5940,
"s": 5645,
"text": "Using this module you can access The Boston Housing Dataset. The Boston Housing Dataset is a derived from information collected by the U.S. Census Service concerning housing in the area of Boston MA. The dataset is small in size with only 506 cases. The following describes the dataset columns:"
},
{
"code": null,
"e": 5977,
"s": 5940,
"text": "CRIM — per capita crime rate by town"
},
{
"code": null,
"e": 6047,
"s": 5977,
"text": "ZN — proportion of residential land zoned for lots over 25,000 sq.ft."
},
{
"code": null,
"e": 6105,
"s": 6047,
"text": "INDUS — proportion of non-retail business acres per town."
},
{
"code": null,
"e": 6180,
"s": 6105,
"text": "CHAS — Charles River dummy variable (1 if tract bounds river; 0 otherwise)"
},
{
"code": null,
"e": 6237,
"s": 6180,
"text": "NOX — nitric oxides concentration (parts per 10 million)"
},
{
"code": null,
"e": 6279,
"s": 6237,
"text": "RM — average number of rooms per dwelling"
},
{
"code": null,
"e": 6340,
"s": 6279,
"text": "AGE — proportion of owner-occupied units built prior to 1940"
},
{
"code": null,
"e": 6399,
"s": 6340,
"text": "DIS — weighted distances to five Boston employment centres"
},
{
"code": null,
"e": 6447,
"s": 6399,
"text": "RAD — index of accessibility to radial highways"
},
{
"code": null,
"e": 6494,
"s": 6447,
"text": "TAX — full-value property-tax rate per $10,000"
},
{
"code": null,
"e": 6532,
"s": 6494,
"text": "PTRATIO — pupil-teacher ratio by town"
},
{
"code": null,
"e": 6598,
"s": 6532,
"text": "B — 1000(Bk — 0.63)2 where Bk is the proportion of blacks by town"
},
{
"code": null,
"e": 6639,
"s": 6598,
"text": "LSTAT — % lower status of the population"
},
{
"code": null,
"e": 6694,
"s": 6639,
"text": "MEDV — Median value of owner-occupied homes in $1000's"
},
{
"code": null,
"e": 7126,
"s": 6694,
"text": "In the next few blocks of code, we will discuss how we can utilize this module to access the dataset as well as some of the additional libraries required for analyzing and solving this simple machine learning task. It will be a quick guide on how you can get started and will cover the basic requirement. After understanding these concepts, you should be able to implement some machine learning algorithms on the following dataset."
},
{
"code": null,
"e": 7505,
"s": 7126,
"text": "The first step is to import all the essential requirements for solving this task. It is recommended that you use the following modules while trying to implement the various machine learning algorithms. The block of code is a simple representation of some of the code lines that might be required to solve the task. (It is for trying a decision tree or a random forest approach.)"
},
{
"code": null,
"e": 7938,
"s": 7505,
"text": "After importing all the essential libraries required for performing this task, you can load the Boston dataset and proceed to assign separate variables for the data and the target variable. The price which is to be predicted is the target variable, while the other important features are the information of the dataset. This converts the problem into a machine learning prediction task. You can do this from the code provided below."
},
{
"code": null,
"e": 8092,
"s": 7938,
"text": "Finally, we can quickly visualize this data using the pandas data frame structure. This can be constructed from the simple code block as mentioned below."
},
{
"code": null,
"e": 8450,
"s": 8092,
"text": "The above image is a representation of the dataset. You can add the feature names for the respective columns if you like. However, this should be a good starting point for most beginners to get started. Kaggle and GitHub are your best friends for solving these machine learning tasks. Check out the Kaggle Website for further information from the link here."
},
{
"code": null,
"e": 8856,
"s": 8450,
"text": "Email spam, also referred to as junk email, is unsolicited messages sent in bulk by email (spamming). Email filtering is the processing of email to organize it according to specified criteria. The term can apply to the intervention of human intelligence, but most often refers to the automatic processing of incoming messages with anti-spam techniques — to outgoing emails as well as those being received."
},
{
"code": null,
"e": 9195,
"s": 8856,
"text": "Various Classification Algorithms can be used for completing the email spam detection task. The various machine learning algorithms like Naive Bayes, support vector machines, K-nearest neighbors, and random forests among many other algorithms can be used for filtering spam messages and classifying if the received email is a spam or not."
},
{
"code": null,
"e": 9376,
"s": 9195,
"text": "Advanced spam detection can be performed using techniques like neural networks or optical character recognition (OCR) which is also used by companies like Gmail for spam filtering."
},
{
"code": null,
"e": 9801,
"s": 9376,
"text": "Assume we have a dataset of 30,000 emails out of which some are classified as spam and some are classified as not spam. The machine learning model will be trained on the dataset. Once the training process is complete, we can test it with a mail that was not included in our training dataset. The machine learning model can make predictions on the following input and classify it correctly if the input e-mail is spam or not."
},
{
"code": null,
"e": 10178,
"s": 9801,
"text": "Various anti-spam techniques are used to prevent email spam (unsolicited bulk email). No technique is a complete solution to the spam problem, and each has trade-offs between incorrectly rejecting legitimate email (false positives) as opposed to not rejecting all spam (false negatives) — and the associated costs in time, effort, and cost of wrongfully obstructing good mail."
},
{
"code": null,
"e": 10623,
"s": 10178,
"text": "As an example, the Naive Bayes classifiers are a popular statistical technique of e-mail filtering. They typically use bag of words features to identify spam e-mail, an approach commonly used in text classification. Naive Bayes classifiers work by correlating the use of tokens (typically words, or sometimes other things), with spam and non-spam e-mails and then using Bayes’ theorem to calculate a probability that an email is or is not spam."
},
{
"code": null,
"e": 10926,
"s": 10623,
"text": "Naive Bayes spam filtering is a baseline technique for dealing with spam that can tailor itself to the email needs of individual users and give low false positive spam detection rates that are generally acceptable to users. It is one of the oldest ways of doing spam filtering, with roots in the 1990s."
},
{
"code": null,
"e": 10994,
"s": 10926,
"text": "A quick guide for the following can be obtained from the link here."
},
{
"code": null,
"e": 11267,
"s": 10994,
"text": "Sentiment analysis (also known as opinion mining or emotion AI) refers to the use of natural language processing, text analysis, computational linguistics, and biometrics to systematically identify, extract, quantify, and study affective states and subjective information."
},
{
"code": null,
"e": 11512,
"s": 11267,
"text": "Sentiment analysis is widely applied to voice of the customer materials such as reviews and survey responses, online and social media, and healthcare materials for applications that range from marketing to customer service to clinical medicine."
},
{
"code": null,
"e": 11894,
"s": 11512,
"text": "A basic task in sentiment analysis is classifying the polarity of a given text at the document, sentence, or feature/aspect level — whether the expressed opinion in a document, a sentence or an entity feature/aspect is positive, negative, or neutral. Advanced, “beyond polarity” sentiment classification looks, for instance, at emotional states such as “angry”, “sad”, and “happy”."
},
{
"code": null,
"e": 12161,
"s": 11894,
"text": "However, you can choose to negate the other reviews and only classify them as good or bad. For example, for a movie review, anything rated 1–2 stars is marked as negative, a rating of 4–5 is marked as positive, while a neutral rating of 3 can be ignored accordingly."
},
{
"code": null,
"e": 12420,
"s": 12161,
"text": "Solving the Sentiment Analysis problem is one of the best beginner-level projects for you to start with due to the wide range of options that you have available to solve the following task. You can choose any method that you prefer for solving this question."
},
{
"code": null,
"e": 12761,
"s": 12420,
"text": "Machine learning Algorithms like logistic and Naive Bayes can be easily used to solve such kinds of tasks. Many approaches can be used for obtaining a solution to this problem, including methods of deep learning. However, even the simplest methods can be used to solve this task, depending on how complicated you decide to make the problem."
},
{
"code": null,
"e": 13021,
"s": 12761,
"text": "My suggestion for detailed understanding of the concepts of natural language processing and sentiment analysis is the link here. You can audit the course if you like. I would also recommend checking out the article below for further information on this topic."
},
{
"code": null,
"e": 13044,
"s": 13021,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 13509,
"s": 13044,
"text": "The outdated GIF you guys can see above is one of my first projects I ever did with the help of pygame about three years ago. If you want a more concise guide on how you can build this from scratch with python then do let me know. But the main idea here is to build a game with python from scratch on your own. Start off with something simple like a snake game, or tic-tac-toe, and proceed towards a more advanced one like flappy birds with reinforcement learning."
},
{
"code": null,
"e": 13917,
"s": 13509,
"text": "The idea behind accomplishing this task is more of personal opinion and preference. I believe that one of the best ways to get a good hold of any programming language is to start with a project that is fun and enjoyable. I am also a bit of a gaming nerd. To get started with gaming projects related to python, I would highly recommend the use of the Pygame library module for the execution of such programs."
},
{
"code": null,
"e": 14329,
"s": 13917,
"text": "With the pygame module, you can build some simple, fun games with python. However, don’t expect anything too fancy as it has its limitations. Regardless, it is a fantastic way to get started, and below is the starter code to dive in. Just install pygame with a simple pip command and then use the following import pygame command. The following message will greet you upon the successful importing of the module."
},
{
"code": null,
"e": 14413,
"s": 14329,
"text": "pygame 1.9.6Hello from the pygame community. https://www.pygame.org/contribute.html"
},
{
"code": null,
"e": 14735,
"s": 14413,
"text": "The versions might differ depending on the time on installation, so don’t worry too much. Just use the updated versions always in any scenario. I will go over some basic commands you should know and how they work. Below is the complete code block for all the important aspects you need to know to get started with pygame."
},
{
"code": null,
"e": 15198,
"s": 14735,
"text": "#imports the pygame library moduleimport pygame# initilize the pygame modulepygame.init()# Setting your screen size with a tuple of the screen width and screen heightdisplay_screen = pygame.display.set_mode((800,600)) # Setting a random caption title for your pygame graphical window.pygame.display.set_caption(\"pygame test\")# Update your screen when requiredpygame.display.update()# quit the pygame initialization and modulepygame.quit()# End the programquit()"
},
{
"code": null,
"e": 15450,
"s": 15198,
"text": "I would highly recommend you check out some YouTube videos for better understanding and learning to build some games. The documentation for the pygame module, albeit a little lengthy, is probably one the best resources to learn more about this module."
},
{
"code": null,
"e": 15718,
"s": 15450,
"text": "Computer vision is an interdisciplinary scientific field that deals with how computers can gain high-level understanding from digital images or videos. From the perspective of engineering, it seeks to understand and automate tasks that the human visual system can do."
},
{
"code": null,
"e": 16067,
"s": 15718,
"text": "RGB are the 3 most significant layers of coloring for computer vision tasks. The composition of these three colors, namely red, green, and blue can be used to compose almost any other color. Mixing them in the right proportion allows us to frame any other desired color. This concept has existed since the cathode ray televisions a few decades ago."
},
{
"code": null,
"e": 16387,
"s": 16067,
"text": "Each of these colors has an 8 bit integer value. This means a matrix of these could range from 0 to 255. The reasoning for this is because 28 is 256 and 0–255 consist of 256 values. Each of these colors will have a value of this range and since we have a 3-Dimensional image, we can stack each of these upon each other."
},
{
"code": null,
"e": 16889,
"s": 16387,
"text": "OpenCV module is by far the best library for the execution of complex machine learning, deep learning, and computer vision tasks. It offers simplicity and high standards for the analysis and performance of the models being built. It is an open-source library and can be integrated with other python modules such as NumPy to accomplish complicated real-time applications. It is supported for a wide range of programming languages and runs remarkably on most platforms such as Windows, Linux, and MacOS."
},
{
"code": null,
"e": 17348,
"s": 16889,
"text": "Working and dealing with images is an essential aspect of computer vision projects for AI and Data Science. The reading, displaying, and writing of images is an essential part of computer vision as you have to consistently deal with images. The best part about opencv apart from the previously mentioned advantages is that it grants you access to a variety of image formats as well. So, we can work on all these image formats without facing any major issues."
},
{
"code": null,
"e": 17640,
"s": 17348,
"text": "The article link mentioned below is a concise guide to master the basics of computer vision from scratch. I have covered all the essential aspects for a beginner to get started and achieve an overall detailed understanding of the OpenCV module and how you can operate on a variety of images."
},
{
"code": null,
"e": 17663,
"s": 17640,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 17986,
"s": 17663,
"text": "The next intermediate level we will be focusing on is one of the coolest aspects of having python programming knowledge. Complicated tasks such as text-to-speech conversion and optical character recognition of python can be completed just with the help of understanding the python library modules created for this purpose."
},
{
"code": null,
"e": 18583,
"s": 17986,
"text": "The text-to-speech (TTS) is the process of converting words into a vocal audio form. The program, tool, or software takes an input text from the user, and using methods of natural language processing, understands the linguistics of the language being used, and performs logical inference on the text. This processed text is passed into the next block, where digital signal processing is performed on the processed text. With the use of the many algorithms and transformations, this processed text is finally converted into a speech format. This entire process involves the synthesizing of speech."
},
{
"code": null,
"e": 19073,
"s": 18583,
"text": "Optical Character Recognition is the conversion of 2-Dimensional text data into a form of machine-encoded text by the use of an electronic or mechanical device. The 2-Dimensional text data can be obtained from various sources such as scanned documents like PDF files, images with text data in formats such as .png or .jpeg, signposts like traffic posts, or any other images with any form of textual data. There is a wide range of interesting applications for optical character recognition."
},
{
"code": null,
"e": 19411,
"s": 19073,
"text": "Below is the list of two articles that will be extremely useful to get you acquainted with the Google Text-To-Speech module for speech translation and the pytesseract module for optical character recognition. Refer to these below articles for a comprehensive guide for getting started with them and perform a project using them together."
},
{
"code": null,
"e": 19434,
"s": 19411,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 19457,
"s": 19434,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 19840,
"s": 19457,
"text": "Face recognition is the procedural recognition of a human face along with the authorized name of the user. Face detection is a simpler task and can be considered as a beginner level project. Face detection is one of the steps that is required for face recognition. Face detection is a method of distinguishing the face of a human from the other parts of the body and the background."
},
{
"code": null,
"e": 20312,
"s": 19840,
"text": "The haar cascade classifier can be used for the purpose of face detection and accurately detect multiple faces in the frame. The haar cascade classifier for frontal face is usually an XML file that can be used with the open-cv module for reading the faces and then detecting the faces. A machine learning model such as the histogram of oriented gradients (H.O.G) which can be used with labeled data along with support vector machines (SVM’s) to perform this task as well."
},
{
"code": null,
"e": 20769,
"s": 20312,
"text": "The best approach for face recognition is to make use of the DNN’s (deep neural networks). After the detection of faces, we can use the approach of deep learning to solve face recognition tasks. There is a huge variety of transfer learning models like VGG-16 architecture, RESNET-50 architecture, face net architecture, etc. which can simplify the procedure to construct a deep learning model and allow users to build high-quality face recognition systems."
},
{
"code": null,
"e": 21118,
"s": 20769,
"text": "You can also build a custom deep learning model for solving the face recognition task. The modern models built for face recognition are highly accurate and provide an accuracy of almost over 99% for labeled datasets. The applications for the face recognition models can be used in security systems, surveillance, attendance systems, and a lot more."
},
{
"code": null,
"e": 21432,
"s": 21118,
"text": "Below is an example of a face recognition model built by me using the methods of VGG-16 transfer learning for face recognition after the face detection is performed by the haar cascade classifier. Check it out to learn a more detailed explanation of how exactly you can build your very own face recognition model."
},
{
"code": null,
"e": 21455,
"s": 21432,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 21828,
"s": 21455,
"text": "The link above is an example for a high accuracy face recognition system using deep learning with transfer learning methods to grant access to authorized users and deny permission to unaccredited personnel. Using methods of image data augmentation and transfer learning models, the face recognition model on the authorized user’s faces predicts with a high accuracy level."
},
{
"code": null,
"e": 22134,
"s": 21828,
"text": "A unique aspect of working on Data Science projects is the ability to create awesome predictive type models. The Google search bar, WhatsApp messages, etc., among many other applications, use the methodology of Next Word Prediction to predict the appropriate suggestion after each new word has been typed."
},
{
"code": null,
"e": 22471,
"s": 22134,
"text": "This is similar to Autocomplete, or word completion, which is a feature in which an application predicts the rest of a word a user is typing. In Android smartphones, this is called predictive text. In graphical user interfaces, users can typically press the tab key to accept a suggestion or the down arrow key to accept one of several."
},
{
"code": null,
"e": 22965,
"s": 22471,
"text": "This project idea is a fantastic choice for transitioning from intermediate-level projects to fairly advanced ones. This project idea uses major concepts of natural language processing and will require a decent amount of skill to solve. You can use a variety of machine learning algorithms and techniques to solve this task. However, I would recommend and encourage all of you to try out some innovative deep learning methods for solving this project while aiming to achieve top-notch results."
},
{
"code": null,
"e": 23430,
"s": 22965,
"text": "The next word prediction for a particular user’s texting or typing can be awesome. It would save a lot of time by understanding the user’s patterns of texting. This could be also used to create a bigger virtual assistant project to complete certain sentences. Overall, the predictive search system and next-word prediction is a very fun concept to implement. You can check out my article below, which covers the deep learning methodology to predict the next words."
},
{
"code": null,
"e": 23453,
"s": 23430,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 23909,
"s": 23453,
"text": "The resource mention above uses LSTM based deep learning model which takes an input word or sentence and predicts the next appropriate word. This deep learning model uses the concept of long short-term memory with natural language processing for the pre-processing of the corpus and text data. Uses a custom sequential model for the prediction of the appropriate next word. It has a wide array of applications in social media for the next word prediction."
},
{
"code": null,
"e": 24512,
"s": 23909,
"text": "This computer vision project could easily be considered a fairly advanced one but there are so many free tools and resources that are available that you could complete this task without any complications. The object detection task is the method of drawing a bounding box around the recognized object and identifying the recognized object according to the determined labels and predict these with specific accuracies. the object tracking is slightly different in comparison to the object detection, as you not only detect the particular object but also follow the object with the bounding box around it."
},
{
"code": null,
"e": 24973,
"s": 24512,
"text": "Object detection is a computer vision technique that allows us to identify and locate objects in an image or video. With this kind of identification and localization, object detection can be used to count objects in a scene and determine and track their precise locations, all while accurately labeling them. An example of this can be either following a particular vehicle on a road path or tracking a ball in any sports game like golf, cricket, baseball, etc."
},
{
"code": null,
"e": 25229,
"s": 24973,
"text": "The various algorithms to perform these tasks are R-CNN’s (Region-based convolutional neural networks), SSD (single shot detector), and YOLO (you only look once) among many others. I am going to mention 2 of the best resources by two talented programmers."
},
{
"code": null,
"e": 25622,
"s": 25229,
"text": "One method is more so for embedded systems like the raspberry pi and the other one is for PC related real-time webcam object detection. These two below resources are some of the best ways to get started with object detection/object tracking and they have YouTube videos explaining them in detail as well. Please do check out these resources to gain a better understanding of object detection."
},
{
"code": null,
"e": 25633,
"s": 25622,
"text": "github.com"
},
{
"code": null,
"e": 25644,
"s": 25633,
"text": "github.com"
},
{
"code": null,
"e": 25983,
"s": 25644,
"text": "The demand for high-quality chatbots is increasing every day. The main reason why chatbots are so popular now is because they can provide automated responses about the website or a particular topic. They can answer frequently asked questions and help new users on the website by welcoming them and briefing them about the particular site."
},
{
"code": null,
"e": 26444,
"s": 25983,
"text": "A well-trained chatbot can even converse with the user similar to how a human assistant would. Chatbots are also able to engage in conversations and help the user perceive what the site is about while promoting the website or social media web page. They can also advertise and garner better interaction from the user. All these factors make chatbots extremely important for any small start-up or any big website as it saves a lot of human effort and resources."
},
{
"code": null,
"e": 26854,
"s": 26444,
"text": "Deep Learning algorithms with neural networks and natural language processing (NLP) are the most popular chatbot methods which are being used today. There are a lot of other machine learning algorithms also which can be used. In deep learning, more popularly LSTMs are used and the sequence to sequence models with attention is preferred. Below is an example of an innovative chatbot built by me from scratch."
},
{
"code": null,
"e": 26877,
"s": 26854,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 26976,
"s": 26877,
"text": "The resource mentioned above is for an Innovative Chatbot with 1-Dimensional Convolutional Layers."
},
{
"code": null,
"e": 27405,
"s": 26976,
"text": "A 1-Dimensional text classification-based chatbot that replies with sarcastic responses to commonly asked questions. This chatbot model is an integral component of the virtual assistant project that will respond to the user with witty responses and keep the user engaged in funny conversations. The chatbot model is also perfect for casual talks and appealing to a foreign audience. It also has a high-quality prediction system."
},
{
"code": null,
"e": 27612,
"s": 27405,
"text": "Machine translation, sometimes referred to by the abbreviation MT, is a sub-field of computational linguistics that investigates the use of software to translate text or speech from one language to another."
},
{
"code": null,
"e": 27981,
"s": 27612,
"text": "On a basic level, MT performs mechanical substitution of words in one language for words in another, but that alone rarely produces a good translation because recognition of whole phrases and their closest counterparts in the target language is needed. Not all words in one language have equivalent words in another language, and many words have more than one meaning."
},
{
"code": null,
"e": 28432,
"s": 27981,
"text": "These types of problems can be solved with AI and Data Science technologies. These usually work on concepts such as natural language processing, machine learning, and deep learning. A sequence to sequence (Seq2seq) mechanism with attention can be used to achieve higher accuracy and lower losses for these predictions. Seq2seq is a family of machine learning approaches used for language processing for applications that include language translation."
},
{
"code": null,
"e": 28956,
"s": 28432,
"text": "Seq2seq turns one sequence into another sequence. It does so by use of a recurrent neural network (RNN) or more often LSTM or GRU to avoid the problem of vanishing gradient. The context for each item is the output from the previous step. The primary components are one encoder and one decoder network. The encoder turns each item into a corresponding hidden vector containing the item and its context. The decoder reverses the process, turning the vector into an output item, using the previous output as the input context."
},
{
"code": null,
"e": 29391,
"s": 28956,
"text": "Zero-shot and one-shot learning methods even exist for natural language processing. The same methods can be used for better training of the model to improve the overall performance and avoid repeated training procedures which can be a really big hindrance in some real-life applications and scenarios. Hence, one-shot learning is a great alternative for deployment and working in other embedded systems with lower training capacities."
},
{
"code": null,
"e": 29760,
"s": 29391,
"text": "Machine Translation is an awesome advanced level project to try out and have fun with. A great resource for accomplishing this task is the official website of TensorFlow that deals with Neural machine translation with attention. They work on a toy dataset and provide great insides on how to perform the following complex problem. You can check out the link from here."
},
{
"code": null,
"e": 30035,
"s": 29760,
"text": "This project uses computer vision and deep learning to detect the various faces and classify the emotions of that particular face. Not only do the models classify the emotions but also detects and classifies the different hand gestures of the recognized fingers accordingly."
},
{
"code": null,
"e": 30310,
"s": 30035,
"text": "After distinguishing the human emotions or gestures a vocal response is provided by the trained model with the accurate prediction of the human emotion or gesture respectively. The best part about this project is the wide range of data set choices you have available to you."
},
{
"code": null,
"e": 30621,
"s": 30310,
"text": "The project is a fairly advanced computer vision task, which will be awesome to fit on your resume of widely accomplished projects. Working on this fabulous project will also provide you with some must needed experience to complete complicated and complex problems related to deep learning and computer vision."
},
{
"code": null,
"e": 31181,
"s": 30621,
"text": "The below links are a reference to one of the deep learning projects done by me by using methodologies of computer vision, data augmentation, and libraries such as TensorFlow and Keras to build deep learning models. I would highly recommend viewers to check the below 2-part series for a complete breakdown, analysis, and understanding of how to compute the following advanced computer vision task. Also, make sure to refer to the Google text-to-speech link provided in the previous section to understand how the vocal text conversion of text to speech works."
},
{
"code": null,
"e": 31204,
"s": 31181,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 31227,
"s": 31204,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 31636,
"s": 31227,
"text": "The links provided above represent a computer vision and deep learning model to recognize human emotions and gestures. The model also provides a vocal response and classifies the respective emotion or gesture accordingly. Uses deep learning technology with a custom-built sequential model to achieve high accuracy on human emotions, and transfer learning based on VGG-16 architecture for gesture recognition."
},
{
"code": null,
"e": 31999,
"s": 31636,
"text": "GANs developed and originated in 2014 by Ian Goodfellow, and his colleagues have gained immense popularity recently. GANs are perceived to be the future of deep learning with their amazing ability to create visuals and images that have never even existed. Generative Adversarial Networks are the current peak of deep learning with an exceedingly improving curve."
},
{
"code": null,
"e": 32378,
"s": 31999,
"text": "GANs are an undeniable future trend that will revolutionize artificial intelligence forever. GANs is a slightly complicated topic, and I will be covering it extensively in the upcoming article’s part by part. However, for the purpose of this post, it is essential to note that two networks, a generator, and a discriminator go to war against each other and have a small dispute."
},
{
"code": null,
"e": 32695,
"s": 32378,
"text": "The generator tries to create realistic fake images to bypass the elemental checking of the discriminator, while the role of the discriminator is to catch the fake copies. This cat and mouse chases leads to the development of unique samples that have never existed, and it is realistic, far beyond human imagination."
},
{
"code": null,
"e": 33122,
"s": 32695,
"text": "I am not going to mention any specific project with GANs as there is a wide variety of unique and awesome applications as well as other innovative projects you can create with them. The popularity of GANs is on the rise, and it can create new artistic and realistic images out of absolutely nothing. GANs are being even explored to generate music from various sub-fields and Genres. Hence, they are not limited to images only."
},
{
"code": null,
"e": 33523,
"s": 33122,
"text": "A famous example of Generative Adversarial Networks (GANs) can be observed from the website called “thispersondoesexist.com.” Upon refreshing or re-visiting this site, you will encounter new faces of individuals who actually don’t exist. This project is constructed and imagined by a type of GANs (generative adversarial network) called the StyleGAN2 (Dec 2019) developed by Karras et al. and Nvidia."
},
{
"code": null,
"e": 33808,
"s": 33523,
"text": "The construction of a variety of new projects with Python and Data Science will enable you to understand and grasp the concepts you have studied much better. The passion to build new applications with Python and Data Science is an important quality for being successful in this field."
},
{
"code": null,
"e": 34193,
"s": 33808,
"text": "Theoretical understanding of the intuition behind machine learning concepts and math for the various topics of data science is crucial. To appreciate the true beauty of data science, you need to try out lots of projects. The wide array of tasks and the problems you can solve are absolutely fantastic, which leads to a sense of accomplishment when you find their respective solutions."
},
{
"code": null,
"e": 34521,
"s": 34193,
"text": "However, you also need to know how you can implement the following projects in a real-life practical scenario. Don’t be afraid to get your hands dirty with some code and implement these projects on your own. Experiment with different parameters and try to achieve better solutions by trying out numerous algorithms and methods."
},
{
"code": null,
"e": 34895,
"s": 34521,
"text": "In this article, we discussed 15 awesome Python and Data Science projects that you can experiment with and try out. These ideas would fit perfectly for anyone’s resume as it includes a wide array of unique and cool projects that you have built. It will help you to improve your overall profile as well as help you in clearing the initial selection process more effectively."
},
{
"code": null,
"e": 35246,
"s": 34895,
"text": "With the implementation of these projects, you will also gain more practical knowledge and a deep understanding of the concepts that you work on. If you have any queries related to the topics discussed in this article, then feel free to let me know in the comments section below, and I will try to get back to you with a response as soon as possible."
},
{
"code": null,
"e": 35312,
"s": 35246,
"text": "Check out some of my other articles that you might enjoy reading!"
},
{
"code": null,
"e": 35335,
"s": 35312,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 35358,
"s": 35335,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 35381,
"s": 35358,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 35404,
"s": 35381,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 35427,
"s": 35404,
"text": "towardsdatascience.com"
}
] |
Play with an array | Practice | GeeksforGeeks
|
Given an unsorted array arr of size N, rearrange the elements of array such that number at the odd index is greater than the number at the previous even index. The task is to complete the function formatArray() which will return formatted array.
NOTE:
If the array formed is according to rules print 1, else 0.
Example 1:
Input:
n = 5
arr[] = {5, 4, 3, 2, 1}
Output:
1
Explanation:
The given array after modification
will be as such: 4 5 2 3 1.
Example 2:
Input:
n = 4
arr[] = {4, 3, 2, 1}
Output:
​1
User task:
Since this is a functional problem you don't have to worry about the input, you just have to complete the function formatArray(), which accepts array arr and its size
Constraints:
1 <= T <= 100
1 <= N <= 100
1 <= arr[i] <= 100
0
mayank180919991 week ago
vector<int> formatArray(vector<int> a,int n)
{
//add code here.
for(int i=0;i<n-1;i=i+2){
if(a[i]>a[i+1]){
swap(a[i],a[i+1]);
}
}
return a;
}
-1
akashmarkad22102 months ago
public int[] formatArray(int[] a,int n) { // add code here. Arrays.sort(a); return a;}
0
patelshivanshu20172 months ago
class GfG{public int[] formatArray(int[] a,int n) { // add code here. for(int i=1;i<n;i+=2){ if(a[i]<a[i-1]){ int temp=a[i]; a[i]=a[i-1]; a[i-1]=temp; } } return a;}}
0
swapniltayal4222 months ago
def formatArray(arr,n): # add code here for i in range(1, n ,2): if (arr[i-1] > arr[i]): arr[i-1], arr[i] = arr[i], arr[i-1] return arr
0
akasksingh0802 months ago
JAVA:
class GfG{public int[] formatArray(int[] a,int n) { // add code here. for(int i=1;i<n;i=i+2) { if(a[i]<a[i-1]) { swap(a,i,i-1); } } return a;} public static void swap(int[] a, int x, int y) { int temp = a[x]; a[x]=a[y]; a[y]=temp; }
}
0
nnamansingh3 months ago
Python code:
def formatArray(a,n): # add code here for i in range(1,n,2): if (a[i-1] > a[i]): a[i-1],a[i]=a[i],a[i-1] return a
0
shailendrarana8913 months ago
Java Code
------------
int temp; for (int i = 1; i < n ; i = (i + 2)) { if (a[i] < a[i - 1]) { temp = a[i]; a[i] = a[i - 1]; a[i - 1] = temp; } } return a;
0
bhavyarajwanshi993 months ago
for(int i=1;i<n;i=(i+2)){ if(a[i]<a[i-1]) swap(a[i-1],a[i]); } return a;
0
abhinavsinghbiz3 months ago
//Very naive to do this problem is to simply sort the given //unsorted array!
I have a question, can anybody tell me that why bubble sort do not work in this problem but Insertion sort does!?
Bubble sort gives Run Time error but Insertion sort does not.(Both having same TC:O(N))
Btw here is my Insertion sort that I used to solve this problem.
vector<int> formatArray(vector<int> A,int n){ int key, j; for (int i = 1; i <= n-1; i++) { key = A[i]; j = i-1; while(j>=0 && A[j] > key){ A[j+1] = A[j]; j--; } A[j+1] = key; } return A;}
+1
abhinavsinghbiz3 months ago
O(N),C++ Code with 0.0 time taken!
vector<int> formatArray(vector<int> a,int n){ for(int i=1;i<n;i=i+2){ /*Traversing the odd index only*/ if(!(a[i]>a[i-1])){ int temp=a[i]; a[i]=a[i-1]; a[i-1]=temp; } } return a;}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 484,
"s": 238,
"text": "Given an unsorted array arr of size N, rearrange the elements of array such that number at the odd index is greater than the number at the previous even index. The task is to complete the function formatArray() which will return formatted array."
},
{
"code": null,
"e": 549,
"s": 484,
"text": "NOTE:\nIf the array formed is according to rules print 1, else 0."
},
{
"code": null,
"e": 560,
"s": 549,
"text": "Example 1:"
},
{
"code": null,
"e": 686,
"s": 560,
"text": "Input:\nn = 5\narr[] = {5, 4, 3, 2, 1}\n\nOutput:\n1\nExplanation:\nThe given array after modification\nwill be as such: 4 5 2 3 1.\n\n"
},
{
"code": null,
"e": 697,
"s": 686,
"text": "Example 2:"
},
{
"code": null,
"e": 746,
"s": 697,
"text": "Input:\nn = 4\narr[] = {4, 3, 2, 1}\n\nOutput:\n​1"
},
{
"code": null,
"e": 926,
"s": 746,
"text": "User task:\nSince this is a functional problem you don't have to worry about the input, you just have to complete the function formatArray(), which accepts array arr and its size "
},
{
"code": null,
"e": 986,
"s": 926,
"text": "Constraints:\n1 <= T <= 100\n1 <= N <= 100\n1 <= arr[i] <= 100"
},
{
"code": null,
"e": 990,
"s": 988,
"text": "0"
},
{
"code": null,
"e": 1015,
"s": 990,
"text": "mayank180919991 week ago"
},
{
"code": null,
"e": 1209,
"s": 1015,
"text": "vector<int> formatArray(vector<int> a,int n)\n{\n//add code here.\n for(int i=0;i<n-1;i=i+2){\n if(a[i]>a[i+1]){\n swap(a[i],a[i+1]);\n }\n }\n return a;\n}"
},
{
"code": null,
"e": 1212,
"s": 1209,
"text": "-1"
},
{
"code": null,
"e": 1240,
"s": 1212,
"text": "akashmarkad22102 months ago"
},
{
"code": null,
"e": 1347,
"s": 1240,
"text": "public int[] formatArray(int[] a,int n) { // add code here. Arrays.sort(a); return a;}"
},
{
"code": null,
"e": 1349,
"s": 1347,
"text": "0"
},
{
"code": null,
"e": 1380,
"s": 1349,
"text": "patelshivanshu20172 months ago"
},
{
"code": null,
"e": 1639,
"s": 1380,
"text": "class GfG{public int[] formatArray(int[] a,int n) { // add code here. for(int i=1;i<n;i+=2){ if(a[i]<a[i-1]){ int temp=a[i]; a[i]=a[i-1]; a[i-1]=temp; } } return a;}}"
},
{
"code": null,
"e": 1641,
"s": 1639,
"text": "0"
},
{
"code": null,
"e": 1669,
"s": 1641,
"text": "swapniltayal4222 months ago"
},
{
"code": null,
"e": 1827,
"s": 1669,
"text": "def formatArray(arr,n): # add code here for i in range(1, n ,2): if (arr[i-1] > arr[i]): arr[i-1], arr[i] = arr[i], arr[i-1] return arr"
},
{
"code": null,
"e": 1829,
"s": 1827,
"text": "0"
},
{
"code": null,
"e": 1855,
"s": 1829,
"text": "akasksingh0802 months ago"
},
{
"code": null,
"e": 1862,
"s": 1855,
"text": "JAVA: "
},
{
"code": null,
"e": 2195,
"s": 1864,
"text": "class GfG{public int[] formatArray(int[] a,int n) { // add code here. for(int i=1;i<n;i=i+2) { if(a[i]<a[i-1]) { swap(a,i,i-1); } } return a;} public static void swap(int[] a, int x, int y) { int temp = a[x]; a[x]=a[y]; a[y]=temp; }"
},
{
"code": null,
"e": 2197,
"s": 2195,
"text": "}"
},
{
"code": null,
"e": 2199,
"s": 2197,
"text": "0"
},
{
"code": null,
"e": 2223,
"s": 2199,
"text": "nnamansingh3 months ago"
},
{
"code": null,
"e": 2236,
"s": 2223,
"text": "Python code:"
},
{
"code": null,
"e": 2372,
"s": 2236,
"text": "def formatArray(a,n): # add code here for i in range(1,n,2): if (a[i-1] > a[i]): a[i-1],a[i]=a[i],a[i-1] return a"
},
{
"code": null,
"e": 2374,
"s": 2372,
"text": "0"
},
{
"code": null,
"e": 2404,
"s": 2374,
"text": "shailendrarana8913 months ago"
},
{
"code": null,
"e": 2414,
"s": 2404,
"text": "Java Code"
},
{
"code": null,
"e": 2427,
"s": 2414,
"text": "------------"
},
{
"code": null,
"e": 2648,
"s": 2427,
"text": " int temp; for (int i = 1; i < n ; i = (i + 2)) { if (a[i] < a[i - 1]) { temp = a[i]; a[i] = a[i - 1]; a[i - 1] = temp; } } return a;"
},
{
"code": null,
"e": 2650,
"s": 2648,
"text": "0"
},
{
"code": null,
"e": 2680,
"s": 2650,
"text": "bhavyarajwanshi993 months ago"
},
{
"code": null,
"e": 2784,
"s": 2680,
"text": "for(int i=1;i<n;i=(i+2)){ if(a[i]<a[i-1]) swap(a[i-1],a[i]); } return a;"
},
{
"code": null,
"e": 2786,
"s": 2784,
"text": "0"
},
{
"code": null,
"e": 2814,
"s": 2786,
"text": "abhinavsinghbiz3 months ago"
},
{
"code": null,
"e": 2892,
"s": 2814,
"text": "//Very naive to do this problem is to simply sort the given //unsorted array!"
},
{
"code": null,
"e": 3006,
"s": 2892,
"text": "I have a question, can anybody tell me that why bubble sort do not work in this problem but Insertion sort does!?"
},
{
"code": null,
"e": 3094,
"s": 3006,
"text": "Bubble sort gives Run Time error but Insertion sort does not.(Both having same TC:O(N))"
},
{
"code": null,
"e": 3159,
"s": 3094,
"text": "Btw here is my Insertion sort that I used to solve this problem."
},
{
"code": null,
"e": 3407,
"s": 3159,
"text": "vector<int> formatArray(vector<int> A,int n){ int key, j; for (int i = 1; i <= n-1; i++) { key = A[i]; j = i-1; while(j>=0 && A[j] > key){ A[j+1] = A[j]; j--; } A[j+1] = key; } return A;}"
},
{
"code": null,
"e": 3410,
"s": 3407,
"text": "+1"
},
{
"code": null,
"e": 3438,
"s": 3410,
"text": "abhinavsinghbiz3 months ago"
},
{
"code": null,
"e": 3473,
"s": 3438,
"text": "O(N),C++ Code with 0.0 time taken!"
},
{
"code": null,
"e": 3707,
"s": 3473,
"text": "vector<int> formatArray(vector<int> a,int n){ for(int i=1;i<n;i=i+2){ /*Traversing the odd index only*/ if(!(a[i]>a[i-1])){ int temp=a[i]; a[i]=a[i-1]; a[i-1]=temp; } } return a;}"
},
{
"code": null,
"e": 3853,
"s": 3707,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 3889,
"s": 3853,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 3899,
"s": 3889,
"text": "\nProblem\n"
},
{
"code": null,
"e": 3909,
"s": 3899,
"text": "\nContest\n"
},
{
"code": null,
"e": 3972,
"s": 3909,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4120,
"s": 3972,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 4328,
"s": 4120,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 4434,
"s": 4328,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Go - Multidimensional Arrays in Go
|
Go programming language allows multidimensional arrays. Here is the general form of a multidimensional array declaration −
var variable_name [SIZE1][SIZE2]...[SIZEN] variable_type
For example, the following declaration creates a three dimensional 5 . 10 . 4 integer array −
var threedim [5][10][4]int
A two-dimensional array is the simplest form of a multidimensional array. A two-dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array of size [x, y], you would write something as follows −
var arrayName [ x ][ y ] variable_type
Where variable_type can be any valid Go data type and arrayName will be a valid Go identifier. A two-dimensional array can be think as a table which will have x number of rows and y number of columns. A 2-dimensional array a, which contains three rows and four columns can be shown as below −
Thus, every element in the array a is identified by an element name of the form a[ i ][ j ], where a is the name of the array, and i and j are the subscripts that uniquely identify each element in a.
Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is an array with 3 rows and each row has 4 columns.
a = [3][4]int{
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
}
An element in two dimensional array is accessed by using the subscripts, i.e., row index and column index of the array. For example −
int val = a[2][3]
The above statement will take the 4th element from the 3rd row of the array. You can verify it in the above diagram. Let us check below program where we have used nested loop to handle a two dimensional array −
package main
import "fmt"
func main() {
/* an array with 5 rows and 2 columns*/
var a = [5][2]int{ {0,0}, {1,2}, {2,4}, {3,6},{4,8}}
var i, j int
/* output each array element's value */
for i = 0; i < 5; i++ {
for j = 0; j < 2; j++ {
fmt.Printf("a[%d][%d] = %d\n", i,j, a[i][j] )
}
}
}
When the above code is compiled and executed, it produces the following result −
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
As explained above, you can have arrays with any number of dimensions, although it is likely that most of the arrays you create will be of one or two dimensions.
64 Lectures
6.5 hours
Ridhi Arora
20 Lectures
2.5 hours
Asif Hussain
22 Lectures
4 hours
Dilip Padmanabhan
48 Lectures
6 hours
Arnab Chakraborty
7 Lectures
1 hours
Aditya Kulkarni
44 Lectures
3 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2060,
"s": 1937,
"text": "Go programming language allows multidimensional arrays. Here is the general form of a multidimensional array declaration −"
},
{
"code": null,
"e": 2118,
"s": 2060,
"text": "var variable_name [SIZE1][SIZE2]...[SIZEN] variable_type\n"
},
{
"code": null,
"e": 2212,
"s": 2118,
"text": "For example, the following declaration creates a three dimensional 5 . 10 . 4 integer array −"
},
{
"code": null,
"e": 2240,
"s": 2212,
"text": "var threedim [5][10][4]int\n"
},
{
"code": null,
"e": 2486,
"s": 2240,
"text": "A two-dimensional array is the simplest form of a multidimensional array. A two-dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array of size [x, y], you would write something as follows −"
},
{
"code": null,
"e": 2526,
"s": 2486,
"text": "var arrayName [ x ][ y ] variable_type\n"
},
{
"code": null,
"e": 2819,
"s": 2526,
"text": "Where variable_type can be any valid Go data type and arrayName will be a valid Go identifier. A two-dimensional array can be think as a table which will have x number of rows and y number of columns. A 2-dimensional array a, which contains three rows and four columns can be shown as below −"
},
{
"code": null,
"e": 3020,
"s": 2819,
"text": "Thus, every element in the array a is identified by an element name of the form a[ i ][ j ], where a is the name of the array, and i and j are the subscripts that uniquely identify each element in a."
},
{
"code": null,
"e": 3170,
"s": 3020,
"text": "Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is an array with 3 rows and each row has 4 columns."
},
{
"code": null,
"e": 3372,
"s": 3170,
"text": "a = [3][4]int{ \n {0, 1, 2, 3} , /* initializers for row indexed by 0 */\n {4, 5, 6, 7} , /* initializers for row indexed by 1 */\n {8, 9, 10, 11} /* initializers for row indexed by 2 */\n}"
},
{
"code": null,
"e": 3506,
"s": 3372,
"text": "An element in two dimensional array is accessed by using the subscripts, i.e., row index and column index of the array. For example −"
},
{
"code": null,
"e": 3525,
"s": 3506,
"text": "int val = a[2][3]\n"
},
{
"code": null,
"e": 3736,
"s": 3525,
"text": "The above statement will take the 4th element from the 3rd row of the array. You can verify it in the above diagram. Let us check below program where we have used nested loop to handle a two dimensional array −"
},
{
"code": null,
"e": 4065,
"s": 3736,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n /* an array with 5 rows and 2 columns*/\n var a = [5][2]int{ {0,0}, {1,2}, {2,4}, {3,6},{4,8}}\n var i, j int\n\n /* output each array element's value */\n for i = 0; i < 5; i++ {\n for j = 0; j < 2; j++ {\n fmt.Printf(\"a[%d][%d] = %d\\n\", i,j, a[i][j] )\n }\n }\n}"
},
{
"code": null,
"e": 4146,
"s": 4065,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 4257,
"s": 4146,
"text": "a[0][0]: 0\na[0][1]: 0\na[1][0]: 1\na[1][1]: 2\na[2][0]: 2\na[2][1]: 4\na[3][0]: 3\na[3][1]: 6\na[4][0]: 4\na[4][1]: 8\n"
},
{
"code": null,
"e": 4419,
"s": 4257,
"text": "As explained above, you can have arrays with any number of dimensions, although it is likely that most of the arrays you create will be of one or two dimensions."
},
{
"code": null,
"e": 4454,
"s": 4419,
"text": "\n 64 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 4467,
"s": 4454,
"text": " Ridhi Arora"
},
{
"code": null,
"e": 4502,
"s": 4467,
"text": "\n 20 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4516,
"s": 4502,
"text": " Asif Hussain"
},
{
"code": null,
"e": 4549,
"s": 4516,
"text": "\n 22 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4568,
"s": 4549,
"text": " Dilip Padmanabhan"
},
{
"code": null,
"e": 4601,
"s": 4568,
"text": "\n 48 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4620,
"s": 4601,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4652,
"s": 4620,
"text": "\n 7 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4669,
"s": 4652,
"text": " Aditya Kulkarni"
},
{
"code": null,
"e": 4702,
"s": 4669,
"text": "\n 44 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 4721,
"s": 4702,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4728,
"s": 4721,
"text": " Print"
},
{
"code": null,
"e": 4739,
"s": 4728,
"text": " Add Notes"
}
] |
How to make custom dialog in android?
|
This example demonstrate about how to make custom dialog 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"
android:id="@+id/parent"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:gravity="center"
android:orientation="vertical">
<Button
android:id="@+id/customDialog"
android:text="Custom Dialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
In the above code, we have taken button. When user click on button, it will show custom dialog.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MainActivity extends AppCompatActivity {
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.customDialog).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
ViewGroup viewGroup = findViewById(android.R.id.content);
View dialogView = LayoutInflater.from(v.getContext()).inflate(R.layout.customview, viewGroup, false);
builder.setView(dialogView);
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
});
}
}
To show custom dialog we have inflated a view as custom view. so create customview.xml and add the following code -
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Success"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Headline" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla eu erat tincidunt lacus fermentum rutrum."
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Medium" />
<Button
android:id="@+id/buttonOk"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="15dp"
android:background="@color/colorPrimary"
android:text="Ok"
android:textColor="#FFF" />
</LinearLayout>
</LinearLayout>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
In the above result, it shown initial screen. Now click on button it will open custom dialog as shown below -
Click here to download the project code
|
[
{
"code": null,
"e": 1131,
"s": 1062,
"text": "This example demonstrate about how to make custom dialog in android."
},
{
"code": null,
"e": 1260,
"s": 1131,
"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": 1325,
"s": 1260,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1877,
"s": 1325,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:id=\"@+id/parent\"\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 android:gravity=\"center\"\n android:orientation=\"vertical\">\n <Button\n android:id=\"@+id/customDialog\"\n android:text=\"Custom Dialog\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n</LinearLayout>"
},
{
"code": null,
"e": 1973,
"s": 1877,
"text": "In the above code, we have taken button. When user click on button, it will show custom dialog."
},
{
"code": null,
"e": 2030,
"s": 1973,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3190,
"s": 2030,
"text": "package com.example.andy.myapplication;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AlertDialog;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\n\npublic class MainActivity extends AppCompatActivity {\n @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n findViewById(R.id.customDialog).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);\n ViewGroup viewGroup = findViewById(android.R.id.content);\n View dialogView = LayoutInflater.from(v.getContext()).inflate(R.layout.customview, viewGroup, false);\n builder.setView(dialogView);\n AlertDialog alertDialog = builder.create();\n alertDialog.show();\n }\n });\n }\n}"
},
{
"code": null,
"e": 3306,
"s": 3190,
"text": "To show custom dialog we have inflated a view as custom view. so create customview.xml and add the following code -"
},
{
"code": null,
"e": 4716,
"s": 3306,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\">\n <LinearLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:orientation=\"vertical\"\n android:padding=\"16dp\">\n <TextView\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:text=\"Success\"\n android:textAlignment=\"center\"\n android:textAppearance=\"@style/TextAppearance.AppCompat.Headline\" />\n <TextView\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"10dp\"\n android:text=\"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla eu erat tincidunt lacus fermentum rutrum.\"\n android:textAlignment=\"center\"\n android:textAppearance=\"@style/TextAppearance.AppCompat.Medium\" />\n <Button\n android:id=\"@+id/buttonOk\"\n android:layout_width=\"200dp\"\n android:layout_height=\"wrap_content\"\n android:layout_gravity=\"center\"\n android:layout_marginTop=\"15dp\"\n android:background=\"@color/colorPrimary\"\n android:text=\"Ok\"\n android:textColor=\"#FFF\" />\n </LinearLayout>\n</LinearLayout>"
},
{
"code": null,
"e": 5063,
"s": 4716,
"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": 5173,
"s": 5063,
"text": "In the above result, it shown initial screen. Now click on button it will open custom dialog as shown below -"
},
{
"code": null,
"e": 5213,
"s": 5173,
"text": "Click here to download the project code"
}
] |
Build kNN from scratch in Python. With k-Fold cross-validation (from... | by Chaitanya Krishna Kasaraneni | Towards Data Science
|
In this article, we shall understand how k-Nearest Neighbors (kNN) algorithm works and build kNN algorithm from ground up. We also shall evaluate our algorithm using the k-Fold cross-validation which is also developed from scratch.
After completing this tutorial you will know:
How to code the k-Nearest Neighbors algorithm step-by-step
How to use k-Nearest Neighbors to make a prediction for new data
How to code the k-Fold Cross Validation step-by-step
How to evaluate k-Nearest Neighbors on a real dataset using k-Fold Cross Validation
Prerequisites: Basic understanding of Python and the concept of classes and objects from Object-oriented Programming (OOP)
k-Nearest Neighbors, kNN for short, is a very simple but powerful technique used for making predictions. The principle behind kNN is to use “most similar historical examples to the new data.”
‘k’ is a number used to identify similar neighbors for the new data point.
The entire training dataset is initially stored. When predictions are required for new data, kNN considers the k-most similar neighbors (records) to decide where the new data point will belong to based on feature similarity.
Once we find the distance or similarity, we choose the top k closest records. After discovering k closest records, we make the prediction by returning the most common outcome or taking the average. As such, kNN can be used for classification or regression problems.
kNN algorithm doesn’t have a training phase. The model just holds the data until a prediction is required and does no work. For this reason, kNN is often referred to as a “lazy learning method”.
Choose a value for kFind the distance of the new point to each record of training dataGet the k-Nearest NeighborsFor classification problem, the new data point belongs to the class that most of the neighbors belong to. For regression problem, the prediction can be average or weighted average of the label of k-Nearest Neighbors
Choose a value for k
Find the distance of the new point to each record of training data
Get the k-Nearest Neighbors
For classification problem, the new data point belongs to the class that most of the neighbors belong to. For regression problem, the prediction can be average or weighted average of the label of k-Nearest Neighbors
You can follow along using the code available in my GitHub.
You can also install it by using:
pip install simple-kNN
GitHub repo for PyPI package version: https://github.com/chaitanyakasaraneni/simple-kNN
Choice of K has a drastic impact on the results we obtain from kNN. Better choose an odd number.
The next step is to calculate distance between two rows in a dataset.
Problem or data specific methods are used to calculate distance or similarity between two records. In general for tabular or vector data, Euclidean distance is considered as starting point. There are several other similarity or distance metrics such as Manhattan distance, Hamming distance, etc.
Euclidean distance is defined as the square root of the sum of squared distance (difference) between two points. It is also known as L2 norm.
Manhattan distance is the sum of the absolute values of the differences between two points
Hamming distance is used for categorical variables. In simple terms it tells us if the two categorical variables are same or not.
where ‘δ’ is used to check equality of the two elements.
In python, we create a separate class that holds the methods to calculate the distance between two vectors.
We shall utilize this class to find the nearest neighbors in the next step.
Neighbors for a piece of new data in the dataset are the top — k closest instances that we obtain using the distance metrics defined above.
To locate the neighbors for a new piece of data within a dataset we must first calculate the distance between each record in the dataset to the new piece of data. We can do this by creating an object for the distanceMetric class that we defined above.
Once distances are calculated, we must sort all of the records in the training dataset by their distance to the new data. We can then select the top k to return as the most similar neighbors.
We can do this by keeping track of the distance for each record in the dataset as a list, sort the list of lists by the distance and then retrieve the neighbors.
Now that we know how to get top k — neighbors from the dataset, we will use them to make predictions.
In this step, we shall use the top — k similar neighbors collected from training dataset to make predictions.
In the case of classification, we can return the most represented class among the neighbors.
We can achieve this by performing the max() function on the list of output values from the neighbors. Given a list of class values observed in the neighbors, the max() function takes a set of unique class values and calls the count on the list of class values for each class value in the set.
Below is the complete kNN class:
Now that we have our predictions, we need to evaluate the performance of our model. For this, we shall use k-Fold Cross Validation which is defined in the next part.
This technique involves randomly dividing the dataset into k-groups or folds of approximately equal size. The first fold is kept for testing and the model is trained on remaining k-1 folds.
There are many variants of k-Fold Cross Validation. You can read more about them here.
In out approach, after each fold, we calculate accuracy, and thus accuracy of k-Fold CV is computed by taking average of the accuracies over k-folds.
As a first step, we divide the dataset into k- folds.
Then for each fold in the k-folds, we perform kNN algorithm, get predictions and evaluate the performance using accuracy as evaluation metric.
The method to split the data into k-Folds:
The method for evaluation:
Both methods combined into a single class:
We can execute this by creating an object for k-Fold cross validation method and call the evaluate method as shown below.
kfcv = kFoldCV()kfcv.kFCVEvaluate(data, foldCount, neighborCount, distanceMetric)
The kfcv.kFCVEvaluate() then splits the data into the specified number of folds and evaluated kNN algorithm by considering top-k neighbors using the distanceMetric specified.
Examples and implementation can be seen in my GitHub repository.
In this blog, we have seen:
kNN algorithm
Some distance metrics used in kNN algorithm
Predictions using kNN algorithm
Evaluating kNN algorithm using kFold Cross validation
Hope you gained some knowledge reading this article. Please remember that this article is just an overview and my understanding of kNN algorithm and kFold Cross validation technique that I read from various online sources.
|
[
{
"code": null,
"e": 404,
"s": 172,
"text": "In this article, we shall understand how k-Nearest Neighbors (kNN) algorithm works and build kNN algorithm from ground up. We also shall evaluate our algorithm using the k-Fold cross-validation which is also developed from scratch."
},
{
"code": null,
"e": 450,
"s": 404,
"text": "After completing this tutorial you will know:"
},
{
"code": null,
"e": 509,
"s": 450,
"text": "How to code the k-Nearest Neighbors algorithm step-by-step"
},
{
"code": null,
"e": 574,
"s": 509,
"text": "How to use k-Nearest Neighbors to make a prediction for new data"
},
{
"code": null,
"e": 627,
"s": 574,
"text": "How to code the k-Fold Cross Validation step-by-step"
},
{
"code": null,
"e": 711,
"s": 627,
"text": "How to evaluate k-Nearest Neighbors on a real dataset using k-Fold Cross Validation"
},
{
"code": null,
"e": 834,
"s": 711,
"text": "Prerequisites: Basic understanding of Python and the concept of classes and objects from Object-oriented Programming (OOP)"
},
{
"code": null,
"e": 1026,
"s": 834,
"text": "k-Nearest Neighbors, kNN for short, is a very simple but powerful technique used for making predictions. The principle behind kNN is to use “most similar historical examples to the new data.”"
},
{
"code": null,
"e": 1101,
"s": 1026,
"text": "‘k’ is a number used to identify similar neighbors for the new data point."
},
{
"code": null,
"e": 1326,
"s": 1101,
"text": "The entire training dataset is initially stored. When predictions are required for new data, kNN considers the k-most similar neighbors (records) to decide where the new data point will belong to based on feature similarity."
},
{
"code": null,
"e": 1592,
"s": 1326,
"text": "Once we find the distance or similarity, we choose the top k closest records. After discovering k closest records, we make the prediction by returning the most common outcome or taking the average. As such, kNN can be used for classification or regression problems."
},
{
"code": null,
"e": 1787,
"s": 1592,
"text": "kNN algorithm doesn’t have a training phase. The model just holds the data until a prediction is required and does no work. For this reason, kNN is often referred to as a “lazy learning method”."
},
{
"code": null,
"e": 2116,
"s": 1787,
"text": "Choose a value for kFind the distance of the new point to each record of training dataGet the k-Nearest NeighborsFor classification problem, the new data point belongs to the class that most of the neighbors belong to. For regression problem, the prediction can be average or weighted average of the label of k-Nearest Neighbors"
},
{
"code": null,
"e": 2137,
"s": 2116,
"text": "Choose a value for k"
},
{
"code": null,
"e": 2204,
"s": 2137,
"text": "Find the distance of the new point to each record of training data"
},
{
"code": null,
"e": 2232,
"s": 2204,
"text": "Get the k-Nearest Neighbors"
},
{
"code": null,
"e": 2448,
"s": 2232,
"text": "For classification problem, the new data point belongs to the class that most of the neighbors belong to. For regression problem, the prediction can be average or weighted average of the label of k-Nearest Neighbors"
},
{
"code": null,
"e": 2508,
"s": 2448,
"text": "You can follow along using the code available in my GitHub."
},
{
"code": null,
"e": 2542,
"s": 2508,
"text": "You can also install it by using:"
},
{
"code": null,
"e": 2565,
"s": 2542,
"text": "pip install simple-kNN"
},
{
"code": null,
"e": 2653,
"s": 2565,
"text": "GitHub repo for PyPI package version: https://github.com/chaitanyakasaraneni/simple-kNN"
},
{
"code": null,
"e": 2750,
"s": 2653,
"text": "Choice of K has a drastic impact on the results we obtain from kNN. Better choose an odd number."
},
{
"code": null,
"e": 2820,
"s": 2750,
"text": "The next step is to calculate distance between two rows in a dataset."
},
{
"code": null,
"e": 3116,
"s": 2820,
"text": "Problem or data specific methods are used to calculate distance or similarity between two records. In general for tabular or vector data, Euclidean distance is considered as starting point. There are several other similarity or distance metrics such as Manhattan distance, Hamming distance, etc."
},
{
"code": null,
"e": 3258,
"s": 3116,
"text": "Euclidean distance is defined as the square root of the sum of squared distance (difference) between two points. It is also known as L2 norm."
},
{
"code": null,
"e": 3349,
"s": 3258,
"text": "Manhattan distance is the sum of the absolute values of the differences between two points"
},
{
"code": null,
"e": 3479,
"s": 3349,
"text": "Hamming distance is used for categorical variables. In simple terms it tells us if the two categorical variables are same or not."
},
{
"code": null,
"e": 3536,
"s": 3479,
"text": "where ‘δ’ is used to check equality of the two elements."
},
{
"code": null,
"e": 3644,
"s": 3536,
"text": "In python, we create a separate class that holds the methods to calculate the distance between two vectors."
},
{
"code": null,
"e": 3720,
"s": 3644,
"text": "We shall utilize this class to find the nearest neighbors in the next step."
},
{
"code": null,
"e": 3860,
"s": 3720,
"text": "Neighbors for a piece of new data in the dataset are the top — k closest instances that we obtain using the distance metrics defined above."
},
{
"code": null,
"e": 4112,
"s": 3860,
"text": "To locate the neighbors for a new piece of data within a dataset we must first calculate the distance between each record in the dataset to the new piece of data. We can do this by creating an object for the distanceMetric class that we defined above."
},
{
"code": null,
"e": 4304,
"s": 4112,
"text": "Once distances are calculated, we must sort all of the records in the training dataset by their distance to the new data. We can then select the top k to return as the most similar neighbors."
},
{
"code": null,
"e": 4466,
"s": 4304,
"text": "We can do this by keeping track of the distance for each record in the dataset as a list, sort the list of lists by the distance and then retrieve the neighbors."
},
{
"code": null,
"e": 4568,
"s": 4466,
"text": "Now that we know how to get top k — neighbors from the dataset, we will use them to make predictions."
},
{
"code": null,
"e": 4678,
"s": 4568,
"text": "In this step, we shall use the top — k similar neighbors collected from training dataset to make predictions."
},
{
"code": null,
"e": 4771,
"s": 4678,
"text": "In the case of classification, we can return the most represented class among the neighbors."
},
{
"code": null,
"e": 5064,
"s": 4771,
"text": "We can achieve this by performing the max() function on the list of output values from the neighbors. Given a list of class values observed in the neighbors, the max() function takes a set of unique class values and calls the count on the list of class values for each class value in the set."
},
{
"code": null,
"e": 5097,
"s": 5064,
"text": "Below is the complete kNN class:"
},
{
"code": null,
"e": 5263,
"s": 5097,
"text": "Now that we have our predictions, we need to evaluate the performance of our model. For this, we shall use k-Fold Cross Validation which is defined in the next part."
},
{
"code": null,
"e": 5453,
"s": 5263,
"text": "This technique involves randomly dividing the dataset into k-groups or folds of approximately equal size. The first fold is kept for testing and the model is trained on remaining k-1 folds."
},
{
"code": null,
"e": 5540,
"s": 5453,
"text": "There are many variants of k-Fold Cross Validation. You can read more about them here."
},
{
"code": null,
"e": 5690,
"s": 5540,
"text": "In out approach, after each fold, we calculate accuracy, and thus accuracy of k-Fold CV is computed by taking average of the accuracies over k-folds."
},
{
"code": null,
"e": 5744,
"s": 5690,
"text": "As a first step, we divide the dataset into k- folds."
},
{
"code": null,
"e": 5887,
"s": 5744,
"text": "Then for each fold in the k-folds, we perform kNN algorithm, get predictions and evaluate the performance using accuracy as evaluation metric."
},
{
"code": null,
"e": 5930,
"s": 5887,
"text": "The method to split the data into k-Folds:"
},
{
"code": null,
"e": 5957,
"s": 5930,
"text": "The method for evaluation:"
},
{
"code": null,
"e": 6000,
"s": 5957,
"text": "Both methods combined into a single class:"
},
{
"code": null,
"e": 6122,
"s": 6000,
"text": "We can execute this by creating an object for k-Fold cross validation method and call the evaluate method as shown below."
},
{
"code": null,
"e": 6204,
"s": 6122,
"text": "kfcv = kFoldCV()kfcv.kFCVEvaluate(data, foldCount, neighborCount, distanceMetric)"
},
{
"code": null,
"e": 6379,
"s": 6204,
"text": "The kfcv.kFCVEvaluate() then splits the data into the specified number of folds and evaluated kNN algorithm by considering top-k neighbors using the distanceMetric specified."
},
{
"code": null,
"e": 6444,
"s": 6379,
"text": "Examples and implementation can be seen in my GitHub repository."
},
{
"code": null,
"e": 6472,
"s": 6444,
"text": "In this blog, we have seen:"
},
{
"code": null,
"e": 6486,
"s": 6472,
"text": "kNN algorithm"
},
{
"code": null,
"e": 6530,
"s": 6486,
"text": "Some distance metrics used in kNN algorithm"
},
{
"code": null,
"e": 6562,
"s": 6530,
"text": "Predictions using kNN algorithm"
},
{
"code": null,
"e": 6616,
"s": 6562,
"text": "Evaluating kNN algorithm using kFold Cross validation"
}
] |
JSF - h:commandLink
|
The h:commandLink tag renders an HTML "anchor" element.
<h:commandLink value = "Page 1" action = "page1" />
<a href = "#" onclick = "mojarra.jsfcljs(document.getElementById('j_idt13'),
{'j_idt13:j_idt14':'j_idt13:j_idt14'},'');return false">Page 1</a>
id
Identifier for a component
binding
Reference to the component that can be used in a backing bean
rendered
A boolean; false suppresses rendering
styleClass
Cascading stylesheet (CSS) class name
value
A component’s value, typically a value binding
valueChangeListener
A method binding to a method that responds to value changes
converter
Converter class name
validator
Class name of a validator that’s created and attached to a component
required
A boolean; if true, requires a value to be entered in the associated field
Accesskey
A key, typically combined with a system-defined metakey, that gives focus to an element
accept
Comma-separated list of content types for a form
accept-charset
Comma- or space-separated list of character encodings for a form. The accept-charset attribute is specified with the JSF HTML attribute named acceptcharset.
Alt
Alternative text for nontextual elements such as images or applets
border
Pixel value for an element’s border width
charset
Character encoding for a linked resource
coords
Coordinates for an element whose shape is a rectangle, circle, or polygon
dir
Direction for text. Valid values are ltr (left to right) and rtl (right to left)
hreflang
Base language of a resource specified with the href attribute; hreflang may only be used with href.
lang
Base language of an element’s attributes and text
maxlength
Maximum number of characters for text fields
readonly
Read-only state of an input field; text can be selected in a readonly field but not edited
rel
Relationship between the current document and a link specified with the href attribute
rev
Reverse link from the anchor specified with href to the current document. The value of the attribute is a space-separated list of link types
size
Size of an input field
style
Inline style information
tabindex
Numerical value specifying a tab index
target
The name of a frame in which a document is opened
title
A title, used for accessibility, that describes an element. Visual browsers typically create tooltips for the title’s value
type
Type of a link; for example, stylesheet
width
Width of an element
onblur
Element loses focus
onchange
Element’s value changes
onclick
Mouse button is clicked over the element
ondblclick
Mouse button is double-clicked over the element
onfocus
Element receives focus
onkeydown
Key is pressed
onkeypress
Key is pressed and subsequently released
onkeyup
Key is released
onmousedown
Mouse button is pressed over the element
onmousemove
Mouse moves over the element
onmouseout
Mouse leaves the element’s area
onmouseover
Mouse moves onto an element
onmouseup
Mouse button is released
onreset
Form is reset
onselect
Text is selected in an input field
Let us create a test JSF application to test the above tag.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>JSF Tutorial!</title>
</head>
<body>
<h2>h:commandLink example</h2>
<hr />
<h:form>
<h:commandLink value = "Page 1" action = "page1" />
</h:form>
</body>
</html>
Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result.
37 Lectures
3.5 hours
Chaand Sheikh
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2008,
"s": 1952,
"text": "The h:commandLink tag renders an HTML \"anchor\" element."
},
{
"code": null,
"e": 2061,
"s": 2008,
"text": "<h:commandLink value = \"Page 1\" action = \"page1\" /> "
},
{
"code": null,
"e": 2210,
"s": 2061,
"text": "<a href = \"#\" onclick = \"mojarra.jsfcljs(document.getElementById('j_idt13'), \n {'j_idt13:j_idt14':'j_idt13:j_idt14'},'');return false\">Page 1</a>\n"
},
{
"code": null,
"e": 2213,
"s": 2210,
"text": "id"
},
{
"code": null,
"e": 2240,
"s": 2213,
"text": "Identifier for a component"
},
{
"code": null,
"e": 2248,
"s": 2240,
"text": "binding"
},
{
"code": null,
"e": 2310,
"s": 2248,
"text": "Reference to the component that can be used in a backing bean"
},
{
"code": null,
"e": 2319,
"s": 2310,
"text": "rendered"
},
{
"code": null,
"e": 2357,
"s": 2319,
"text": "A boolean; false suppresses rendering"
},
{
"code": null,
"e": 2368,
"s": 2357,
"text": "styleClass"
},
{
"code": null,
"e": 2406,
"s": 2368,
"text": "Cascading stylesheet (CSS) class name"
},
{
"code": null,
"e": 2412,
"s": 2406,
"text": "value"
},
{
"code": null,
"e": 2459,
"s": 2412,
"text": "A component’s value, typically a value binding"
},
{
"code": null,
"e": 2479,
"s": 2459,
"text": "valueChangeListener"
},
{
"code": null,
"e": 2539,
"s": 2479,
"text": "A method binding to a method that responds to value changes"
},
{
"code": null,
"e": 2549,
"s": 2539,
"text": "converter"
},
{
"code": null,
"e": 2570,
"s": 2549,
"text": "Converter class name"
},
{
"code": null,
"e": 2580,
"s": 2570,
"text": "validator"
},
{
"code": null,
"e": 2649,
"s": 2580,
"text": "Class name of a validator that’s created and attached to a component"
},
{
"code": null,
"e": 2658,
"s": 2649,
"text": "required"
},
{
"code": null,
"e": 2733,
"s": 2658,
"text": "A boolean; if true, requires a value to be entered in the associated field"
},
{
"code": null,
"e": 2743,
"s": 2733,
"text": "Accesskey"
},
{
"code": null,
"e": 2831,
"s": 2743,
"text": "A key, typically combined with a system-defined metakey, that gives focus to an element"
},
{
"code": null,
"e": 2838,
"s": 2831,
"text": "accept"
},
{
"code": null,
"e": 2887,
"s": 2838,
"text": "Comma-separated list of content types for a form"
},
{
"code": null,
"e": 2902,
"s": 2887,
"text": "accept-charset"
},
{
"code": null,
"e": 3059,
"s": 2902,
"text": "Comma- or space-separated list of character encodings for a form. The accept-charset attribute is specified with the JSF HTML attribute named acceptcharset."
},
{
"code": null,
"e": 3063,
"s": 3059,
"text": "Alt"
},
{
"code": null,
"e": 3130,
"s": 3063,
"text": "Alternative text for nontextual elements such as images or applets"
},
{
"code": null,
"e": 3137,
"s": 3130,
"text": "border"
},
{
"code": null,
"e": 3179,
"s": 3137,
"text": "Pixel value for an element’s border width"
},
{
"code": null,
"e": 3187,
"s": 3179,
"text": "charset"
},
{
"code": null,
"e": 3228,
"s": 3187,
"text": "Character encoding for a linked resource"
},
{
"code": null,
"e": 3235,
"s": 3228,
"text": "coords"
},
{
"code": null,
"e": 3309,
"s": 3235,
"text": "Coordinates for an element whose shape is a rectangle, circle, or polygon"
},
{
"code": null,
"e": 3313,
"s": 3309,
"text": "dir"
},
{
"code": null,
"e": 3394,
"s": 3313,
"text": "Direction for text. Valid values are ltr (left to right) and rtl (right to left)"
},
{
"code": null,
"e": 3403,
"s": 3394,
"text": "hreflang"
},
{
"code": null,
"e": 3503,
"s": 3403,
"text": "Base language of a resource specified with the href attribute; hreflang may only be used with href."
},
{
"code": null,
"e": 3508,
"s": 3503,
"text": "lang"
},
{
"code": null,
"e": 3558,
"s": 3508,
"text": "Base language of an element’s attributes and text"
},
{
"code": null,
"e": 3568,
"s": 3558,
"text": "maxlength"
},
{
"code": null,
"e": 3613,
"s": 3568,
"text": "Maximum number of characters for text fields"
},
{
"code": null,
"e": 3622,
"s": 3613,
"text": "readonly"
},
{
"code": null,
"e": 3713,
"s": 3622,
"text": "Read-only state of an input field; text can be selected in a readonly field but not edited"
},
{
"code": null,
"e": 3717,
"s": 3713,
"text": "rel"
},
{
"code": null,
"e": 3804,
"s": 3717,
"text": "Relationship between the current document and a link specified with the href attribute"
},
{
"code": null,
"e": 3808,
"s": 3804,
"text": "rev"
},
{
"code": null,
"e": 3949,
"s": 3808,
"text": "Reverse link from the anchor specified with href to the current document. The value of the attribute is a space-separated list of link types"
},
{
"code": null,
"e": 3954,
"s": 3949,
"text": "size"
},
{
"code": null,
"e": 3977,
"s": 3954,
"text": "Size of an input field"
},
{
"code": null,
"e": 3983,
"s": 3977,
"text": "style"
},
{
"code": null,
"e": 4008,
"s": 3983,
"text": "Inline style information"
},
{
"code": null,
"e": 4017,
"s": 4008,
"text": "tabindex"
},
{
"code": null,
"e": 4056,
"s": 4017,
"text": "Numerical value specifying a tab index"
},
{
"code": null,
"e": 4063,
"s": 4056,
"text": "target"
},
{
"code": null,
"e": 4113,
"s": 4063,
"text": "The name of a frame in which a document is opened"
},
{
"code": null,
"e": 4119,
"s": 4113,
"text": "title"
},
{
"code": null,
"e": 4243,
"s": 4119,
"text": "A title, used for accessibility, that describes an element. Visual browsers typically create tooltips for the title’s value"
},
{
"code": null,
"e": 4248,
"s": 4243,
"text": "type"
},
{
"code": null,
"e": 4288,
"s": 4248,
"text": "Type of a link; for example, stylesheet"
},
{
"code": null,
"e": 4294,
"s": 4288,
"text": "width"
},
{
"code": null,
"e": 4314,
"s": 4294,
"text": "Width of an element"
},
{
"code": null,
"e": 4321,
"s": 4314,
"text": "onblur"
},
{
"code": null,
"e": 4341,
"s": 4321,
"text": "Element loses focus"
},
{
"code": null,
"e": 4350,
"s": 4341,
"text": "onchange"
},
{
"code": null,
"e": 4374,
"s": 4350,
"text": "Element’s value changes"
},
{
"code": null,
"e": 4382,
"s": 4374,
"text": "onclick"
},
{
"code": null,
"e": 4423,
"s": 4382,
"text": "Mouse button is clicked over the element"
},
{
"code": null,
"e": 4434,
"s": 4423,
"text": "ondblclick"
},
{
"code": null,
"e": 4482,
"s": 4434,
"text": "Mouse button is double-clicked over the element"
},
{
"code": null,
"e": 4490,
"s": 4482,
"text": "onfocus"
},
{
"code": null,
"e": 4513,
"s": 4490,
"text": "Element receives focus"
},
{
"code": null,
"e": 4523,
"s": 4513,
"text": "onkeydown"
},
{
"code": null,
"e": 4538,
"s": 4523,
"text": "Key is pressed"
},
{
"code": null,
"e": 4549,
"s": 4538,
"text": "onkeypress"
},
{
"code": null,
"e": 4590,
"s": 4549,
"text": "Key is pressed and subsequently released"
},
{
"code": null,
"e": 4598,
"s": 4590,
"text": "onkeyup"
},
{
"code": null,
"e": 4614,
"s": 4598,
"text": "Key is released"
},
{
"code": null,
"e": 4626,
"s": 4614,
"text": "onmousedown"
},
{
"code": null,
"e": 4667,
"s": 4626,
"text": "Mouse button is pressed over the element"
},
{
"code": null,
"e": 4679,
"s": 4667,
"text": "onmousemove"
},
{
"code": null,
"e": 4708,
"s": 4679,
"text": "Mouse moves over the element"
},
{
"code": null,
"e": 4719,
"s": 4708,
"text": "onmouseout"
},
{
"code": null,
"e": 4751,
"s": 4719,
"text": "Mouse leaves the element’s area"
},
{
"code": null,
"e": 4763,
"s": 4751,
"text": "onmouseover"
},
{
"code": null,
"e": 4791,
"s": 4763,
"text": "Mouse moves onto an element"
},
{
"code": null,
"e": 4801,
"s": 4791,
"text": "onmouseup"
},
{
"code": null,
"e": 4826,
"s": 4801,
"text": "Mouse button is released"
},
{
"code": null,
"e": 4834,
"s": 4826,
"text": "onreset"
},
{
"code": null,
"e": 4848,
"s": 4834,
"text": "Form is reset"
},
{
"code": null,
"e": 4857,
"s": 4848,
"text": "onselect"
},
{
"code": null,
"e": 4892,
"s": 4857,
"text": "Text is selected in an input field"
},
{
"code": null,
"e": 4952,
"s": 4892,
"text": "Let us create a test JSF application to test the above tag."
},
{
"code": null,
"e": 5362,
"s": 4952,
"text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\">\n <head>\n <title>JSF Tutorial!</title>\n </head>\n \n <body>\n <h2>h:commandLink example</h2>\n <hr />\n \n <h:form>\n <h:commandLink value = \"Page 1\" action = \"page1\" />\n </h:form>\n </body>\n</html>"
},
{
"code": null,
"e": 5578,
"s": 5362,
"text": "Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result."
},
{
"code": null,
"e": 5613,
"s": 5578,
"text": "\n 37 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5628,
"s": 5613,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 5635,
"s": 5628,
"text": " Print"
},
{
"code": null,
"e": 5646,
"s": 5635,
"text": " Add Notes"
}
] |
Getting Selenium to pause for X seconds.
|
We can get Selenium to pause for X seconds with the concept of synchronization. There are two types of waits − implicit and explicit. Apart from this there is the Thread.sleep method that halts Selenium for a certain time. The wait time is passed as an argument to the method.
Code Implementation with Thread.sleep.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class ThreadWt{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.tutorialspoint.com/index.htm");
// identify element, enter text
WebElement n=driver.findElement(By.className("gsc-input"));
// wait of 200 ms applied
Thread.sleep(200);
n.sendKeys("Selenium");
driver.quit();
}
}
We can specify an implicit wait. It shall keep the driver to wait for a specific amount of time for an element to be available.
driver.manage().timeouts().implicitlyWait();
The implicit is a global wait applied to every element on the page and is dynamic in nature.
Code Implementation with implicit wait.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class ImplicitWt{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = "https://www.tutorialspoint.com/index.htm";
driver.get(url);
// wait of 5 seconds
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
// identify element, enter text
WebElement n=driver.findElement(By.className("gsc−input"));
n.sendKeys("Selenium");
driver.quit();
}
}
The explicit wait is also used and it is applied to a specific element on the page. It is a WebDriverWait that works in association with the Expected Condition class. It is also dynamic in nature.
Expected conditions for explicit waits are −
titleContains
titleContains
alertIsPresent
alertIsPresent
invisibilityOfElementLocated
invisibilityOfElementLocated
invisibilityOfElementWithText
invisibilityOfElementWithText
textToBePresentInElement
textToBePresentInElement
visibilityOfElementLocated
visibilityOfElementLocated
presenceOfAllElementsLocatedBy
presenceOfAllElementsLocatedBy
visibilityOf
visibilityOf
presenceOfElementLocated
presenceOfElementLocated
elementToBeClickable
elementToBeClickable
stalenessOf
stalenessOf
Code Implementation with explicit wait.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class ExpltWaits{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.tutorialspoint.com/index.htm");
// identify element and click()
driver.findElement(By.xpath("//*[text()='Library']")).click();
// expected condition - invisibility condition
WebDriverWait wt = new WebDriverWait(driver,5);
// invisibilityOfElementLocated condition
wt.until(ExpectedConditions.
invisibilityOfElementLocated(By.xpath("//*[@class='mui-btn']")));
driver.close();
}
}
|
[
{
"code": null,
"e": 1339,
"s": 1062,
"text": "We can get Selenium to pause for X seconds with the concept of synchronization. There are two types of waits − implicit and explicit. Apart from this there is the Thread.sleep method that halts Selenium for a certain time. The wait time is passed as an argument to the method."
},
{
"code": null,
"e": 1378,
"s": 1339,
"text": "Code Implementation with Thread.sleep."
},
{
"code": null,
"e": 2041,
"s": 1378,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\npublic class ThreadWt{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.get(\"https://www.tutorialspoint.com/index.htm\");\n // identify element, enter text\n WebElement n=driver.findElement(By.className(\"gsc-input\"));\n // wait of 200 ms applied\n Thread.sleep(200);\n n.sendKeys(\"Selenium\");\n driver.quit();\n }\n}"
},
{
"code": null,
"e": 2169,
"s": 2041,
"text": "We can specify an implicit wait. It shall keep the driver to wait for a specific amount of time for an element to be available."
},
{
"code": null,
"e": 2214,
"s": 2169,
"text": "driver.manage().timeouts().implicitlyWait();"
},
{
"code": null,
"e": 2307,
"s": 2214,
"text": "The implicit is a global wait applied to every element on the page and is dynamic in nature."
},
{
"code": null,
"e": 2347,
"s": 2307,
"text": "Code Implementation with implicit wait."
},
{
"code": null,
"e": 3114,
"s": 2347,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\npublic class ImplicitWt{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n String url = \"https://www.tutorialspoint.com/index.htm\";\n driver.get(url);\n // wait of 5 seconds\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n // identify element, enter text\n WebElement n=driver.findElement(By.className(\"gsc−input\"));\n n.sendKeys(\"Selenium\");\n driver.quit();\n }\n}"
},
{
"code": null,
"e": 3311,
"s": 3114,
"text": "The explicit wait is also used and it is applied to a specific element on the page. It is a WebDriverWait that works in association with the Expected Condition class. It is also dynamic in nature."
},
{
"code": null,
"e": 3356,
"s": 3311,
"text": "Expected conditions for explicit waits are −"
},
{
"code": null,
"e": 3370,
"s": 3356,
"text": "titleContains"
},
{
"code": null,
"e": 3384,
"s": 3370,
"text": "titleContains"
},
{
"code": null,
"e": 3399,
"s": 3384,
"text": "alertIsPresent"
},
{
"code": null,
"e": 3414,
"s": 3399,
"text": "alertIsPresent"
},
{
"code": null,
"e": 3443,
"s": 3414,
"text": "invisibilityOfElementLocated"
},
{
"code": null,
"e": 3472,
"s": 3443,
"text": "invisibilityOfElementLocated"
},
{
"code": null,
"e": 3502,
"s": 3472,
"text": "invisibilityOfElementWithText"
},
{
"code": null,
"e": 3532,
"s": 3502,
"text": "invisibilityOfElementWithText"
},
{
"code": null,
"e": 3557,
"s": 3532,
"text": "textToBePresentInElement"
},
{
"code": null,
"e": 3582,
"s": 3557,
"text": "textToBePresentInElement"
},
{
"code": null,
"e": 3609,
"s": 3582,
"text": "visibilityOfElementLocated"
},
{
"code": null,
"e": 3636,
"s": 3609,
"text": "visibilityOfElementLocated"
},
{
"code": null,
"e": 3667,
"s": 3636,
"text": "presenceOfAllElementsLocatedBy"
},
{
"code": null,
"e": 3698,
"s": 3667,
"text": "presenceOfAllElementsLocatedBy"
},
{
"code": null,
"e": 3711,
"s": 3698,
"text": "visibilityOf"
},
{
"code": null,
"e": 3724,
"s": 3711,
"text": "visibilityOf"
},
{
"code": null,
"e": 3749,
"s": 3724,
"text": "presenceOfElementLocated"
},
{
"code": null,
"e": 3774,
"s": 3749,
"text": "presenceOfElementLocated"
},
{
"code": null,
"e": 3795,
"s": 3774,
"text": "elementToBeClickable"
},
{
"code": null,
"e": 3816,
"s": 3795,
"text": "elementToBeClickable"
},
{
"code": null,
"e": 3828,
"s": 3816,
"text": "stalenessOf"
},
{
"code": null,
"e": 3840,
"s": 3828,
"text": "stalenessOf"
},
{
"code": null,
"e": 3880,
"s": 3840,
"text": "Code Implementation with explicit wait."
},
{
"code": null,
"e": 4873,
"s": 3880,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\nimport org.openqa.selenium.support.ui.ExpectedConditions;\nimport org.openqa.selenium.support.ui.WebDriverWait;\npublic class ExpltWaits{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.get(\"https://www.tutorialspoint.com/index.htm\");\n // identify element and click()\n driver.findElement(By.xpath(\"//*[text()='Library']\")).click();\n // expected condition - invisibility condition\n WebDriverWait wt = new WebDriverWait(driver,5);\n // invisibilityOfElementLocated condition\n wt.until(ExpectedConditions.\n invisibilityOfElementLocated(By.xpath(\"//*[@class='mui-btn']\")));\n driver.close();\n }\n}"
}
] |
Introduction to Retofit 2 in android | Set 1
|
17 Nov, 2021
I have divided it in 3 parts. I am assuming reader has basic knowledge of Android and java.
Introduction
Retrofit 2 is type-safe REST client build by square for Android and Java which intends to make it simpler to expand RESTful webservices. Retrofit 2 use OkHttp as the systems administration layer and is based over it. Retrofit naturally serializes the JSON reaction utilizing a POJO (PlainOldJavaObject) which must be characterized in cutting edge for the JSON Structure . To serialize JSON we require a converter to change over it into Gson first. Retrofit is much simpler than other libraries we don’t have to parse our json it directly returns objects but there is one disadvantage also it doesn’t provide support to loadimages from server but we can use picasso for the same. Now we should go for some practical implementation which will give better understanding to you.
Implementation
Step-1 : For using Retrofit in our android project firstly we have to add dependency in gradle file. For adding dependency open app/build.gradle file in your Android project and add the following lines inside it. Add these lines inside dependencies{}
compile'com.google.code.gson:gson:2.6.2'
compile'com.squareup.retrofit2:retrofit:2.0.2'
compile'com.squareup.retrofit2:converter-gson:2.0.2'
Step-2 : We should now add InternetPermission inside Manifestfile.Open the manifest.xml file and add the following line.
users-permission android:name="android.permission.INTERNET"
Step-3 : For retrieving data from the server using retrofit 2 we require a modelclass. We are going to make model class to retrieve data from the server.For making modelclass we should know how the json looks. Suppose our json looks something like this :
“current_page”:1, “data”: [ { “id”:1, “source”:”http:\/\/mhrd.gov.in\/sites\/upload_files\/mhrd\/files\/upload_document\/NSISGE-Scheme-Copy.pdf”, “name”:”National Scheme of Incentive to Girls for Secondary Education (NSIGSE)”, “sector”:”Education”, “government”:”Central”, “eligible_beneficiaries”:”Individual”, “requirements”:”i. Girls, who pass class VIII examination and enroll for class IX in State\/UT Government, Government-aided or local body schools.\nii. Girls should be below 16 years of age (as on 31st March) on joining class IX\niii. Girls studying in private un-aided schools and enrolled in schools run by Central Government like KVS, NVS and CBS affiliated Schools are excluded.”, “benefits”:”FD of Rs.3000 in the name of selected girls. The girls are entitled to withdraw the sum along with interest thereon on reaching 18 years of age and on passing 10th class examination.”, “how_to_apply”:”Contact Principal\/Headmaster of the School”, “profession”:””, “nationality”:””, “gender”:”Female”, “social_category”:[ “SC”, “ST”, “Girls from Kasturba Gandhi Balika Vidyalayas” ], “bpl”:””, “maximum_income”:””, “maximum_monthly_income”:””, “min_age”:14, “max_age”:18, “age_relaxation”:””, “qualification”:8, “employed”:””, “domicile”:””, “marital_status”:”Unmarried”, “parents_profession”:””, “person_with_disabilities”:””, “current_student”:”Yes”, “min_marks_in_previous_examination”:””, “religion”:””, “isDeleted”:”false”, “isLatest”:”false”, “isPopular”:”false”, “isHtml”:”false”, “state_url”:”http:\/\/161.202.178.14\/kalyani\/storage\/states\/AORGzbxjrB3zHhAyfs6zTqpt3pQhJsHRwSC4JVBs.png”, “sector_url”:”http:\/\/161.202.178.14\/kalyani\/storage\/sector\/lDASDAsje3BuWQYgaBCqKKWwkfKEuqIvVYp3dp53.png” }, .... ]”from”:1, “last_page”:75, “next_page_url”:”http:\/\/localhost:8081\/\/api\/v1\/search?page=2′′, “per_page”:10, “prev_page_url”:null, “to”:10, “total”:741
If you see the json you will realize that json contains different fields like source, stateurl, sectorurl, id, name, sector, government, id, name, sector, government, eligibleBeneficiarieand etc for all the fields we have created getter setter and used parcelable(https://developer.android.com/reference/android/os/Parcelable.html).Here is the code for model class please read it for better understanding.
java
import android.os.Parcel;import android.os.Parcelable; import com.google.gson.annotations.Expose;import com.google.gson.annotations.SerializedName; public class Scheme implements Parcelable { public static final Creator<Scheme> CREATOR = new Creator<Scheme> ( ) { @Override public Scheme createFromParcel ( Parcel source ) { return new Scheme ( source ); } @Override public Scheme[] newArray ( int size ) { return new Scheme[size]; } }; @SerializedName("source") @Expose private String source; @SerializedName("state_url") @Expose private String stateurl; @SerializedName("sector_url") @Expose private String sectorurl; @SerializedName("id") @Expose private Integer id; @SerializedName("name") @Expose private String name; @SerializedName("sector") @Expose private String sector; @SerializedName("government") @Expose private String government; @SerializedName("eligible_beneficiaries") @Expose private String eligibleBeneficiaries; @SerializedName("maximum_income") @Expose private String income; @SerializedName("social_category") @Expose private String[] socialCategory; @SerializedName("religion") @Expose private String religion; @SerializedName("requirements") @Expose private String requirements; @SerializedName("benefits") @Expose private String benefits; @SerializedName("how_to_apply") @Expose private String howToApply; @SerializedName("gender") @Expose private String gender; @SerializedName("min_age") @Expose private Integer minAge; @SerializedName("max_age") @Expose private Integer maxAge; @SerializedName("qualification") @Expose private String qualification; @SerializedName("marital_status") @Expose private String maritalStatus; @SerializedName("bpl") @Expose private String bpl; @SerializedName("disability") @Expose private String disability; public Scheme ( ) { } protected Scheme ( Parcel in ) { this.source = in.readString ( ); this.stateurl = in.readString ( ); this.sectorurl = in.readString ( ); this.id = (Integer) in.readValue ( Integer.class.getClassLoader ( ) ); this.name = in.readString ( ); this.sector = in.readString ( ); this.government = in.readString ( ); this.eligibleBeneficiaries = in.readString ( ); this.income = in.readString ( ); this.socialCategory = in.createStringArray ( ); this.religion = in.readString ( ); this.requirements = in.readString ( ); this.benefits = in.readString ( ); this.howToApply = in.readString ( ); this.gender = in.readString ( ); this.minAge = (Integer) in.readValue ( Integer.class.getClassLoader ( ) ); this.maxAge = (Integer) in.readValue ( Integer.class.getClassLoader ( ) ); this.qualification = in.readString ( ); this.maritalStatus = in.readString ( ); this.bpl = in.readString ( ); this.disability = in.readString ( ); } public String getBpl ( ) { return bpl; } public void setBpl ( String bpl ) { this.bpl = bpl; } public String getDisability ( ) { return disability; } public void setDisability ( String disability ) { this.disability = disability; } public String getStateurl ( ) { return stateurl; } public void setStateurl ( String stateurl ) { this.stateurl = stateurl; } public String getSectorurl ( ) { return sectorurl; } public void setSectorurl ( String sectorurl ) { this.sectorurl = sectorurl; } public String getIncome ( ) { return income; } public void setIncome ( String income ) { this.income = income; } public String[] getSocialCategory ( ) { return socialCategory; } public void setSocialCategory ( String[] socialCategory ) { this.socialCategory = socialCategory; } public String getReligion ( ) { return religion; } public void setReligion ( String religion ) { this.religion = religion; } public String getRequirements ( ) { return requirements; } public void setRequirements ( String requirements ) { this.requirements = requirements; } public String getSource ( ) { return source; } public void setSource ( String source ) { this.source = source; } public Integer getId ( ) { return id; } public void setId ( Integer id ) { this.id = id; } public String getName ( ) { return name; } public void setName ( String name ) { this.name = name; } public String getSector ( ) { return sector; } public void setSector ( String sector ) { this.sector = sector; } public String getGovernment ( ) { return government; } public void setGovernment ( String government ) { this.government = government; } public String getEligibleBeneficiaries ( ) { return eligibleBeneficiaries; } public void setEligibleBeneficiaries ( String eligibleBeneficiaries ) { this.eligibleBeneficiaries = eligibleBeneficiaries; } public String getBenefits ( ) { return benefits; } public void setBenefits ( String benefits ) { this.benefits = benefits; } public String getHowToApply ( ) { return howToApply; } public void setHowToApply ( String howToApply ) { this.howToApply = howToApply; } public String getGender ( ) { return gender; } public void setGender ( String gender ) { this.gender = gender; } public Integer getMinAge ( ) { return minAge; } public void setMinAge ( Integer minAge ) { this.minAge = minAge; } public Integer getMaxAge ( ) { return maxAge; } public void setMaxAge ( Integer maxAge ) { this.maxAge = maxAge; } public String getQualification ( ) { return qualification; } public void setQualification ( String qualification ) { this.qualification = qualification; } public String getMaritalStatus ( ) { return maritalStatus; } public void setMaritalStatus ( String maritalStatus ) { this.maritalStatus = maritalStatus; } public String getSocialCategoryString(){ if(socialCategory != null && socialCategory.length > 0){ return android.text.TextUtils.join(",", socialCategory); } return null; } @Override public int describeContents ( ) { return 0; } @Override public void writeToParcel ( Parcel dest, int flags ) { dest.writeString ( this.source ); dest.writeString ( this.stateurl ); dest.writeString ( this.sectorurl ); dest.writeValue ( this.id ); dest.writeString ( this.name ); dest.writeString ( this.sector ); dest.writeString ( this.government ); dest.writeString ( this.eligibleBeneficiaries ); dest.writeString ( this.income ); dest.writeStringArray ( this.socialCategory ); dest.writeString ( this.religion ); dest.writeString ( this.requirements ); dest.writeString ( this.benefits ); dest.writeString ( this.howToApply ); dest.writeString ( this.gender ); dest.writeValue ( this.minAge ); dest.writeValue ( this.maxAge ); dest.writeString ( this.qualification ); dest.writeString ( this.maritalStatus ); dest.writeString ( this.bpl ); dest.writeString ( this.disability ); }}
You must have observed that we have used pagination in json (we are retrieving data in a set of 10).For handling this pagination we will create one more java file.Here is the code for pagination please read it for better understanding.
java
import android.os.Parcel;import android.os.Parcelable; import com.google.gson.annotations.Expose;import com.google.gson.annotations.SerializedName; import java.util.ArrayList; public class Page implements Parcelable { public static final Creator<Page> CREATOR = new Creator<Page> ( ) { @Override public Page createFromParcel ( Parcel source ) { return new Page ( source ); } @Override public Page[] newArray ( int size ) { return new Page[size]; } }; @SerializedName("current_page") @Expose private Integer currentPage; @SerializedName("data") @Expose private ArrayList<Scheme> data = null; @SerializedName("from") @Expose private Integer from; @SerializedName("last_page") @Expose private Integer lastPage; @SerializedName("next_page_url") @Expose private String nextPageUrl; @SerializedName("path") @Expose private String path; @SerializedName("per_page") @Expose private Integer perPage; @SerializedName("prev_page_url") @Expose private String prevPageUrl; @SerializedName("to") @Expose private Integer to; @SerializedName("total") @Expose private Integer total; public Page ( ) { } protected Page ( Parcel in ) { this.currentPage = (Integer) in.readValue ( Integer.class.getClassLoader ( ) ); this.data = in.createTypedArrayList ( Scheme.CREATOR ); this.from = (Integer) in.readValue ( Integer.class.getClassLoader ( ) ); this.lastPage = (Integer) in.readValue ( Integer.class.getClassLoader ( ) ); this.nextPageUrl = in.readString ( ); this.path = in.readString ( ); this.perPage = (Integer) in.readValue ( Integer.class.getClassLoader ( ) ); this.prevPageUrl = in.readString ( ); this.to = (Integer) in.readValue ( Integer.class.getClassLoader ( ) ); this.total = (Integer) in.readValue ( Integer.class.getClassLoader ( ) ); } public Integer getCurrentPage() { return currentPage; } public void setCurrentPage(Integer currentPage) { this.currentPage = currentPage; } public ArrayList<Scheme> getData ( ) { return data; } public void setData ( ArrayList<Scheme> data ) { this.data = data; } public Integer getFrom() { return from; } public void setFrom(Integer from) { this.from = from; } public Integer getLastPage() { return lastPage; } public void setLastPage(Integer lastPage) { this.lastPage = lastPage; } public String getNextPageUrl() { return nextPageUrl; } public void setNextPageUrl(String nextPageUrl) { this.nextPageUrl = nextPageUrl; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public Integer getPerPage() { return perPage; } public void setPerPage(Integer perPage) { this.perPage = perPage; } public String getPrevPageUrl ( ) { return prevPageUrl; } public void setPrevPageUrl ( String prevPageUrl ) { this.prevPageUrl = prevPageUrl; } public Integer getTo() { return to; } public void setTo(Integer to) { this.to = to; } public Integer getTotal() { return total; } public void setTotal(Integer total) { this.total = total; } @Override public int describeContents ( ) { return 0; } @Override public void writeToParcel ( Parcel dest, int flags ) { dest.writeValue ( this.currentPage ); dest.writeTypedList ( this.data ); dest.writeValue ( this.from ); dest.writeValue ( this.lastPage ); dest.writeString ( this.nextPageUrl ); dest.writeString ( this.path ); dest.writeValue ( this.perPage ); dest.writeString ( this.prevPageUrl ); dest.writeValue ( this.to ); dest.writeValue ( this.total ); }}
Now we have created model class(forhandlingdata) and pagination class(handling pagination in json).Now we have to create adapter and API service provider and display our data.We will cover these things in second and third part of this tutorial.Reference : http://square.github.io/retrofit/This article is contributed by Ashutosh Bhushan Srivastava. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
sagar0719kumar
android
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Nov, 2021"
},
{
"code": null,
"e": 122,
"s": 28,
"text": "I have divided it in 3 parts. I am assuming reader has basic knowledge of Android and java. "
},
{
"code": null,
"e": 135,
"s": 122,
"text": "Introduction"
},
{
"code": null,
"e": 911,
"s": 135,
"text": "Retrofit 2 is type-safe REST client build by square for Android and Java which intends to make it simpler to expand RESTful webservices. Retrofit 2 use OkHttp as the systems administration layer and is based over it. Retrofit naturally serializes the JSON reaction utilizing a POJO (PlainOldJavaObject) which must be characterized in cutting edge for the JSON Structure . To serialize JSON we require a converter to change over it into Gson first. Retrofit is much simpler than other libraries we don’t have to parse our json it directly returns objects but there is one disadvantage also it doesn’t provide support to loadimages from server but we can use picasso for the same. Now we should go for some practical implementation which will give better understanding to you. "
},
{
"code": null,
"e": 926,
"s": 911,
"text": "Implementation"
},
{
"code": null,
"e": 1179,
"s": 926,
"text": "Step-1 : For using Retrofit in our android project firstly we have to add dependency in gradle file. For adding dependency open app/build.gradle file in your Android project and add the following lines inside it. Add these lines inside dependencies{} "
},
{
"code": null,
"e": 1320,
"s": 1179,
"text": "compile'com.google.code.gson:gson:2.6.2'\ncompile'com.squareup.retrofit2:retrofit:2.0.2'\ncompile'com.squareup.retrofit2:converter-gson:2.0.2'"
},
{
"code": null,
"e": 1443,
"s": 1320,
"text": "Step-2 : We should now add InternetPermission inside Manifestfile.Open the manifest.xml file and add the following line. "
},
{
"code": null,
"e": 1503,
"s": 1443,
"text": "users-permission android:name=\"android.permission.INTERNET\""
},
{
"code": null,
"e": 1759,
"s": 1503,
"text": "Step-3 : For retrieving data from the server using retrofit 2 we require a modelclass. We are going to make model class to retrieve data from the server.For making modelclass we should know how the json looks. Suppose our json looks something like this : "
},
{
"code": null,
"e": 3641,
"s": 1759,
"text": "“current_page”:1, “data”: [ { “id”:1, “source”:”http:\\/\\/mhrd.gov.in\\/sites\\/upload_files\\/mhrd\\/files\\/upload_document\\/NSISGE-Scheme-Copy.pdf”, “name”:”National Scheme of Incentive to Girls for Secondary Education (NSIGSE)”, “sector”:”Education”, “government”:”Central”, “eligible_beneficiaries”:”Individual”, “requirements”:”i. Girls, who pass class VIII examination and enroll for class IX in State\\/UT Government, Government-aided or local body schools.\\nii. Girls should be below 16 years of age (as on 31st March) on joining class IX\\niii. Girls studying in private un-aided schools and enrolled in schools run by Central Government like KVS, NVS and CBS affiliated Schools are excluded.”, “benefits”:”FD of Rs.3000 in the name of selected girls. The girls are entitled to withdraw the sum along with interest thereon on reaching 18 years of age and on passing 10th class examination.”, “how_to_apply”:”Contact Principal\\/Headmaster of the School”, “profession”:””, “nationality”:””, “gender”:”Female”, “social_category”:[ “SC”, “ST”, “Girls from Kasturba Gandhi Balika Vidyalayas” ], “bpl”:””, “maximum_income”:””, “maximum_monthly_income”:””, “min_age”:14, “max_age”:18, “age_relaxation”:””, “qualification”:8, “employed”:””, “domicile”:””, “marital_status”:”Unmarried”, “parents_profession”:””, “person_with_disabilities”:””, “current_student”:”Yes”, “min_marks_in_previous_examination”:””, “religion”:””, “isDeleted”:”false”, “isLatest”:”false”, “isPopular”:”false”, “isHtml”:”false”, “state_url”:”http:\\/\\/161.202.178.14\\/kalyani\\/storage\\/states\\/AORGzbxjrB3zHhAyfs6zTqpt3pQhJsHRwSC4JVBs.png”, “sector_url”:”http:\\/\\/161.202.178.14\\/kalyani\\/storage\\/sector\\/lDASDAsje3BuWQYgaBCqKKWwkfKEuqIvVYp3dp53.png” }, .... ]”from”:1, “last_page”:75, “next_page_url”:”http:\\/\\/localhost:8081\\/\\/api\\/v1\\/search?page=2′′, “per_page”:10, “prev_page_url”:null, “to”:10, “total”:741 "
},
{
"code": null,
"e": 4049,
"s": 3641,
"text": "If you see the json you will realize that json contains different fields like source, stateurl, sectorurl, id, name, sector, government, id, name, sector, government, eligibleBeneficiarieand etc for all the fields we have created getter setter and used parcelable(https://developer.android.com/reference/android/os/Parcelable.html).Here is the code for model class please read it for better understanding. "
},
{
"code": null,
"e": 4054,
"s": 4049,
"text": "java"
},
{
"code": "import android.os.Parcel;import android.os.Parcelable; import com.google.gson.annotations.Expose;import com.google.gson.annotations.SerializedName; public class Scheme implements Parcelable { public static final Creator<Scheme> CREATOR = new Creator<Scheme> ( ) { @Override public Scheme createFromParcel ( Parcel source ) { return new Scheme ( source ); } @Override public Scheme[] newArray ( int size ) { return new Scheme[size]; } }; @SerializedName(\"source\") @Expose private String source; @SerializedName(\"state_url\") @Expose private String stateurl; @SerializedName(\"sector_url\") @Expose private String sectorurl; @SerializedName(\"id\") @Expose private Integer id; @SerializedName(\"name\") @Expose private String name; @SerializedName(\"sector\") @Expose private String sector; @SerializedName(\"government\") @Expose private String government; @SerializedName(\"eligible_beneficiaries\") @Expose private String eligibleBeneficiaries; @SerializedName(\"maximum_income\") @Expose private String income; @SerializedName(\"social_category\") @Expose private String[] socialCategory; @SerializedName(\"religion\") @Expose private String religion; @SerializedName(\"requirements\") @Expose private String requirements; @SerializedName(\"benefits\") @Expose private String benefits; @SerializedName(\"how_to_apply\") @Expose private String howToApply; @SerializedName(\"gender\") @Expose private String gender; @SerializedName(\"min_age\") @Expose private Integer minAge; @SerializedName(\"max_age\") @Expose private Integer maxAge; @SerializedName(\"qualification\") @Expose private String qualification; @SerializedName(\"marital_status\") @Expose private String maritalStatus; @SerializedName(\"bpl\") @Expose private String bpl; @SerializedName(\"disability\") @Expose private String disability; public Scheme ( ) { } protected Scheme ( Parcel in ) { this.source = in.readString ( ); this.stateurl = in.readString ( ); this.sectorurl = in.readString ( ); this.id = (Integer) in.readValue ( Integer.class.getClassLoader ( ) ); this.name = in.readString ( ); this.sector = in.readString ( ); this.government = in.readString ( ); this.eligibleBeneficiaries = in.readString ( ); this.income = in.readString ( ); this.socialCategory = in.createStringArray ( ); this.religion = in.readString ( ); this.requirements = in.readString ( ); this.benefits = in.readString ( ); this.howToApply = in.readString ( ); this.gender = in.readString ( ); this.minAge = (Integer) in.readValue ( Integer.class.getClassLoader ( ) ); this.maxAge = (Integer) in.readValue ( Integer.class.getClassLoader ( ) ); this.qualification = in.readString ( ); this.maritalStatus = in.readString ( ); this.bpl = in.readString ( ); this.disability = in.readString ( ); } public String getBpl ( ) { return bpl; } public void setBpl ( String bpl ) { this.bpl = bpl; } public String getDisability ( ) { return disability; } public void setDisability ( String disability ) { this.disability = disability; } public String getStateurl ( ) { return stateurl; } public void setStateurl ( String stateurl ) { this.stateurl = stateurl; } public String getSectorurl ( ) { return sectorurl; } public void setSectorurl ( String sectorurl ) { this.sectorurl = sectorurl; } public String getIncome ( ) { return income; } public void setIncome ( String income ) { this.income = income; } public String[] getSocialCategory ( ) { return socialCategory; } public void setSocialCategory ( String[] socialCategory ) { this.socialCategory = socialCategory; } public String getReligion ( ) { return religion; } public void setReligion ( String religion ) { this.religion = religion; } public String getRequirements ( ) { return requirements; } public void setRequirements ( String requirements ) { this.requirements = requirements; } public String getSource ( ) { return source; } public void setSource ( String source ) { this.source = source; } public Integer getId ( ) { return id; } public void setId ( Integer id ) { this.id = id; } public String getName ( ) { return name; } public void setName ( String name ) { this.name = name; } public String getSector ( ) { return sector; } public void setSector ( String sector ) { this.sector = sector; } public String getGovernment ( ) { return government; } public void setGovernment ( String government ) { this.government = government; } public String getEligibleBeneficiaries ( ) { return eligibleBeneficiaries; } public void setEligibleBeneficiaries ( String eligibleBeneficiaries ) { this.eligibleBeneficiaries = eligibleBeneficiaries; } public String getBenefits ( ) { return benefits; } public void setBenefits ( String benefits ) { this.benefits = benefits; } public String getHowToApply ( ) { return howToApply; } public void setHowToApply ( String howToApply ) { this.howToApply = howToApply; } public String getGender ( ) { return gender; } public void setGender ( String gender ) { this.gender = gender; } public Integer getMinAge ( ) { return minAge; } public void setMinAge ( Integer minAge ) { this.minAge = minAge; } public Integer getMaxAge ( ) { return maxAge; } public void setMaxAge ( Integer maxAge ) { this.maxAge = maxAge; } public String getQualification ( ) { return qualification; } public void setQualification ( String qualification ) { this.qualification = qualification; } public String getMaritalStatus ( ) { return maritalStatus; } public void setMaritalStatus ( String maritalStatus ) { this.maritalStatus = maritalStatus; } public String getSocialCategoryString(){ if(socialCategory != null && socialCategory.length > 0){ return android.text.TextUtils.join(\",\", socialCategory); } return null; } @Override public int describeContents ( ) { return 0; } @Override public void writeToParcel ( Parcel dest, int flags ) { dest.writeString ( this.source ); dest.writeString ( this.stateurl ); dest.writeString ( this.sectorurl ); dest.writeValue ( this.id ); dest.writeString ( this.name ); dest.writeString ( this.sector ); dest.writeString ( this.government ); dest.writeString ( this.eligibleBeneficiaries ); dest.writeString ( this.income ); dest.writeStringArray ( this.socialCategory ); dest.writeString ( this.religion ); dest.writeString ( this.requirements ); dest.writeString ( this.benefits ); dest.writeString ( this.howToApply ); dest.writeString ( this.gender ); dest.writeValue ( this.minAge ); dest.writeValue ( this.maxAge ); dest.writeString ( this.qualification ); dest.writeString ( this.maritalStatus ); dest.writeString ( this.bpl ); dest.writeString ( this.disability ); }}",
"e": 11761,
"s": 4054,
"text": null
},
{
"code": null,
"e": 11999,
"s": 11761,
"text": "You must have observed that we have used pagination in json (we are retrieving data in a set of 10).For handling this pagination we will create one more java file.Here is the code for pagination please read it for better understanding. "
},
{
"code": null,
"e": 12004,
"s": 11999,
"text": "java"
},
{
"code": "import android.os.Parcel;import android.os.Parcelable; import com.google.gson.annotations.Expose;import com.google.gson.annotations.SerializedName; import java.util.ArrayList; public class Page implements Parcelable { public static final Creator<Page> CREATOR = new Creator<Page> ( ) { @Override public Page createFromParcel ( Parcel source ) { return new Page ( source ); } @Override public Page[] newArray ( int size ) { return new Page[size]; } }; @SerializedName(\"current_page\") @Expose private Integer currentPage; @SerializedName(\"data\") @Expose private ArrayList<Scheme> data = null; @SerializedName(\"from\") @Expose private Integer from; @SerializedName(\"last_page\") @Expose private Integer lastPage; @SerializedName(\"next_page_url\") @Expose private String nextPageUrl; @SerializedName(\"path\") @Expose private String path; @SerializedName(\"per_page\") @Expose private Integer perPage; @SerializedName(\"prev_page_url\") @Expose private String prevPageUrl; @SerializedName(\"to\") @Expose private Integer to; @SerializedName(\"total\") @Expose private Integer total; public Page ( ) { } protected Page ( Parcel in ) { this.currentPage = (Integer) in.readValue ( Integer.class.getClassLoader ( ) ); this.data = in.createTypedArrayList ( Scheme.CREATOR ); this.from = (Integer) in.readValue ( Integer.class.getClassLoader ( ) ); this.lastPage = (Integer) in.readValue ( Integer.class.getClassLoader ( ) ); this.nextPageUrl = in.readString ( ); this.path = in.readString ( ); this.perPage = (Integer) in.readValue ( Integer.class.getClassLoader ( ) ); this.prevPageUrl = in.readString ( ); this.to = (Integer) in.readValue ( Integer.class.getClassLoader ( ) ); this.total = (Integer) in.readValue ( Integer.class.getClassLoader ( ) ); } public Integer getCurrentPage() { return currentPage; } public void setCurrentPage(Integer currentPage) { this.currentPage = currentPage; } public ArrayList<Scheme> getData ( ) { return data; } public void setData ( ArrayList<Scheme> data ) { this.data = data; } public Integer getFrom() { return from; } public void setFrom(Integer from) { this.from = from; } public Integer getLastPage() { return lastPage; } public void setLastPage(Integer lastPage) { this.lastPage = lastPage; } public String getNextPageUrl() { return nextPageUrl; } public void setNextPageUrl(String nextPageUrl) { this.nextPageUrl = nextPageUrl; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public Integer getPerPage() { return perPage; } public void setPerPage(Integer perPage) { this.perPage = perPage; } public String getPrevPageUrl ( ) { return prevPageUrl; } public void setPrevPageUrl ( String prevPageUrl ) { this.prevPageUrl = prevPageUrl; } public Integer getTo() { return to; } public void setTo(Integer to) { this.to = to; } public Integer getTotal() { return total; } public void setTotal(Integer total) { this.total = total; } @Override public int describeContents ( ) { return 0; } @Override public void writeToParcel ( Parcel dest, int flags ) { dest.writeValue ( this.currentPage ); dest.writeTypedList ( this.data ); dest.writeValue ( this.from ); dest.writeValue ( this.lastPage ); dest.writeString ( this.nextPageUrl ); dest.writeString ( this.path ); dest.writeValue ( this.perPage ); dest.writeString ( this.prevPageUrl ); dest.writeValue ( this.to ); dest.writeValue ( this.total ); }}",
"e": 15995,
"s": 12004,
"text": null
},
{
"code": null,
"e": 16720,
"s": 15995,
"text": "Now we have created model class(forhandlingdata) and pagination class(handling pagination in json).Now we have to create adapter and API service provider and display our data.We will cover these things in second and third part of this tutorial.Reference : http://square.github.io/retrofit/This article is contributed by Ashutosh Bhushan Srivastava. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 16735,
"s": 16720,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 16743,
"s": 16735,
"text": "android"
},
{
"code": null,
"e": 16749,
"s": 16743,
"text": "GBlog"
}
] |
Java Collectors
|
19 Jul, 2020
Collectors is one of the utility class in JDK which contains a lot of utility functions. It is mostly used with Stream API as a final step. In this article, we will study different methods in the collector class.
When it comes to the functional style of programming in Java, we typically have few functions which we use widely and those functions are filter(), map(), reduce(), and collect() which belongs to the Streams API. collect() and reduce() methods are called as the terminal methods because here, the operation gets terminated with some outcome. Functions associated with Collectors usually get used inside collect() methods. Collectors class is part of Stream package and can be imported as:
import static java.util.stream.Collectors.*;
Class Hierarchy:
java.lang.Object
↳ java.util.stream
↳ class Collectors
Syntax:
public final
class Collectors
extends Object
Let’s consider a City class, which has attributes like name and temperature which are being initialized with the parameterized constructor. We will observe the different methods available in the collectors class using this example.
Below is the implementation of the City class:
// Java program to implement a// City class // Defining a city classpublic class City { // Initializing the properties // of the city class private String name; private double temperature; // Parameterized constructor to // initialize the city class public City(String name, double temperature) { this.name = name; this.temperature = temperature; } // Getters to get the name and // temperature public String getName() { return name; } public Double getTemperature() { return temperature; } // Overriding the toString method // to return the name and temperature @Override public String toString() { return name + " --> " + temperature; }}
Before getting into the different methods, let’s create a list of cities with name and temperature. Below is the implementation of a method to create a list of cities with name and temperature:
// Java program to create a list// of cities with name and// temperature // Function to create a list of// cities with name and temperatureprivate static List<City> prepareTemperature(){ List<City> cities = new ArrayList<>(); cities.add(new City("New Delhi", 33.5)); cities.add(new City("Mexico", 14)); cities.add(new City("New York", 13)); cities.add(new City("Dubai", 43)); cities.add(new City("London", 15)); cities.add(new City("Alaska", 1)); cities.add(new City("Kolkata", 30)); cities.add(new City("Sydney", 11)); cities.add(new City("Mexico", 14)); cities.add(new City("Dubai", 43)); return cities;}
The following are the various methods to perform operations on the above cities:
1. Collector<T, ?, List<T>> toList(): Transforms the input elements into a new List and returns a Collector. Here, T is the type of the input elements. In the following example, we are trying to process the list of cities whose temperature is more than 10, and get only the city names.
To do so, we use filter() to apply the filter check of temperature, we use map() to transform the city name and use collect() to collect these city names. Now this collect() method is basically used for collecting the elements passed though stream and its various functions and return a List instance.
// Java program to implement the // toList() method import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class GFG { public static void main(String[] args) { // The following statement filters // cities having temp > 10 // The map function transforms only // the names of the cities // The collect function collects the // output as a List System.out.println(prepareTemperature().stream() .filter(f -> f.getTemperature() > 10) .map(f -> f.getName()) .collect(Collectors.toList())); } }
Output:
[New Delhi, Mexico, New York, Dubai, London, Kolkata, Sydney, Mexico, Dubai]
Here, the city Alaska is not present in the output because it’s temperature was initialized as 1.
2. Collector<T, ?, Set<T>> toSet(): Transforms the input elements into a new Set and returns a Collector. This method will return Set instance and it doesn’t contain any duplicates.
// Java program to implement the// toSet() methodimport java.util.ArrayList;import java.util.List;import java.util.stream.Collectors; public class GFG { public static void main(String[] args) { // Here, we have applied the filter // to get the set of the names // of the cities whose temperature // is greater than 10 System.out.println(prepareTemperature() .stream() .filter(f -> f.getTemperature() > 10) .map(f -> f.getName()) .collect(Collectors.toSet())); }}
Output:
[New York, New Delhi, London, Mexico, Kolkata, Dubai, Sydney]
Here, we can notice in the output that Mexico and Dubai have not been repeated.
3. Collector<T, ?, C> toCollection(Supplier <C> collectionFactory): Transforms the input elements into a new Collection, and returns a Collector. If we observe toList() and toSet() methods discussed above, We don’t have control over their implementations. So with toCollection() we can achieve custom implementation where C is the type of the resulting collection and T is the type of the input elements.
// Java program to implement the// toCollection() methodimport java.util.ArrayList;import java.util.LinkedList;import java.util.List;import java.util.stream.Collectors; public class GFG { public static void main(String[] args) { // Here, a list of all the names // have been returned System.out.println(prepareTemperature() .stream() .map(f -> f.getName()) .collect(Collectors.toCollection(List::new))); }}
Output:
[New Delhi, Mexico, New York, Dubai, London, Alaska, Kolkata, Sydney, Mexico, Dubai]
Similarly, we can use all other implementation classes such as ArrayList, HashSet, TreeSet, etc.
4. Collector<T, ?, Map< K, U>> toMap(Function keyMapper, Function valueMapper): Transforms the elements into a Map whose keys and values are the results of applying the passed mapper functions to the input elements and returns a Collector. toMap() is used to collect input of elements and convert it into Map instance. toMap() methods ask for following arguments:
K - Key function
U - Value Function
BinaryOperator(optional)
Supplier(Optional)
Let’s try to understand this with an example. For above discussed list of cities and temperatures, we want to fetch the city name with temperature in the Map.
prepareTemperature().stream().filter(city -> city.getTemperature() > 10).collect(Collectors.toMap(City::getName, City::getTemperature));
The above statements work perfectly if the list doesn’t have duplicates. Since our list contains duplicates then it will not filter it out silently as toSet(). Instead, it throws an IllegalStateException. We can avoid and fix this issue by avoiding the key collision(in case of duplicate keys) with the third argument that is BinaryOperator. For example:
// Java program to implement the// Map() method import java.util.ArrayList;import java.util.List;import java.util.stream.Collectors; public class GFG { public static void main(String[] args) { // Here, the name and the temperature // are defined as the type City System.out.println(prepareTemperature() .stream() .filter(city -> city.getTemperature() > 10) .collect(Collectors.toMap( City::getName, City::getTemperature, (key, identicalKey) -> key))); }}
Output:
{New York=13.0, New Delhi=33.5, London=15.0, Mexico=14.0, Kolkata=30.0, Dubai=43.0, Sydney=11.0}
Binary operator specifies, how can we handle the collision. Above statements pick either of the colliding elements.
5. Collector collectingAndThen(Collector downstream, Function finisher): This method allows us to perform another operation on the result after collecting the input element of collection.
// Java program to implement the// collectingAndThen() methodimport java.util.ArrayList;import java.util.List;import java.util.stream.Collectors; public class GFG { public static void main(String[] args) { // Collects the elements and // counts the occurrences System.out.println(prepareTemperature() .stream() .collect(Collectors.groupingBy( City::getName, Collectors.collectingAndThen( Collectors.counting(), f -> f.intValue())))); }}
Output:
{New York=1, New Delhi=1, London=1, Alaska=1, Mexico=2, Kolkata=1, Dubai=2, Sydney=1}
6. Collector counting(): It counts the number of input elements of type T and returns a Collector. This method is used in a case where we want to group and count the number of times each city is present in the collection of elements.
// Java program to implement the// counting() methodimport java.util.ArrayList;import java.util.List;import java.util.stream.Collectors; public class GFG { public static void main(String[] args) { System.out.println(prepareTemperature() .stream() .collect(Collectors.groupingBy( City::getName, Collectors.counting()))); }}
Output:
{New York=1, New Delhi=1, London=1, Alaska=1, Mexico=2, Kolkata=1, Dubai=2, Sydney=1}
We can see that the cities Mexico and Dubai count is 2, and the rest are available once. And, the return type of groupingBy is Map.
7. Collector <T, ?, Map<K, List>> groupingBy(Function classifier): Performs group by operation on input elements of type T. The grouping of elements is done as per the passed classifier function and returns the Collector with result in a Map.
// Java program to implement the// groupingBy() methodimport java.util.ArrayList;import java.util.List;import java.util.stream.Collectors; public class GFG { public static void main(String[] args) { System.out.println(prepareTemperature() .stream() .collect(Collectors.groupingBy(City::getName))); }}
Output:
{New York=[New York –> 13.0], New Delhi=[New Delhi –> 33.5], London=[London –> 15.0], Alaska=[Alaska –> 1.0], Mexico=[Mexico –> 14.0, Mexico –> 14.0], Kolkata=[Kolkata –> 30.0], Dubai=[Dubai –> 43.0, Dubai –> 43.0], Sydney=[Sydney –> 11.0]}
In the above example, cities like Mexico and Dubai have been grouped, the rest of the groups contains only one city because they are all alone. The return type of above groupingBy() is Map<String, List>.
8. Collector <T, ?, Map> groupingBy(Function classifier, Collector downstream): Performs group by operation on input elements of type T. The grouping of the elements is done as per the passed classifier function and then performs a reduction operation on the values associated with a given key as per the specified downstream Collector and returns the Collector with result in a Map.
9. Collector groupingBy(Function classifier, Supplier mapFactory, Collector downstream): Performs group by operation on input elements of type T, the grouping of elements is done as per the passed classifier function and then performs a reduction operation on the values associated with a given key as per the specified downstream Collector and returns the Collector.
10. Collector joining(): Concatenates the input elements into a String and returns a Collector.
11. Collector joining(CharSequence delimiter): Concatenates the input elements, separated by the specified delimiter, and returns a Collector.
// Java program to implement the// joining() methodimport java.util.ArrayList;import java.util.List;import java.util.stream.Collectors; public class GFG { public static void main(String[] args) { // Concatenate the collection with // comma System.out.println(prepareTemperature() .stream() .filter(city -> city.getTemperature() > 10) .map(f -> f.getName()) .collect(Collectors.joining(", "))); }}
Output:
New Delhi, Mexico, New York, Dubai, London, Kolkata, Sydney, Mexico, Dubai
12. Collector joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix): Concatenates the input elements, separated by the specified delimiter, as per the specified prefix and suffix, and returns a Collector.
// Java program to implement the// joining() methodimport java.util.ArrayList;import java.util.List;import java.util.stream.Collectors; public class GFG { public static void main(String[] args) { System.out.println(prepareTemperature() .stream() .filter(city -> city.getTemperature() > 10) .map(f -> f.getName()) .collect(Collectors.joining(" ", "Prefix:", ":Suffix"))); }}
Output:
Prefix:New Delhi Mexico New York Dubai London Kolkata Sydney Mexico Dubai:Suffix
13. Collector mapping(Function mapper, Collector downstream): Transforms a Collector of the input elements of type U to one the input elements of type T by applying a mapping function to every input element before the transformation.
// Java program to implement the// mapping() methodimport java.util.ArrayList;import java.util.List;import java.util.stream.Collectors; public class GFG { public static void main(String[] args) { System.out.println(prepareTemperature() .stream() .collect(Collectors.groupingBy( City::getName, Collectors.mapping( City::getTemperature, Collectors.toList())))); }}
Output:
{New York=[13.0], New Delhi=[33.5], London=[15.0], Alaska=[1.0], Mexico=[14.0, 14.0], Kolkata=[30.0], Dubai=[43.0, 43.0], Sydney=[11.0]}
In the above output, each city group contains only the temperature, and this is done with the help ofmapping() method, which takes two function argument of type function and collector. Above mapping method return a list and finally the return type of the above groupingBy() method becomes Map<String, List>. We can also use toSet() method to get the set of elements instead of the list as follows:
// Java program to implement the// joining() method import java.util.ArrayList;import java.util.List;import java.util.stream.Collectors; public class GFG { public static void main(String[] args) { System.out.println(prepareTemperature() .stream() .collect(Collectors.groupingBy( City::getName, Collectors.mapping( City::getTemperature, Collectors.toSet())))); }}
Output:
{New York=[13.0], New Delhi=[33.5], London=[15.0], Alaska=[1.0], Mexico=[14.0], Kolkata=[30.0], Dubai=[43.0], Sydney=[11.0]}
If we observe the output and compare it from the previous one, the duplicates have been removed because it is a set now. The return type of above groupingBy() now becomes Map<String, Set>.
14. Collector<T, ?, Map<Boolean, List>> partitioningBy(Predicate predicate): Partitions the input elements as per the passed Predicate, and transforms them into a Map and returns the Collector.
// Java program to implement the// partitioningBy() methodimport java.util.ArrayList;import java.util.List;import java.util.stream.Collectors; public class GFG { public static void main(String[] args) { // Here, we are partitioning the list // in two groups i.e., Cities having // temperatures more than 15 // and other than that. System.out.println(prepareTemperature() .stream() .collect(Collectors.partitioningBy( city -> city.getTemperature() > 15))); }}
Output:
{false=[Mexico–> 14.0, New York–> 13.0, London–> 15.0, Alaska–> 1.0, Sydney–> 11.0, Mexico–> 14.0], true=[New Delhi–> 33.5, Dubai–> 43.0, Kolkata–> 30.0, Dubai–> 43.0]}
15. Collector partitioningBy(Predicate predicate, Collector downstream): Partitions the input elements as per the passed Predicate, and collects the values of each partition as per another Collector, and transforms them into a Map whose values are the results of the downstream reduction and then return Collector.
16. Collector averagingDouble(ToDoubleFunction mapper): Performs the average of the input elements of type Double, and returns the Collector as a result.
17. Collector averagingInt(ToIntFunction mapper): Performs the average of the input elements of type Int, and returns the Collector as a result.
18. Collector averagingLong(ToLongFunction mapper): Performs the average of the input elements of type Long, and returns the Collector as a result.
19. Collector<T, ?, ConcurrentMap<K, List>> groupingByConcurrent(Function classifier): Performs group by operation on the input elements of type T, the grouping of elements is done as per the passed classifier function and returns concurrent Collector.
20. Collector<T, ?, ConcurrentMap> groupingByConcurrent(Function classifier, Collector downstream): Performs group by operation on the input elements of type T, the grouping of elements is done as per the passed classifier function, and then performs a reduction operation on the values associated with a given key as per the specified downstream Collector and returns a concurrent Collector.
21. Collector groupingByConcurrent(Function classifier, Supplier mapFactory, Collector downstream): Performs group by operation on input elements of type T, the grouping of elements is done as per the passed classifier function, and then performs a reduction operation on the values associated with a given key as per the specified downstream Collector and returns a concurrent Collector.
22. Collector reducing(BinaryOperator op): Performs a reduction of its input elements as per passed BinaryOperator and returns a Collector.
23. Collector reducing(T identity, BinaryOperator op): Performs a reduction of its input elements as per passed BinaryOperator and as per the passed identity and returns Collector.
24. Collector<T, ?, Optional> maxBy(Comparator comparator): Produces the maximal element as per given Comparator, returns an Optional Collector.
25. Collector<T, ?, Optional> minBy(Comparator comparator): Produces the minimal element as per given Comparator, returns an Optional Collector.
26. Collector<T, ?, ConcurrentMap> toConcurrentMap(Function keyMapper, Function valueMapper): Transforms elements into a ConcurrentMap whose keys and values are the results of the passed mapper functions to the input elements and returns a concurrent Collector.
Reference: https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html
Java-Collectors
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Stack Class in Java
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n19 Jul, 2020"
},
{
"code": null,
"e": 267,
"s": 54,
"text": "Collectors is one of the utility class in JDK which contains a lot of utility functions. It is mostly used with Stream API as a final step. In this article, we will study different methods in the collector class."
},
{
"code": null,
"e": 756,
"s": 267,
"text": "When it comes to the functional style of programming in Java, we typically have few functions which we use widely and those functions are filter(), map(), reduce(), and collect() which belongs to the Streams API. collect() and reduce() methods are called as the terminal methods because here, the operation gets terminated with some outcome. Functions associated with Collectors usually get used inside collect() methods. Collectors class is part of Stream package and can be imported as:"
},
{
"code": null,
"e": 802,
"s": 756,
"text": "import static java.util.stream.Collectors.*;\n"
},
{
"code": null,
"e": 819,
"s": 802,
"text": "Class Hierarchy:"
},
{
"code": null,
"e": 887,
"s": 819,
"text": "java.lang.Object\n ↳ java.util.stream\n ↳ class Collectors\n"
},
{
"code": null,
"e": 895,
"s": 887,
"text": "Syntax:"
},
{
"code": null,
"e": 947,
"s": 895,
"text": "public final\n class Collectors\n extends Object\n"
},
{
"code": null,
"e": 1179,
"s": 947,
"text": "Let’s consider a City class, which has attributes like name and temperature which are being initialized with the parameterized constructor. We will observe the different methods available in the collectors class using this example."
},
{
"code": null,
"e": 1226,
"s": 1179,
"text": "Below is the implementation of the City class:"
},
{
"code": "// Java program to implement a// City class // Defining a city classpublic class City { // Initializing the properties // of the city class private String name; private double temperature; // Parameterized constructor to // initialize the city class public City(String name, double temperature) { this.name = name; this.temperature = temperature; } // Getters to get the name and // temperature public String getName() { return name; } public Double getTemperature() { return temperature; } // Overriding the toString method // to return the name and temperature @Override public String toString() { return name + \" --> \" + temperature; }}",
"e": 1981,
"s": 1226,
"text": null
},
{
"code": null,
"e": 2175,
"s": 1981,
"text": "Before getting into the different methods, let’s create a list of cities with name and temperature. Below is the implementation of a method to create a list of cities with name and temperature:"
},
{
"code": "// Java program to create a list// of cities with name and// temperature // Function to create a list of// cities with name and temperatureprivate static List<City> prepareTemperature(){ List<City> cities = new ArrayList<>(); cities.add(new City(\"New Delhi\", 33.5)); cities.add(new City(\"Mexico\", 14)); cities.add(new City(\"New York\", 13)); cities.add(new City(\"Dubai\", 43)); cities.add(new City(\"London\", 15)); cities.add(new City(\"Alaska\", 1)); cities.add(new City(\"Kolkata\", 30)); cities.add(new City(\"Sydney\", 11)); cities.add(new City(\"Mexico\", 14)); cities.add(new City(\"Dubai\", 43)); return cities;}",
"e": 2819,
"s": 2175,
"text": null
},
{
"code": null,
"e": 2900,
"s": 2819,
"text": "The following are the various methods to perform operations on the above cities:"
},
{
"code": null,
"e": 3186,
"s": 2900,
"text": "1. Collector<T, ?, List<T>> toList(): Transforms the input elements into a new List and returns a Collector. Here, T is the type of the input elements. In the following example, we are trying to process the list of cities whose temperature is more than 10, and get only the city names."
},
{
"code": null,
"e": 3488,
"s": 3186,
"text": "To do so, we use filter() to apply the filter check of temperature, we use map() to transform the city name and use collect() to collect these city names. Now this collect() method is basically used for collecting the elements passed though stream and its various functions and return a List instance."
},
{
"code": "// Java program to implement the // toList() method import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class GFG { public static void main(String[] args) { // The following statement filters // cities having temp > 10 // The map function transforms only // the names of the cities // The collect function collects the // output as a List System.out.println(prepareTemperature().stream() .filter(f -> f.getTemperature() > 10) .map(f -> f.getName()) .collect(Collectors.toList())); } } ",
"e": 4144,
"s": 3488,
"text": null
},
{
"code": null,
"e": 4152,
"s": 4144,
"text": "Output:"
},
{
"code": null,
"e": 4229,
"s": 4152,
"text": "[New Delhi, Mexico, New York, Dubai, London, Kolkata, Sydney, Mexico, Dubai]"
},
{
"code": null,
"e": 4327,
"s": 4229,
"text": "Here, the city Alaska is not present in the output because it’s temperature was initialized as 1."
},
{
"code": null,
"e": 4509,
"s": 4327,
"text": "2. Collector<T, ?, Set<T>> toSet(): Transforms the input elements into a new Set and returns a Collector. This method will return Set instance and it doesn’t contain any duplicates."
},
{
"code": "// Java program to implement the// toSet() methodimport java.util.ArrayList;import java.util.List;import java.util.stream.Collectors; public class GFG { public static void main(String[] args) { // Here, we have applied the filter // to get the set of the names // of the cities whose temperature // is greater than 10 System.out.println(prepareTemperature() .stream() .filter(f -> f.getTemperature() > 10) .map(f -> f.getName()) .collect(Collectors.toSet())); }}",
"e": 5088,
"s": 4509,
"text": null
},
{
"code": null,
"e": 5096,
"s": 5088,
"text": "Output:"
},
{
"code": null,
"e": 5158,
"s": 5096,
"text": "[New York, New Delhi, London, Mexico, Kolkata, Dubai, Sydney]"
},
{
"code": null,
"e": 5238,
"s": 5158,
"text": "Here, we can notice in the output that Mexico and Dubai have not been repeated."
},
{
"code": null,
"e": 5643,
"s": 5238,
"text": "3. Collector<T, ?, C> toCollection(Supplier <C> collectionFactory): Transforms the input elements into a new Collection, and returns a Collector. If we observe toList() and toSet() methods discussed above, We don’t have control over their implementations. So with toCollection() we can achieve custom implementation where C is the type of the resulting collection and T is the type of the input elements."
},
{
"code": "// Java program to implement the// toCollection() methodimport java.util.ArrayList;import java.util.LinkedList;import java.util.List;import java.util.stream.Collectors; public class GFG { public static void main(String[] args) { // Here, a list of all the names // have been returned System.out.println(prepareTemperature() .stream() .map(f -> f.getName()) .collect(Collectors.toCollection(List::new))); }}",
"e": 6133,
"s": 5643,
"text": null
},
{
"code": null,
"e": 6141,
"s": 6133,
"text": "Output:"
},
{
"code": null,
"e": 6226,
"s": 6141,
"text": "[New Delhi, Mexico, New York, Dubai, London, Alaska, Kolkata, Sydney, Mexico, Dubai]"
},
{
"code": null,
"e": 6323,
"s": 6226,
"text": "Similarly, we can use all other implementation classes such as ArrayList, HashSet, TreeSet, etc."
},
{
"code": null,
"e": 6687,
"s": 6323,
"text": "4. Collector<T, ?, Map< K, U>> toMap(Function keyMapper, Function valueMapper): Transforms the elements into a Map whose keys and values are the results of applying the passed mapper functions to the input elements and returns a Collector. toMap() is used to collect input of elements and convert it into Map instance. toMap() methods ask for following arguments:"
},
{
"code": null,
"e": 6768,
"s": 6687,
"text": "K - Key function\nU - Value Function\nBinaryOperator(optional)\nSupplier(Optional)\n"
},
{
"code": null,
"e": 6927,
"s": 6768,
"text": "Let’s try to understand this with an example. For above discussed list of cities and temperatures, we want to fetch the city name with temperature in the Map."
},
{
"code": null,
"e": 7064,
"s": 6927,
"text": "prepareTemperature().stream().filter(city -> city.getTemperature() > 10).collect(Collectors.toMap(City::getName, City::getTemperature));"
},
{
"code": null,
"e": 7419,
"s": 7064,
"text": "The above statements work perfectly if the list doesn’t have duplicates. Since our list contains duplicates then it will not filter it out silently as toSet(). Instead, it throws an IllegalStateException. We can avoid and fix this issue by avoiding the key collision(in case of duplicate keys) with the third argument that is BinaryOperator. For example:"
},
{
"code": "// Java program to implement the// Map() method import java.util.ArrayList;import java.util.List;import java.util.stream.Collectors; public class GFG { public static void main(String[] args) { // Here, the name and the temperature // are defined as the type City System.out.println(prepareTemperature() .stream() .filter(city -> city.getTemperature() > 10) .collect(Collectors.toMap( City::getName, City::getTemperature, (key, identicalKey) -> key))); }}",
"e": 8037,
"s": 7419,
"text": null
},
{
"code": null,
"e": 8045,
"s": 8037,
"text": "Output:"
},
{
"code": null,
"e": 8142,
"s": 8045,
"text": "{New York=13.0, New Delhi=33.5, London=15.0, Mexico=14.0, Kolkata=30.0, Dubai=43.0, Sydney=11.0}"
},
{
"code": null,
"e": 8258,
"s": 8142,
"text": "Binary operator specifies, how can we handle the collision. Above statements pick either of the colliding elements."
},
{
"code": null,
"e": 8446,
"s": 8258,
"text": "5. Collector collectingAndThen(Collector downstream, Function finisher): This method allows us to perform another operation on the result after collecting the input element of collection."
},
{
"code": "// Java program to implement the// collectingAndThen() methodimport java.util.ArrayList;import java.util.List;import java.util.stream.Collectors; public class GFG { public static void main(String[] args) { // Collects the elements and // counts the occurrences System.out.println(prepareTemperature() .stream() .collect(Collectors.groupingBy( City::getName, Collectors.collectingAndThen( Collectors.counting(), f -> f.intValue())))); }}",
"e": 9072,
"s": 8446,
"text": null
},
{
"code": null,
"e": 9080,
"s": 9072,
"text": "Output:"
},
{
"code": null,
"e": 9166,
"s": 9080,
"text": "{New York=1, New Delhi=1, London=1, Alaska=1, Mexico=2, Kolkata=1, Dubai=2, Sydney=1}"
},
{
"code": null,
"e": 9400,
"s": 9166,
"text": "6. Collector counting(): It counts the number of input elements of type T and returns a Collector. This method is used in a case where we want to group and count the number of times each city is present in the collection of elements."
},
{
"code": "// Java program to implement the// counting() methodimport java.util.ArrayList;import java.util.List;import java.util.stream.Collectors; public class GFG { public static void main(String[] args) { System.out.println(prepareTemperature() .stream() .collect(Collectors.groupingBy( City::getName, Collectors.counting()))); }}",
"e": 9828,
"s": 9400,
"text": null
},
{
"code": null,
"e": 9836,
"s": 9828,
"text": "Output:"
},
{
"code": null,
"e": 9922,
"s": 9836,
"text": "{New York=1, New Delhi=1, London=1, Alaska=1, Mexico=2, Kolkata=1, Dubai=2, Sydney=1}"
},
{
"code": null,
"e": 10054,
"s": 9922,
"text": "We can see that the cities Mexico and Dubai count is 2, and the rest are available once. And, the return type of groupingBy is Map."
},
{
"code": null,
"e": 10297,
"s": 10054,
"text": "7. Collector <T, ?, Map<K, List>> groupingBy(Function classifier): Performs group by operation on input elements of type T. The grouping of elements is done as per the passed classifier function and returns the Collector with result in a Map."
},
{
"code": "// Java program to implement the// groupingBy() methodimport java.util.ArrayList;import java.util.List;import java.util.stream.Collectors; public class GFG { public static void main(String[] args) { System.out.println(prepareTemperature() .stream() .collect(Collectors.groupingBy(City::getName))); }}",
"e": 10649,
"s": 10297,
"text": null
},
{
"code": null,
"e": 10657,
"s": 10649,
"text": "Output:"
},
{
"code": null,
"e": 10898,
"s": 10657,
"text": "{New York=[New York –> 13.0], New Delhi=[New Delhi –> 33.5], London=[London –> 15.0], Alaska=[Alaska –> 1.0], Mexico=[Mexico –> 14.0, Mexico –> 14.0], Kolkata=[Kolkata –> 30.0], Dubai=[Dubai –> 43.0, Dubai –> 43.0], Sydney=[Sydney –> 11.0]}"
},
{
"code": null,
"e": 11102,
"s": 10898,
"text": "In the above example, cities like Mexico and Dubai have been grouped, the rest of the groups contains only one city because they are all alone. The return type of above groupingBy() is Map<String, List>."
},
{
"code": null,
"e": 11486,
"s": 11102,
"text": "8. Collector <T, ?, Map> groupingBy(Function classifier, Collector downstream): Performs group by operation on input elements of type T. The grouping of the elements is done as per the passed classifier function and then performs a reduction operation on the values associated with a given key as per the specified downstream Collector and returns the Collector with result in a Map."
},
{
"code": null,
"e": 11854,
"s": 11486,
"text": "9. Collector groupingBy(Function classifier, Supplier mapFactory, Collector downstream): Performs group by operation on input elements of type T, the grouping of elements is done as per the passed classifier function and then performs a reduction operation on the values associated with a given key as per the specified downstream Collector and returns the Collector."
},
{
"code": null,
"e": 11950,
"s": 11854,
"text": "10. Collector joining(): Concatenates the input elements into a String and returns a Collector."
},
{
"code": null,
"e": 12093,
"s": 11950,
"text": "11. Collector joining(CharSequence delimiter): Concatenates the input elements, separated by the specified delimiter, and returns a Collector."
},
{
"code": "// Java program to implement the// joining() methodimport java.util.ArrayList;import java.util.List;import java.util.stream.Collectors; public class GFG { public static void main(String[] args) { // Concatenate the collection with // comma System.out.println(prepareTemperature() .stream() .filter(city -> city.getTemperature() > 10) .map(f -> f.getName()) .collect(Collectors.joining(\", \"))); }}",
"e": 12585,
"s": 12093,
"text": null
},
{
"code": null,
"e": 12593,
"s": 12585,
"text": "Output:"
},
{
"code": null,
"e": 12668,
"s": 12593,
"text": "New Delhi, Mexico, New York, Dubai, London, Kolkata, Sydney, Mexico, Dubai"
},
{
"code": null,
"e": 12893,
"s": 12668,
"text": "12. Collector joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix): Concatenates the input elements, separated by the specified delimiter, as per the specified prefix and suffix, and returns a Collector."
},
{
"code": "// Java program to implement the// joining() methodimport java.util.ArrayList;import java.util.List;import java.util.stream.Collectors; public class GFG { public static void main(String[] args) { System.out.println(prepareTemperature() .stream() .filter(city -> city.getTemperature() > 10) .map(f -> f.getName()) .collect(Collectors.joining(\" \", \"Prefix:\", \":Suffix\"))); }}",
"e": 13364,
"s": 12893,
"text": null
},
{
"code": null,
"e": 13372,
"s": 13364,
"text": "Output:"
},
{
"code": null,
"e": 13453,
"s": 13372,
"text": "Prefix:New Delhi Mexico New York Dubai London Kolkata Sydney Mexico Dubai:Suffix"
},
{
"code": null,
"e": 13687,
"s": 13453,
"text": "13. Collector mapping(Function mapper, Collector downstream): Transforms a Collector of the input elements of type U to one the input elements of type T by applying a mapping function to every input element before the transformation."
},
{
"code": "// Java program to implement the// mapping() methodimport java.util.ArrayList;import java.util.List;import java.util.stream.Collectors; public class GFG { public static void main(String[] args) { System.out.println(prepareTemperature() .stream() .collect(Collectors.groupingBy( City::getName, Collectors.mapping( City::getTemperature, Collectors.toList())))); }}",
"e": 14217,
"s": 13687,
"text": null
},
{
"code": null,
"e": 14225,
"s": 14217,
"text": "Output:"
},
{
"code": null,
"e": 14362,
"s": 14225,
"text": "{New York=[13.0], New Delhi=[33.5], London=[15.0], Alaska=[1.0], Mexico=[14.0, 14.0], Kolkata=[30.0], Dubai=[43.0, 43.0], Sydney=[11.0]}"
},
{
"code": null,
"e": 14760,
"s": 14362,
"text": "In the above output, each city group contains only the temperature, and this is done with the help ofmapping() method, which takes two function argument of type function and collector. Above mapping method return a list and finally the return type of the above groupingBy() method becomes Map<String, List>. We can also use toSet() method to get the set of elements instead of the list as follows:"
},
{
"code": "// Java program to implement the// joining() method import java.util.ArrayList;import java.util.List;import java.util.stream.Collectors; public class GFG { public static void main(String[] args) { System.out.println(prepareTemperature() .stream() .collect(Collectors.groupingBy( City::getName, Collectors.mapping( City::getTemperature, Collectors.toSet())))); }}",
"e": 15300,
"s": 14760,
"text": null
},
{
"code": null,
"e": 15308,
"s": 15300,
"text": "Output:"
},
{
"code": null,
"e": 15433,
"s": 15308,
"text": "{New York=[13.0], New Delhi=[33.5], London=[15.0], Alaska=[1.0], Mexico=[14.0], Kolkata=[30.0], Dubai=[43.0], Sydney=[11.0]}"
},
{
"code": null,
"e": 15622,
"s": 15433,
"text": "If we observe the output and compare it from the previous one, the duplicates have been removed because it is a set now. The return type of above groupingBy() now becomes Map<String, Set>."
},
{
"code": null,
"e": 15816,
"s": 15622,
"text": "14. Collector<T, ?, Map<Boolean, List>> partitioningBy(Predicate predicate): Partitions the input elements as per the passed Predicate, and transforms them into a Map and returns the Collector."
},
{
"code": "// Java program to implement the// partitioningBy() methodimport java.util.ArrayList;import java.util.List;import java.util.stream.Collectors; public class GFG { public static void main(String[] args) { // Here, we are partitioning the list // in two groups i.e., Cities having // temperatures more than 15 // and other than that. System.out.println(prepareTemperature() .stream() .collect(Collectors.partitioningBy( city -> city.getTemperature() > 15))); }}",
"e": 16381,
"s": 15816,
"text": null
},
{
"code": null,
"e": 16389,
"s": 16381,
"text": "Output:"
},
{
"code": null,
"e": 16558,
"s": 16389,
"text": "{false=[Mexico–> 14.0, New York–> 13.0, London–> 15.0, Alaska–> 1.0, Sydney–> 11.0, Mexico–> 14.0], true=[New Delhi–> 33.5, Dubai–> 43.0, Kolkata–> 30.0, Dubai–> 43.0]}"
},
{
"code": null,
"e": 16873,
"s": 16558,
"text": "15. Collector partitioningBy(Predicate predicate, Collector downstream): Partitions the input elements as per the passed Predicate, and collects the values of each partition as per another Collector, and transforms them into a Map whose values are the results of the downstream reduction and then return Collector."
},
{
"code": null,
"e": 17027,
"s": 16873,
"text": "16. Collector averagingDouble(ToDoubleFunction mapper): Performs the average of the input elements of type Double, and returns the Collector as a result."
},
{
"code": null,
"e": 17172,
"s": 17027,
"text": "17. Collector averagingInt(ToIntFunction mapper): Performs the average of the input elements of type Int, and returns the Collector as a result."
},
{
"code": null,
"e": 17320,
"s": 17172,
"text": "18. Collector averagingLong(ToLongFunction mapper): Performs the average of the input elements of type Long, and returns the Collector as a result."
},
{
"code": null,
"e": 17573,
"s": 17320,
"text": "19. Collector<T, ?, ConcurrentMap<K, List>> groupingByConcurrent(Function classifier): Performs group by operation on the input elements of type T, the grouping of elements is done as per the passed classifier function and returns concurrent Collector."
},
{
"code": null,
"e": 17966,
"s": 17573,
"text": "20. Collector<T, ?, ConcurrentMap> groupingByConcurrent(Function classifier, Collector downstream): Performs group by operation on the input elements of type T, the grouping of elements is done as per the passed classifier function, and then performs a reduction operation on the values associated with a given key as per the specified downstream Collector and returns a concurrent Collector."
},
{
"code": null,
"e": 18355,
"s": 17966,
"text": "21. Collector groupingByConcurrent(Function classifier, Supplier mapFactory, Collector downstream): Performs group by operation on input elements of type T, the grouping of elements is done as per the passed classifier function, and then performs a reduction operation on the values associated with a given key as per the specified downstream Collector and returns a concurrent Collector."
},
{
"code": null,
"e": 18495,
"s": 18355,
"text": "22. Collector reducing(BinaryOperator op): Performs a reduction of its input elements as per passed BinaryOperator and returns a Collector."
},
{
"code": null,
"e": 18676,
"s": 18495,
"text": "23. Collector reducing(T identity, BinaryOperator op): Performs a reduction of its input elements as per passed BinaryOperator and as per the passed identity and returns Collector."
},
{
"code": null,
"e": 18821,
"s": 18676,
"text": "24. Collector<T, ?, Optional> maxBy(Comparator comparator): Produces the maximal element as per given Comparator, returns an Optional Collector."
},
{
"code": null,
"e": 18966,
"s": 18821,
"text": "25. Collector<T, ?, Optional> minBy(Comparator comparator): Produces the minimal element as per given Comparator, returns an Optional Collector."
},
{
"code": null,
"e": 19228,
"s": 18966,
"text": "26. Collector<T, ?, ConcurrentMap> toConcurrentMap(Function keyMapper, Function valueMapper): Transforms elements into a ConcurrentMap whose keys and values are the results of the passed mapper functions to the input elements and returns a concurrent Collector."
},
{
"code": null,
"e": 19314,
"s": 19228,
"text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html"
},
{
"code": null,
"e": 19330,
"s": 19314,
"text": "Java-Collectors"
},
{
"code": null,
"e": 19335,
"s": 19330,
"text": "Java"
},
{
"code": null,
"e": 19340,
"s": 19335,
"text": "Java"
},
{
"code": null,
"e": 19438,
"s": 19340,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 19489,
"s": 19438,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 19520,
"s": 19489,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 19539,
"s": 19520,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 19569,
"s": 19539,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 19587,
"s": 19569,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 19607,
"s": 19587,
"text": "Collections in Java"
},
{
"code": null,
"e": 19631,
"s": 19607,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 19663,
"s": 19631,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 19675,
"s": 19663,
"text": "Set in Java"
}
] |
PyQt5 QSpinBox – Editing Finished Signal
|
03 Jan, 2022
In this article we will see how we can use the editing finished signal of the spin box, editing finished is the signal generated by the spin box when enter is pressed. We know we can ad action to the spin box when its value get changed but calling a method every time the value get changed is no required sometimes method should get called only when value is set and enter is pressed i.e editing is finished of spin box.
In order to do this we use editingFinished.connec method.
Syntax : spin_box.editingFinished.connect(method_name)
Argument : It takes method name as argument as argument
Action Performed : It calls the passed method every time editing is finished
Below is the implementation
Python3
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating spin box self.spin = QSpinBox(self) # setting geometry to spin box self.spin.setGeometry(100, 100, 250, 40) # setting prefix to spin self.spin.setPrefix("Prefix ") # setting suffix to spin self.spin.setSuffix(" Suffix") # creating a label self.label = QLabel("Label ", self) # setting geometry to the label self.label.setGeometry(100, 150, 300, 70) # adding action when editing get finished self.spin.editingFinished.connect(self.do_action) # method called after editing finished def do_action(self): # getting current value of spin box current = self.spin.value() self.label.setText("Editing finished, final value : " + str(current)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
anikakapoor
Python PyQt-SpinBox
Python-gui
Python-PyQt
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
Python OOPs Concepts
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Jan, 2022"
},
{
"code": null,
"e": 449,
"s": 28,
"text": "In this article we will see how we can use the editing finished signal of the spin box, editing finished is the signal generated by the spin box when enter is pressed. We know we can ad action to the spin box when its value get changed but calling a method every time the value get changed is no required sometimes method should get called only when value is set and enter is pressed i.e editing is finished of spin box."
},
{
"code": null,
"e": 507,
"s": 449,
"text": "In order to do this we use editingFinished.connec method."
},
{
"code": null,
"e": 562,
"s": 507,
"text": "Syntax : spin_box.editingFinished.connect(method_name)"
},
{
"code": null,
"e": 618,
"s": 562,
"text": "Argument : It takes method name as argument as argument"
},
{
"code": null,
"e": 695,
"s": 618,
"text": "Action Performed : It calls the passed method every time editing is finished"
},
{
"code": null,
"e": 723,
"s": 695,
"text": "Below is the implementation"
},
{
"code": null,
"e": 731,
"s": 723,
"text": "Python3"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating spin box self.spin = QSpinBox(self) # setting geometry to spin box self.spin.setGeometry(100, 100, 250, 40) # setting prefix to spin self.spin.setPrefix(\"Prefix \") # setting suffix to spin self.spin.setSuffix(\" Suffix\") # creating a label self.label = QLabel(\"Label \", self) # setting geometry to the label self.label.setGeometry(100, 150, 300, 70) # adding action when editing get finished self.spin.editingFinished.connect(self.do_action) # method called after editing finished def do_action(self): # getting current value of spin box current = self.spin.value() self.label.setText(\"Editing finished, final value : \" + str(current)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 2187,
"s": 731,
"text": null
},
{
"code": null,
"e": 2196,
"s": 2187,
"text": "Output :"
},
{
"code": null,
"e": 2208,
"s": 2196,
"text": "anikakapoor"
},
{
"code": null,
"e": 2228,
"s": 2208,
"text": "Python PyQt-SpinBox"
},
{
"code": null,
"e": 2239,
"s": 2228,
"text": "Python-gui"
},
{
"code": null,
"e": 2251,
"s": 2239,
"text": "Python-PyQt"
},
{
"code": null,
"e": 2258,
"s": 2251,
"text": "Python"
},
{
"code": null,
"e": 2356,
"s": 2258,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2374,
"s": 2356,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2416,
"s": 2374,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2438,
"s": 2416,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2473,
"s": 2438,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2499,
"s": 2473,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2531,
"s": 2499,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2560,
"s": 2531,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2587,
"s": 2560,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2617,
"s": 2587,
"text": "Iterate over a list in Python"
}
] |
Area of intersection of two circles | Practice | GeeksforGeeks
|
Given the coordinates of the centres of two circles (X1, Y1) and (X2, Y2) as well as the radii of the respective circles R1 and R2.Find the floor of the area of their intersection.
Note: Use the value of Pi as 3.14
Example 1:
Input:
X1=0,Y1=0,R1=4
X2=6,Y2=0,R2=4
Output:
7
Explanation:
The intersecting area equals 7.25298806.
So,Answer is 7.
Example 2:
Input:
X1=0,Y1=0,R1=5
X2=11,Y2=0,R2=5
Output:
0
Explanation:
The circles don't intersect.
Your Task:
You don't need to read input or print anything. Your task is to complete the function intersectionArea() which takes the coordinates of the centers as well as the radii(X1, Y1, R1, X2, Y2, R2) as input parameters and returns the area of intersection of the two circles.
Expected Time Complexity:O(LogN)
Expected Auxillary Space:O(1)
Constraints:
-109<=X1,Y1,X2,Y2<=109
1<=R1,R2<=109
-3
Naveen Kotha11 months agolong double Pi = 3.14; long double d, alpha, beta, a1, a2; long long int ans; d = sqrt((X2 - X1) * (X2 - X1) + (Y2 - Y1) * (Y2 - Y1)); if (d > R1 + R2) ans = 0; else if (d <= abs(R2 - R1) && R1 >= R2) ans = floor(Pi * R2 * R2); else if (d <= abs(R2 - R1) && R2 >= R1) ans = floor(Pi * R1 * R1); else { alpha = acos((R1 * R1 + d * d - R2 * R2) / (2 * R1 * d)) * 2; beta = acos((R2 * R2 + d * d - R1 * R1) / (2 * R2 * d)) * 2; a1 = 0.5 * beta * R2 * R2 - 0.5 * R2 * R2 * sin(beta); a2 = 0.5 * alpha * R1 * R1 - 0.5 * R1 * R1 * sin(alpha); ans = floor(a1 + a2); } return ans;Reply Open ExternallyShow 0 RepliesLoading...
Naveen Kotha
long double Pi = 3.14; long double d, alpha, beta, a1, a2; long long int ans; d = sqrt((X2 - X1) * (X2 - X1) + (Y2 - Y1) * (Y2 - Y1));
if (d > R1 + R2) ans = 0; else if (d <= abs(R2 - R1) && R1 >= R2) ans = floor(Pi * R2 * R2);
else if (d <= abs(R2 - R1) && R2 >= R1) ans = floor(Pi * R1 * R1);
else { alpha = acos((R1 * R1 + d * d - R2 * R2) / (2 * R1 * d)) * 2; beta = acos((R2 * R2 + d * d - R1 * R1) / (2 * R2 * d)) * 2; a1 = 0.5 * beta * R2 * R2 - 0.5 * R2 * R2 * sin(beta); a2 = 0.5 * alpha * R1 * R1 - 0.5 * R1 * R1 * sin(alpha); ans = floor(a1 + a2); } return ans;
-2
Hazem5 years agoThere are three more cases not mentioned in the solution here http://code.geeksforgeeks.o... (and by the way, most solutions I found online). They are:- d is less than one radius but larger than the other- d is less than both radiiIn either case, one circle is almost inside the other. The intersection area is then the area of the smaller circle minus the difference of the circular segments (i.e. minus area(r1,r2,d)-area(r2,r1,d))Reply Open ExternallyShow 0 RepliesLoading...
Hazem
There are three more cases not mentioned in the solution here http://code.geeksforgeeks.o... (and by the way, most solutions I found online). They are:
- d is less than one radius but larger than the other- d is less than both radii
In either case, one circle is almost inside the other. The intersection area is then the area of the smaller circle minus the difference of the circular segments (i.e. minus area(r1,r2,d)-area(r2,r1,d))
0
Quandray5 years agoInput:-11786939 388749051 844435993 -11696460 388789113 844535886Its Correct output is:2240182216213578196And Your Output is:2240182216213578283For this test case, the smaller circle is inside the larger, so the overlap is the area of the smaller circle. 844435993*844435993*pi.I make that 2240182216213578283.58.In my code I have the lineconst long double pi=3.1415926535897932384L;With that line, I get the answer 2240182216213578283If I remove the L from the end of that line, pi is shortened and I get the expected, but wrong, answer 2240182216213578196.Please can someone correct this.Reply Open ExternallyShow 0 RepliesLoading...
Quandray
Input:-11786939 388749051 844435993 -11696460 388789113 844535886
Its Correct output is:2240182216213578196
And Your Output is:2240182216213578283
For this test case, the smaller circle is inside the larger, so the overlap is the area of the smaller circle. 844435993*844435993*pi.I make that 2240182216213578283.58.
In my code I have the lineconst long double pi=3.1415926535897932384L;With that line, I get the answer 2240182216213578283If I remove the L from the end of that line, pi is shortened and I get the expected, but wrong, answer 2240182216213578196.Please can someone correct this.
-2
张昆玮6 years agoI think my solution is correct. http://code.geeksforgeeks.o... . How can you show the expected output is more accurate than my solution?Reply Open ExternallyShow 1 RepliesLoading...
张昆玮
I think my solution is correct. http://code.geeksforgeeks.o... . How can you show the expected output is more accurate than my solution?
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
On submission, your code is tested against multiple test cases consisting of all
possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the
correctness of code. On submission, your code is tested against multiple test cases
consisting of all possible corner cases and stress constraints.
|
[
{
"code": null,
"e": 441,
"s": 226,
"text": "Given the coordinates of the centres of two circles (X1, Y1) and (X2, Y2) as well as the radii of the respective circles R1 and R2.Find the floor of the area of their intersection.\nNote: Use the value of Pi as 3.14"
},
{
"code": null,
"e": 452,
"s": 441,
"text": "Example 1:"
},
{
"code": null,
"e": 569,
"s": 452,
"text": "Input:\nX1=0,Y1=0,R1=4\nX2=6,Y2=0,R2=4\nOutput:\n7\nExplanation:\nThe intersecting area equals 7.25298806.\nSo,Answer is 7."
},
{
"code": null,
"e": 580,
"s": 569,
"text": "Example 2:"
},
{
"code": null,
"e": 670,
"s": 580,
"text": "Input:\nX1=0,Y1=0,R1=5\nX2=11,Y2=0,R2=5\nOutput:\n0\nExplanation:\nThe circles don't intersect."
},
{
"code": null,
"e": 952,
"s": 670,
"text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function intersectionArea() which takes the coordinates of the centers as well as the radii(X1, Y1, R1, X2, Y2, R2) as input parameters and returns the area of intersection of the two circles."
},
{
"code": null,
"e": 1016,
"s": 952,
"text": "\nExpected Time Complexity:O(LogN)\nExpected Auxillary Space:O(1)"
},
{
"code": null,
"e": 1067,
"s": 1016,
"text": "\nConstraints:\n-109<=X1,Y1,X2,Y2<=109\n1<=R1,R2<=109"
},
{
"code": null,
"e": 1070,
"s": 1067,
"text": "-3"
},
{
"code": null,
"e": 1853,
"s": 1070,
"text": "Naveen Kotha11 months agolong double Pi = 3.14; long double d, alpha, beta, a1, a2; long long int ans; d = sqrt((X2 - X1) * (X2 - X1) + (Y2 - Y1) * (Y2 - Y1)); if (d > R1 + R2) ans = 0; else if (d <= abs(R2 - R1) && R1 >= R2) ans = floor(Pi * R2 * R2); else if (d <= abs(R2 - R1) && R2 >= R1) ans = floor(Pi * R1 * R1); else { alpha = acos((R1 * R1 + d * d - R2 * R2) / (2 * R1 * d)) * 2; beta = acos((R2 * R2 + d * d - R1 * R1) / (2 * R2 * d)) * 2; a1 = 0.5 * beta * R2 * R2 - 0.5 * R2 * R2 * sin(beta); a2 = 0.5 * alpha * R1 * R1 - 0.5 * R1 * R1 * sin(alpha); ans = floor(a1 + a2); } return ans;Reply Open ExternallyShow 0 RepliesLoading..."
},
{
"code": null,
"e": 1866,
"s": 1853,
"text": "Naveen Kotha"
},
{
"code": null,
"e": 2022,
"s": 1866,
"text": "long double Pi = 3.14; long double d, alpha, beta, a1, a2; long long int ans; d = sqrt((X2 - X1) * (X2 - X1) + (Y2 - Y1) * (Y2 - Y1));"
},
{
"code": null,
"e": 2142,
"s": 2022,
"text": " if (d > R1 + R2) ans = 0; else if (d <= abs(R2 - R1) && R1 >= R2) ans = floor(Pi * R2 * R2);"
},
{
"code": null,
"e": 2228,
"s": 2142,
"text": " else if (d <= abs(R2 - R1) && R2 >= R1) ans = floor(Pi * R1 * R1);"
},
{
"code": null,
"e": 2582,
"s": 2228,
"text": " else { alpha = acos((R1 * R1 + d * d - R2 * R2) / (2 * R1 * d)) * 2; beta = acos((R2 * R2 + d * d - R1 * R1) / (2 * R2 * d)) * 2; a1 = 0.5 * beta * R2 * R2 - 0.5 * R2 * R2 * sin(beta); a2 = 0.5 * alpha * R1 * R1 - 0.5 * R1 * R1 * sin(alpha); ans = floor(a1 + a2); } return ans;"
},
{
"code": null,
"e": 2585,
"s": 2582,
"text": "-2"
},
{
"code": null,
"e": 3080,
"s": 2585,
"text": "Hazem5 years agoThere are three more cases not mentioned in the solution here http://code.geeksforgeeks.o... (and by the way, most solutions I found online). They are:- d is less than one radius but larger than the other- d is less than both radiiIn either case, one circle is almost inside the other. The intersection area is then the area of the smaller circle minus the difference of the circular segments (i.e. minus area(r1,r2,d)-area(r2,r1,d))Reply Open ExternallyShow 0 RepliesLoading..."
},
{
"code": null,
"e": 3086,
"s": 3080,
"text": "Hazem"
},
{
"code": null,
"e": 3238,
"s": 3086,
"text": "There are three more cases not mentioned in the solution here http://code.geeksforgeeks.o... (and by the way, most solutions I found online). They are:"
},
{
"code": null,
"e": 3319,
"s": 3238,
"text": "- d is less than one radius but larger than the other- d is less than both radii"
},
{
"code": null,
"e": 3522,
"s": 3319,
"text": "In either case, one circle is almost inside the other. The intersection area is then the area of the smaller circle minus the difference of the circular segments (i.e. minus area(r1,r2,d)-area(r2,r1,d))"
},
{
"code": null,
"e": 3524,
"s": 3522,
"text": "0"
},
{
"code": null,
"e": 4181,
"s": 3524,
"text": "Quandray5 years agoInput:-11786939 388749051 844435993 -11696460 388789113 844535886Its Correct output is:2240182216213578196And Your Output is:2240182216213578283For this test case, the smaller circle is inside the larger, so the overlap is the area of the smaller circle. 844435993*844435993*pi.I make that 2240182216213578283.58.In my code I have the lineconst long double pi=3.1415926535897932384L;With that line, I get the answer 2240182216213578283If I remove the L from the end of that line, pi is shortened and I get the expected, but wrong, answer 2240182216213578196.Please can someone correct this.Reply Open ExternallyShow 0 RepliesLoading..."
},
{
"code": null,
"e": 4190,
"s": 4181,
"text": "Quandray"
},
{
"code": null,
"e": 4256,
"s": 4190,
"text": "Input:-11786939 388749051 844435993 -11696460 388789113 844535886"
},
{
"code": null,
"e": 4298,
"s": 4256,
"text": "Its Correct output is:2240182216213578196"
},
{
"code": null,
"e": 4337,
"s": 4298,
"text": "And Your Output is:2240182216213578283"
},
{
"code": null,
"e": 4509,
"s": 4337,
"text": "For this test case, the smaller circle is inside the larger, so the overlap is the area of the smaller circle. 844435993*844435993*pi.I make that 2240182216213578283.58."
},
{
"code": null,
"e": 4787,
"s": 4509,
"text": "In my code I have the lineconst long double pi=3.1415926535897932384L;With that line, I get the answer 2240182216213578283If I remove the L from the end of that line, pi is shortened and I get the expected, but wrong, answer 2240182216213578196.Please can someone correct this."
},
{
"code": null,
"e": 4790,
"s": 4787,
"text": "-2"
},
{
"code": null,
"e": 4986,
"s": 4790,
"text": "张昆玮6 years agoI think my solution is correct. http://code.geeksforgeeks.o... . How can you show the expected output is more accurate than my solution?Reply Open ExternallyShow 1 RepliesLoading..."
},
{
"code": null,
"e": 4990,
"s": 4986,
"text": "张昆玮"
},
{
"code": null,
"e": 5127,
"s": 4990,
"text": "I think my solution is correct. http://code.geeksforgeeks.o... . How can you show the expected output is more accurate than my solution?"
},
{
"code": null,
"e": 5273,
"s": 5127,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 5309,
"s": 5273,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5319,
"s": 5309,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5329,
"s": 5319,
"text": "\nContest\n"
},
{
"code": null,
"e": 5392,
"s": 5329,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5577,
"s": 5392,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 5861,
"s": 5577,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 6007,
"s": 5861,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 6084,
"s": 6007,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 6125,
"s": 6084,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 6153,
"s": 6125,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 6224,
"s": 6153,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 6411,
"s": 6224,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
] |
How to get text of a tag in selenium – Python?
|
24 Jan, 2021
Selenium is a powerful tool for controlling web browsers through programs and performing browser automation. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e Python, Java, C#, etc, we will be working with Python.
In this article, we will write a Python Script for getting the text from the tag name using selenium module. We will be getting the tag text from this URL.
Step #1: Import required libraries
Python3
# Import Libraryfrom selenium import webdriver
Step #2: Create a Chrome object or specify web driver path if it is not present in the default path and assign URL.
Python3
# Chrome Pathdriver = webdriver.Chrome('Enter Chrome Path') # Web URLdriver.get('Enter Web URL')
Step #3: Specify the tag name, which you want to extract the text.
Syntax:
Object Name.find_element_by_tag_name(Tag Name)
Python3
# Get Textprint (element.text) # Close the windowdriver.close()
Below is the implementation.
Python3
# Import Libraryfrom selenium import webdriver # Chrome Pathdriver = webdriver.Chrome() # Web URLdriver.get('https://phptravels.com/demo/') element = driver.find_element_by_tag_name('a') # Get Textprint(element.text) # Close the windowdriver.close()
Output:
Picked
Python-selenium
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
Create a directory in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Jan, 2021"
},
{
"code": null,
"e": 302,
"s": 28,
"text": "Selenium is a powerful tool for controlling web browsers through programs and performing browser automation. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e Python, Java, C#, etc, we will be working with Python."
},
{
"code": null,
"e": 458,
"s": 302,
"text": "In this article, we will write a Python Script for getting the text from the tag name using selenium module. We will be getting the tag text from this URL."
},
{
"code": null,
"e": 493,
"s": 458,
"text": "Step #1: Import required libraries"
},
{
"code": null,
"e": 501,
"s": 493,
"text": "Python3"
},
{
"code": "# Import Libraryfrom selenium import webdriver",
"e": 548,
"s": 501,
"text": null
},
{
"code": null,
"e": 664,
"s": 548,
"text": "Step #2: Create a Chrome object or specify web driver path if it is not present in the default path and assign URL."
},
{
"code": null,
"e": 672,
"s": 664,
"text": "Python3"
},
{
"code": "# Chrome Pathdriver = webdriver.Chrome('Enter Chrome Path') # Web URLdriver.get('Enter Web URL')",
"e": 770,
"s": 672,
"text": null
},
{
"code": null,
"e": 838,
"s": 770,
"text": "Step #3: Specify the tag name, which you want to extract the text. "
},
{
"code": null,
"e": 846,
"s": 838,
"text": "Syntax:"
},
{
"code": null,
"e": 893,
"s": 846,
"text": "Object Name.find_element_by_tag_name(Tag Name)"
},
{
"code": null,
"e": 901,
"s": 893,
"text": "Python3"
},
{
"code": "# Get Textprint (element.text) # Close the windowdriver.close()",
"e": 966,
"s": 901,
"text": null
},
{
"code": null,
"e": 995,
"s": 966,
"text": "Below is the implementation."
},
{
"code": null,
"e": 1003,
"s": 995,
"text": "Python3"
},
{
"code": "# Import Libraryfrom selenium import webdriver # Chrome Pathdriver = webdriver.Chrome() # Web URLdriver.get('https://phptravels.com/demo/') element = driver.find_element_by_tag_name('a') # Get Textprint(element.text) # Close the windowdriver.close()",
"e": 1258,
"s": 1003,
"text": null
},
{
"code": null,
"e": 1266,
"s": 1258,
"text": "Output:"
},
{
"code": null,
"e": 1273,
"s": 1266,
"text": "Picked"
},
{
"code": null,
"e": 1289,
"s": 1273,
"text": "Python-selenium"
},
{
"code": null,
"e": 1296,
"s": 1289,
"text": "Python"
},
{
"code": null,
"e": 1394,
"s": 1296,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1426,
"s": 1394,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1453,
"s": 1426,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1474,
"s": 1453,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1497,
"s": 1474,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1553,
"s": 1497,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1584,
"s": 1553,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1626,
"s": 1584,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1668,
"s": 1626,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1707,
"s": 1668,
"text": "Python | Get unique values from a list"
}
] |
std::divides in C++
|
06 Aug, 2017
Function object for performing division. Effectively calls operator / on two instances of type T.
Syntax :
template struct divides : binary_function
{
T operator() (const T& x, const T& y) const {return x/y;}
};
Template Parameters :
T - Type of the arguments and return type of the functional call.
The type shall support the operation (operator /).
Member types :
x : Type of the first argument in member operator()
y : Type of the second argument in member operator()
result_type : Type returned by member operator()
Example :
// C++ program to illustrate std::divides// by dividing the respective elements of 2 arrays#include <iostream> // std::cout#include <functional> // std::divides#include <algorithm> // std::transform int main(){ // First array int first[] = { 10, 20, 30, 40, 50 }; // Second array int second[] = { 1, 2, 3, 4, 5 }; // Result array int results[5]; // std::transform applies std::divides to the whole array std::transform(first, first + 5, second, results, std::divides<int>()); // Printing the result array for (int i = 0; i < 5; i++) std::cout << results[i] << " "; return 0;}
Output:
10 10 10 10 10
Another Example :
// C++ program to illustrate std::divides// by dividing all array elements with a number#include <bits/stdc++.h> int main(){ // Array with elements to be divided int arr[] = { 10, 10 }; // size of array int size = sizeof(arr) / sizeof(arr[0]); // Variable with which array is to be divided int num = 100; // Variable to store result int result; // using std::accumulate to perform division on array with num // using std::divides result = std::accumulate(arr, arr + size, num, std::divides<int>()); // Printing the result std::cout << "The result of (100 / 10) / 10 is " << result; return 0;}
Output:
The result of (100 / 10) / 10 is 1
This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Pair in C++ Standard Template Library (STL)
Friend class and function in C++
std::string class in C++
Queue in C++ Standard Template Library (STL)
std::find in C++
Unordered Sets in C++ Standard Template Library
List in C++ Standard Template Library (STL)
vector insert() function in C++ STL
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Aug, 2017"
},
{
"code": null,
"e": 126,
"s": 28,
"text": "Function object for performing division. Effectively calls operator / on two instances of type T."
},
{
"code": null,
"e": 135,
"s": 126,
"text": "Syntax :"
},
{
"code": null,
"e": 563,
"s": 135,
"text": "\ntemplate struct divides : binary_function \n{\n T operator() (const T& x, const T& y) const {return x/y;}\n};\n\nTemplate Parameters :\nT - Type of the arguments and return type of the functional call.\n The type shall support the operation (operator /).\n\nMember types :\nx : Type of the first argument in member operator()\ny : Type of the second argument in member operator()\nresult_type : Type returned by member operator()\n"
},
{
"code": null,
"e": 573,
"s": 563,
"text": "Example :"
},
{
"code": "// C++ program to illustrate std::divides// by dividing the respective elements of 2 arrays#include <iostream> // std::cout#include <functional> // std::divides#include <algorithm> // std::transform int main(){ // First array int first[] = { 10, 20, 30, 40, 50 }; // Second array int second[] = { 1, 2, 3, 4, 5 }; // Result array int results[5]; // std::transform applies std::divides to the whole array std::transform(first, first + 5, second, results, std::divides<int>()); // Printing the result array for (int i = 0; i < 5; i++) std::cout << results[i] << \" \"; return 0;}",
"e": 1200,
"s": 573,
"text": null
},
{
"code": null,
"e": 1208,
"s": 1200,
"text": "Output:"
},
{
"code": null,
"e": 1223,
"s": 1208,
"text": "10 10 10 10 10"
},
{
"code": null,
"e": 1241,
"s": 1223,
"text": "Another Example :"
},
{
"code": "// C++ program to illustrate std::divides// by dividing all array elements with a number#include <bits/stdc++.h> int main(){ // Array with elements to be divided int arr[] = { 10, 10 }; // size of array int size = sizeof(arr) / sizeof(arr[0]); // Variable with which array is to be divided int num = 100; // Variable to store result int result; // using std::accumulate to perform division on array with num // using std::divides result = std::accumulate(arr, arr + size, num, std::divides<int>()); // Printing the result std::cout << \"The result of (100 / 10) / 10 is \" << result; return 0;}",
"e": 1889,
"s": 1241,
"text": null
},
{
"code": null,
"e": 1897,
"s": 1889,
"text": "Output:"
},
{
"code": null,
"e": 1933,
"s": 1897,
"text": "The result of (100 / 10) / 10 is 1\n"
},
{
"code": null,
"e": 2236,
"s": 1933,
"text": "This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 2361,
"s": 2236,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 2365,
"s": 2361,
"text": "STL"
},
{
"code": null,
"e": 2369,
"s": 2365,
"text": "C++"
},
{
"code": null,
"e": 2373,
"s": 2369,
"text": "STL"
},
{
"code": null,
"e": 2377,
"s": 2373,
"text": "CPP"
},
{
"code": null,
"e": 2475,
"s": 2377,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2499,
"s": 2475,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 2519,
"s": 2499,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 2563,
"s": 2519,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2596,
"s": 2563,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 2621,
"s": 2596,
"text": "std::string class in C++"
},
{
"code": null,
"e": 2666,
"s": 2621,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2683,
"s": 2666,
"text": "std::find in C++"
},
{
"code": null,
"e": 2731,
"s": 2683,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 2775,
"s": 2731,
"text": "List in C++ Standard Template Library (STL)"
}
] |
Material Design Text Input Field using Jetpack Compose in Android
|
06 Apr, 2021
Jetpack Compose is a modern toolkit for building native Android UI. Jetpack Compose simplifies and accelerates UI development on Android with less code, powerful tools, and intuitive Kotlin APIs. Compose is built to support material design principles. Many of its UI elements implement material design out of the box. In this article, we will explain how you can create Material design Text Input Fields using Jetpack Compose. Below is the sample picture to show what we are going to build.
Step 1: Create a new project
To create a new project in Android Studio using Jetpack Compose please refer to How to Create a New Project in Android Studio Canary Version with Jetpack Compose.
Step 2: Working with MainActivity.kt
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.os.Bundleimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.text.KeyboardOptionsimport androidx.compose.material.*import androidx.compose.material.MaterialTheme.typographyimport androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.filled.Editimport androidx.compose.material.icons.filled.Emailimport androidx.compose.runtime.*import androidx.compose.ui.Modifierimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.text.InternalTextApiimport androidx.compose.ui.text.input.KeyboardTypeimport androidx.compose.ui.text.input.PasswordVisualTransformationimport androidx.compose.ui.text.input.TextFieldValueimport androidx.compose.ui.tooling.preview.Previewimport androidx.compose.ui.unit.dpimport com.example.jetpackcomposepractice.ui.theme.JetpackComposePracticeTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { JetpackComposePracticeTheme { // A surface container using the 'background' color from the theme Surface(color = Color.White) { Column { // call the function which contains all the input fields TextInputs() } } } } }} @Composablefun TextInputs() { Column { Text(text = "Text Inputs", style = typography.h6, modifier = Modifier.padding(8.dp)) var text by remember { mutableStateOf(TextFieldValue("")) } // for preview add same text to all the fields // Normal Text Input field with floating label // placeholder is same as hint in xml of edit text TextField( value = text, onValueChange = { newValue -> text = newValue }, modifier = Modifier .padding(8.dp) .fillMaxWidth(), label = { Text("label") }, placeholder = { Text("placeholder") }, ) // Outlined Text Input Field OutlinedTextField( value = text, modifier = Modifier .padding(8.dp) .fillMaxWidth(), label = { Text(text = "Password") }, placeholder = { Text(text = "12334444") }, visualTransformation = PasswordVisualTransformation(), onValueChange = { text = it }, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password) ) // Outlined Input text with icon on the left // inside leadingIcon property add the icon OutlinedTextField( value = text, leadingIcon = { Icon(imageVector = Icons.Default.Email, contentDescription = null) }, modifier = Modifier .padding(8.dp) .fillMaxWidth(), keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text), label = { Text(text = "Email address") }, placeholder = { Text(text = "Your email") }, onValueChange = { text = it } ) // Outlined Input text with icon on the left and right // inside leadingIcon property add the left icon // inside trailingIcon property add right icon OutlinedTextField( value = text, leadingIcon = { Icon(imageVector = Icons.Default.Email, contentDescription = null) }, trailingIcon = { Icon(imageVector = Icons.Default.Edit, contentDescription = null) }, modifier = Modifier .padding(8.dp) .fillMaxWidth(), keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text), label = { Text(text = "Email address") }, placeholder = { Text(text = "Your email") }, onValueChange = { text = it } ) var numberText by remember { mutableStateOf(TextFieldValue("")) } // Outlined Text input field with input type number // It will open the number keyboard OutlinedTextField(value = numberText, modifier = Modifier .padding(8.dp) .fillMaxWidth(), keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), label = { Text(text = "Phone number") }, placeholder = { Text(text = "88888888") }, onValueChange = { numberText = it } ) }} @InternalTextApi@Preview@Composablefun PreviewInputs() { Column { TextInputs() }}
Output:
Android-Jetpack
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Android SDK and it's Components
How to Add Views Dynamically and Store Data in Arraylist in Android?
Flutter - Custom Bottom Navigation Bar
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android UI Layouts
Kotlin Array
Retrofit with Kotlin Coroutine in Android
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Apr, 2021"
},
{
"code": null,
"e": 521,
"s": 28,
"text": "Jetpack Compose is a modern toolkit for building native Android UI. Jetpack Compose simplifies and accelerates UI development on Android with less code, powerful tools, and intuitive Kotlin APIs. Compose is built to support material design principles. Many of its UI elements implement material design out of the box. In this article, we will explain how you can create Material design Text Input Fields using Jetpack Compose. Below is the sample picture to show what we are going to build. "
},
{
"code": null,
"e": 550,
"s": 521,
"text": "Step 1: Create a new project"
},
{
"code": null,
"e": 713,
"s": 550,
"text": "To create a new project in Android Studio using Jetpack Compose please refer to How to Create a New Project in Android Studio Canary Version with Jetpack Compose."
},
{
"code": null,
"e": 750,
"s": 713,
"text": "Step 2: Working with MainActivity.kt"
},
{
"code": null,
"e": 936,
"s": 750,
"text": "Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 943,
"s": 936,
"text": "Kotlin"
},
{
"code": "import android.os.Bundleimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.text.KeyboardOptionsimport androidx.compose.material.*import androidx.compose.material.MaterialTheme.typographyimport androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.filled.Editimport androidx.compose.material.icons.filled.Emailimport androidx.compose.runtime.*import androidx.compose.ui.Modifierimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.text.InternalTextApiimport androidx.compose.ui.text.input.KeyboardTypeimport androidx.compose.ui.text.input.PasswordVisualTransformationimport androidx.compose.ui.text.input.TextFieldValueimport androidx.compose.ui.tooling.preview.Previewimport androidx.compose.ui.unit.dpimport com.example.jetpackcomposepractice.ui.theme.JetpackComposePracticeTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { JetpackComposePracticeTheme { // A surface container using the 'background' color from the theme Surface(color = Color.White) { Column { // call the function which contains all the input fields TextInputs() } } } } }} @Composablefun TextInputs() { Column { Text(text = \"Text Inputs\", style = typography.h6, modifier = Modifier.padding(8.dp)) var text by remember { mutableStateOf(TextFieldValue(\"\")) } // for preview add same text to all the fields // Normal Text Input field with floating label // placeholder is same as hint in xml of edit text TextField( value = text, onValueChange = { newValue -> text = newValue }, modifier = Modifier .padding(8.dp) .fillMaxWidth(), label = { Text(\"label\") }, placeholder = { Text(\"placeholder\") }, ) // Outlined Text Input Field OutlinedTextField( value = text, modifier = Modifier .padding(8.dp) .fillMaxWidth(), label = { Text(text = \"Password\") }, placeholder = { Text(text = \"12334444\") }, visualTransformation = PasswordVisualTransformation(), onValueChange = { text = it }, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password) ) // Outlined Input text with icon on the left // inside leadingIcon property add the icon OutlinedTextField( value = text, leadingIcon = { Icon(imageVector = Icons.Default.Email, contentDescription = null) }, modifier = Modifier .padding(8.dp) .fillMaxWidth(), keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text), label = { Text(text = \"Email address\") }, placeholder = { Text(text = \"Your email\") }, onValueChange = { text = it } ) // Outlined Input text with icon on the left and right // inside leadingIcon property add the left icon // inside trailingIcon property add right icon OutlinedTextField( value = text, leadingIcon = { Icon(imageVector = Icons.Default.Email, contentDescription = null) }, trailingIcon = { Icon(imageVector = Icons.Default.Edit, contentDescription = null) }, modifier = Modifier .padding(8.dp) .fillMaxWidth(), keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text), label = { Text(text = \"Email address\") }, placeholder = { Text(text = \"Your email\") }, onValueChange = { text = it } ) var numberText by remember { mutableStateOf(TextFieldValue(\"\")) } // Outlined Text input field with input type number // It will open the number keyboard OutlinedTextField(value = numberText, modifier = Modifier .padding(8.dp) .fillMaxWidth(), keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), label = { Text(text = \"Phone number\") }, placeholder = { Text(text = \"88888888\") }, onValueChange = { numberText = it } ) }} @InternalTextApi@Preview@Composablefun PreviewInputs() { Column { TextInputs() }}",
"e": 5772,
"s": 943,
"text": null
},
{
"code": null,
"e": 5780,
"s": 5772,
"text": "Output:"
},
{
"code": null,
"e": 5796,
"s": 5780,
"text": "Android-Jetpack"
},
{
"code": null,
"e": 5804,
"s": 5796,
"text": "Android"
},
{
"code": null,
"e": 5811,
"s": 5804,
"text": "Kotlin"
},
{
"code": null,
"e": 5819,
"s": 5811,
"text": "Android"
},
{
"code": null,
"e": 5917,
"s": 5819,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5949,
"s": 5917,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 6018,
"s": 5949,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 6057,
"s": 6018,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 6099,
"s": 6057,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 6150,
"s": 6099,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 6219,
"s": 6150,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 6238,
"s": 6219,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 6251,
"s": 6238,
"text": "Kotlin Array"
}
] |
REST API Architectural Constraints
|
28 Jun, 2022
REST stands for REpresentational State Transfer and API stands for Application Program Interface. REST is a software architectural style that defines the set of rules to be used for creating web services. Web services which follow the REST architectural style are known as RESTful web services. It allows requesting systems to access and manipulate web resources by using a uniform and predefined set of rules. Interaction in REST based systems happen through Internet’s Hypertext Transfer Protocol (HTTP).
A Restful system consists of a:
client who requests for the resources.
server who has the resources.
It is important to create REST API according to industry standards which results in ease of development and increase client adoption.
Architectural Constraints of RESTful API: There are six architectural constraints which makes any web service are listed below:
Uniform Interface
Stateless
Cacheable
Client-Server
Layered System
Code on Demand
The only optional constraint of REST architecture is code on demand. If a service violates any other constraint, it cannot strictly be referred to as RESTful.
Uniform Interface: It is a key constraint that differentiate between a REST API and Non-REST API. It suggests that there should be an uniform way of interacting with a given server irrespective of device or type of application (website, mobile app).There are four guidelines principle of Uniform Interface are:
Resource-Based: Individual resources are identified in requests. For example: API/users.
Manipulation of Resources Through Representations: Client has representation of resource and it contains enough information to modify or delete the resource on the server, provided it has permission to do so. Example: Usually user get a user id when user request for a list of users and then use that id to delete or modify that particular user.
Self-descriptive Messages: Each message includes enough information to describe how to process the message so that server can easily analyses the request.
Hypermedia as the Engine of Application State (HATEOAS): It need to include links for each response so that client can discover other resources easily.
Stateless: It means that the necessary state to handle the request is contained within the request itself and server would not store anything related to the session. In REST, the client must include all information for the server to fulfill the request whether as a part of query params, headers or URI. Statelessness enables greater availability since the server does not have to maintain, update or communicate that session state. There is a drawback when the client need to send too much data to the server so it reduces the scope of network optimization and requires more bandwidth.
Cacheable: Every response should include whether the response is cacheable or not and for how much duration responses can be cached at the client side. Client will return the data from its cache for any subsequent request and there would be no need to send the request again to the server. A well-managed caching partially or completely eliminates some client–server interactions, further improving availability and performance. But sometime there are chances that user may receive stale data.
Client-Server: REST application should have a client-server architecture. A Client is someone who is requesting resources and are not concerned with data storage, which remains internal to each server, and server is someone who holds the resources and are not concerned with the user interface or user state. They can evolve independently. Client doesn’t need to know anything about business logic and server doesn’t need to know anything about frontend UI.
Layered system: An application architecture needs to be composed of multiple layers. Each layer doesn’t know any thing about any layer other than that of immediate layer and there can be lot of intermediate servers between client and the end server. Intermediary servers may improve system availability by enabling load-balancing and by providing shared caches.
Code on demand: It is an optional feature. According to this, servers can also provide executable code to the client. The examples of code on demand may include the compiled components such as Java applets and client-side scripts such as JavaScript.
Rules of REST API: There are certain rules which should be kept in mind while creating REST API endpoints.
REST is based on the resource or noun instead of action or verb based. It means that a URI of a REST API should always end with a noun. Example: /api/users is a good example, but /api?type=users is a bad example of creating a REST API.
HTTP verbs are used to identify the action. Some of the HTTP verbs are – GET, PUT, POST, DELETE, UPDATE, PATCH.
A web application should be organized into resources like users and then uses HTTP verbs like – GET, PUT, POST, DELETE to modify those resources. And as a developer it should be clear that what needs to be done just by looking at the endpoint and HTTP method used.URIHTTP verbDescriptionapi/usersGETGet all usersapi/users/newGETShow form for adding new userapi/usersPOSTAdd a userapi/users/1PUTUpdate a user with id = 1api/users/1/editGETShow edit form for user with id = 1api/users/1DELETEDelete a user with id = 1api/users/1GETGet a user with id = 1
Always use plurals in URL to keep an API URI consistent throughout the application.
Send a proper HTTP code to indicate a success or error status.
Note : You can easily use GET and POST but in order to use PUT and DELETE you will need to install method override. You can do this by following below code :
npm install method-override --save
This simply require this package in your code by writing :
var methodOverride = require("method-override");
Now you can easily use PUT and DELETE routes :
app.use(methodOverride("_method"));
HTTP verbs: Some of the common HTTP methods/verbs are described below:
GET: Retrieves one or more resources identified by the request URI and it can cache the information receive.
POST: Create a resource from the submission of a request and response is not cacheable in this case. This method is unsafe if no security is applied to the endpoint as it would allow anyone to create a random resource by submission.
PUT: Update an existing resource on the server specified by the request URI.
DELETE: Delete an existing resource on the server specified by the request URI. It always return an appropriate HTTP status for every request.
GET, PUT, DELETE methods are also known as Idempotent methods. Applying an operation once or applying it multiple times has the same effect. Example: Delete any resource from the server and it succeeds with 200 OK and then try again to delete that resource than it will display an error message 410 GONE.
MohdArsalan
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.readFileSync() Method
How to set the default value for an HTML <select> element ?
How do you run JavaScript script through the Terminal?
Node.js | fs.writeFileSync() Method
ReactJS setState()
Difference between var, let and const keywords in JavaScript
How to set space between the flexbox ?
How to create footer to stay at the bottom of a Web page?
Differences between Functional Components and Class Components in React
JavaScript | promise resolve() Method
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n28 Jun, 2022"
},
{
"code": null,
"e": 560,
"s": 53,
"text": "REST stands for REpresentational State Transfer and API stands for Application Program Interface. REST is a software architectural style that defines the set of rules to be used for creating web services. Web services which follow the REST architectural style are known as RESTful web services. It allows requesting systems to access and manipulate web resources by using a uniform and predefined set of rules. Interaction in REST based systems happen through Internet’s Hypertext Transfer Protocol (HTTP)."
},
{
"code": null,
"e": 592,
"s": 560,
"text": "A Restful system consists of a:"
},
{
"code": null,
"e": 631,
"s": 592,
"text": "client who requests for the resources."
},
{
"code": null,
"e": 661,
"s": 631,
"text": "server who has the resources."
},
{
"code": null,
"e": 795,
"s": 661,
"text": "It is important to create REST API according to industry standards which results in ease of development and increase client adoption."
},
{
"code": null,
"e": 923,
"s": 795,
"text": "Architectural Constraints of RESTful API: There are six architectural constraints which makes any web service are listed below:"
},
{
"code": null,
"e": 941,
"s": 923,
"text": "Uniform Interface"
},
{
"code": null,
"e": 951,
"s": 941,
"text": "Stateless"
},
{
"code": null,
"e": 961,
"s": 951,
"text": "Cacheable"
},
{
"code": null,
"e": 975,
"s": 961,
"text": "Client-Server"
},
{
"code": null,
"e": 990,
"s": 975,
"text": "Layered System"
},
{
"code": null,
"e": 1005,
"s": 990,
"text": "Code on Demand"
},
{
"code": null,
"e": 1164,
"s": 1005,
"text": "The only optional constraint of REST architecture is code on demand. If a service violates any other constraint, it cannot strictly be referred to as RESTful."
},
{
"code": null,
"e": 1475,
"s": 1164,
"text": "Uniform Interface: It is a key constraint that differentiate between a REST API and Non-REST API. It suggests that there should be an uniform way of interacting with a given server irrespective of device or type of application (website, mobile app).There are four guidelines principle of Uniform Interface are:"
},
{
"code": null,
"e": 1564,
"s": 1475,
"text": "Resource-Based: Individual resources are identified in requests. For example: API/users."
},
{
"code": null,
"e": 1910,
"s": 1564,
"text": "Manipulation of Resources Through Representations: Client has representation of resource and it contains enough information to modify or delete the resource on the server, provided it has permission to do so. Example: Usually user get a user id when user request for a list of users and then use that id to delete or modify that particular user."
},
{
"code": null,
"e": 2065,
"s": 1910,
"text": "Self-descriptive Messages: Each message includes enough information to describe how to process the message so that server can easily analyses the request."
},
{
"code": null,
"e": 2217,
"s": 2065,
"text": "Hypermedia as the Engine of Application State (HATEOAS): It need to include links for each response so that client can discover other resources easily."
},
{
"code": null,
"e": 2804,
"s": 2217,
"text": "Stateless: It means that the necessary state to handle the request is contained within the request itself and server would not store anything related to the session. In REST, the client must include all information for the server to fulfill the request whether as a part of query params, headers or URI. Statelessness enables greater availability since the server does not have to maintain, update or communicate that session state. There is a drawback when the client need to send too much data to the server so it reduces the scope of network optimization and requires more bandwidth."
},
{
"code": null,
"e": 3298,
"s": 2804,
"text": "Cacheable: Every response should include whether the response is cacheable or not and for how much duration responses can be cached at the client side. Client will return the data from its cache for any subsequent request and there would be no need to send the request again to the server. A well-managed caching partially or completely eliminates some client–server interactions, further improving availability and performance. But sometime there are chances that user may receive stale data."
},
{
"code": null,
"e": 3756,
"s": 3298,
"text": "Client-Server: REST application should have a client-server architecture. A Client is someone who is requesting resources and are not concerned with data storage, which remains internal to each server, and server is someone who holds the resources and are not concerned with the user interface or user state. They can evolve independently. Client doesn’t need to know anything about business logic and server doesn’t need to know anything about frontend UI."
},
{
"code": null,
"e": 4118,
"s": 3756,
"text": "Layered system: An application architecture needs to be composed of multiple layers. Each layer doesn’t know any thing about any layer other than that of immediate layer and there can be lot of intermediate servers between client and the end server. Intermediary servers may improve system availability by enabling load-balancing and by providing shared caches."
},
{
"code": null,
"e": 4368,
"s": 4118,
"text": "Code on demand: It is an optional feature. According to this, servers can also provide executable code to the client. The examples of code on demand may include the compiled components such as Java applets and client-side scripts such as JavaScript."
},
{
"code": null,
"e": 4475,
"s": 4368,
"text": "Rules of REST API: There are certain rules which should be kept in mind while creating REST API endpoints."
},
{
"code": null,
"e": 4711,
"s": 4475,
"text": "REST is based on the resource or noun instead of action or verb based. It means that a URI of a REST API should always end with a noun. Example: /api/users is a good example, but /api?type=users is a bad example of creating a REST API."
},
{
"code": null,
"e": 4823,
"s": 4711,
"text": "HTTP verbs are used to identify the action. Some of the HTTP verbs are – GET, PUT, POST, DELETE, UPDATE, PATCH."
},
{
"code": null,
"e": 5375,
"s": 4823,
"text": "A web application should be organized into resources like users and then uses HTTP verbs like – GET, PUT, POST, DELETE to modify those resources. And as a developer it should be clear that what needs to be done just by looking at the endpoint and HTTP method used.URIHTTP verbDescriptionapi/usersGETGet all usersapi/users/newGETShow form for adding new userapi/usersPOSTAdd a userapi/users/1PUTUpdate a user with id = 1api/users/1/editGETShow edit form for user with id = 1api/users/1DELETEDelete a user with id = 1api/users/1GETGet a user with id = 1"
},
{
"code": null,
"e": 5459,
"s": 5375,
"text": "Always use plurals in URL to keep an API URI consistent throughout the application."
},
{
"code": null,
"e": 5522,
"s": 5459,
"text": "Send a proper HTTP code to indicate a success or error status."
},
{
"code": null,
"e": 5680,
"s": 5522,
"text": "Note : You can easily use GET and POST but in order to use PUT and DELETE you will need to install method override. You can do this by following below code :"
},
{
"code": null,
"e": 5715,
"s": 5680,
"text": "npm install method-override --save"
},
{
"code": null,
"e": 5774,
"s": 5715,
"text": "This simply require this package in your code by writing :"
},
{
"code": null,
"e": 5823,
"s": 5774,
"text": "var methodOverride = require(\"method-override\");"
},
{
"code": null,
"e": 5870,
"s": 5823,
"text": "Now you can easily use PUT and DELETE routes :"
},
{
"code": null,
"e": 5906,
"s": 5870,
"text": "app.use(methodOverride(\"_method\"));"
},
{
"code": null,
"e": 5977,
"s": 5906,
"text": "HTTP verbs: Some of the common HTTP methods/verbs are described below:"
},
{
"code": null,
"e": 6086,
"s": 5977,
"text": "GET: Retrieves one or more resources identified by the request URI and it can cache the information receive."
},
{
"code": null,
"e": 6319,
"s": 6086,
"text": "POST: Create a resource from the submission of a request and response is not cacheable in this case. This method is unsafe if no security is applied to the endpoint as it would allow anyone to create a random resource by submission."
},
{
"code": null,
"e": 6396,
"s": 6319,
"text": "PUT: Update an existing resource on the server specified by the request URI."
},
{
"code": null,
"e": 6539,
"s": 6396,
"text": "DELETE: Delete an existing resource on the server specified by the request URI. It always return an appropriate HTTP status for every request."
},
{
"code": null,
"e": 6844,
"s": 6539,
"text": "GET, PUT, DELETE methods are also known as Idempotent methods. Applying an operation once or applying it multiple times has the same effect. Example: Delete any resource from the server and it succeeds with 200 OK and then try again to delete that resource than it will display an error message 410 GONE."
},
{
"code": null,
"e": 6856,
"s": 6844,
"text": "MohdArsalan"
},
{
"code": null,
"e": 6873,
"s": 6856,
"text": "Web Technologies"
},
{
"code": null,
"e": 6971,
"s": 6873,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7004,
"s": 6971,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 7064,
"s": 7004,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 7119,
"s": 7064,
"text": "How do you run JavaScript script through the Terminal?"
},
{
"code": null,
"e": 7155,
"s": 7119,
"text": "Node.js | fs.writeFileSync() Method"
},
{
"code": null,
"e": 7174,
"s": 7155,
"text": "ReactJS setState()"
},
{
"code": null,
"e": 7235,
"s": 7174,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 7274,
"s": 7235,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 7332,
"s": 7274,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 7404,
"s": 7332,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Implement Zoom In or Zoom Out in Android
|
06 Oct, 2021
Zoom In and Zoom Out animations are used to enlarge and reduce the size of a view in Android applications respectively. These types of animations are often used by developers to provide a dynamic nature to the applications. Users also feel the changes happening in the application by watching these kinds of animations.
The characteristics of Zoom In and Zoom Out animations are defined in the XML files by using scale tag.
The following example demonstrates the steps involved in implementing Zoom In and Zoom Out animation to an image file. An image file will be added in the activity using ImageView.
Note: Following steps are performed on Android Studio version 4.0
Step 1: Create new project
Click on File, then New => New Project.Select language as Kotlin.Select the minimum SDK as per your need.
Click on File, then New => New Project.
Select language as Kotlin.
Select the minimum SDK as per your need.
Step 2: Modify activity_main.xml fileBelow is the code for activity_main.xml file to add a TextView, ImageView and two Buttons in an activity.
Filename: activity_main.xml
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#168BC34A" tools:context=".MainActivity" > <TextView android:id="@+id/textView" android:layout_width="0dp" android:layout_height="wrap_content" android:fontFamily="@font/roboto" android:text="@string/heading" android:textAlignment="center" android:textColor="@android:color/holo_green_light" android:textSize="36sp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.060000002" /> <ImageView android:id="@+id/imageView" android:layout_width="179dp" android:layout_height="172dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView" app:layout_constraintVertical_bias="0.31" app:srcCompat="@drawable/logo" /> <Button android:id="@+id/zoomInButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#AB4CAF50" android:fontFamily="@font/roboto" android:padding="5dp" android:text="@string/zoomInButtonText" android:textSize="18sp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toStartOf="@+id/zoomOutButton" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/imageView" app:layout_constraintVertical_bias="0.76" /> <Button android:id="@+id/zoomOutButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#AB4CAF50" android:fontFamily="@font/roboto" android:padding="5dp" android:text="@string/zoomOutButtonText" android:textSize="18sp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.77" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/imageView" app:layout_constraintVertical_bias="0.76" /></androidx.constraintlayout.widget.ConstraintLayout>
Step 3: Define XML file for Zoom In and Zoom Out animation of the imageCreate a new directory in the res folder of the application through right-click on res => New => Android Resource Directory. Select Resource Type as anim and Directory name should also be anim. In this directory create 2 Animation Resource File namely zoom_in and zoom_out. These 2 files are the XML file which holds the details of the animation. Below is the code for both the file.
Filename: zoom_in.xml
XML
<?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android" android:fillAfter = "true"> <scale xmlns:android = "http://schemas.android.com/apk/res/android" android:duration = "1000" android:fromXScal = "1" android:fromYScale = "1" android:pivotX = "50%" android:pivotY = "50%" android:toXScale = "2" android:toYScale = "2"/> </set>
Filename: zoom_out.xm
XML
<?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android" android:fillAfter = "true"> <scale xmlns:android="http://schemas.android.com/apk/res/android" android:duration = "2500" android:fromXScale = "1" android:fromYScale = "1" android:pivotX = "50%" android:pivotY = "50%" android:toXScale = ".2" android:toYScale = ".2" /> </set>
The android:fillAfter attribute under set tag is used to fix the final size of the image file until any other animation happens.
Step 4: Modify MainActivity.kt fileBelow is the code for MainActivity.kt file to load and start the animation on the ImageView widget according to the button clicked by the user.
Filename: MainActivity.kt
Java
package com.example.zomminout import android.os.Bundleimport android.view.animation.AnimationUtilsimport android.widget.Buttonimport android.widget.ImageViewimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // assigning id of the button // which zoom in the image val buttonZoomIn: Button = findViewById(R.id.zoomInButton) // assigning id of the button // which zoom out the image val buttonZoomOut: Button = findViewById(R.id.zoomOutButton) // assigning id of imageview on // which zoom in/out will be performed val image: ImageView = findViewById(R.id.imageView) // actions to be performed when // "Zoom In" button is clicked buttonZoomIn.setOnClickListener() { // loading the animation of // zoom_in.xml file into a variable val animZoomIn = AnimationUtils.loadAnimation(this, R.anim.zoom_in) // assigning that animation to // the image and start animation image.startAnimation(animZoomIn) } // actions to be performed when // "Zoom Out" button is clicked buttonZoomOut.setOnClickListener() { // loading the animation of // zoom_out.xml file into a variable val animZoomOut = AnimationUtils.loadAnimation(this, R.anim.zoom_out) // assigning that animation to // the image and start animation image.startAnimation(animZoomOut) } }}
Step 5: Modify strings.xml fileAll the strings which are used in the activity are listed in this file.
Filename: strings.xml
XML
<resources> <string name="app_name">ZoomInOut</string> <string name="heading">Zoom In/Out in Android</string> <string name="zoomOutButtonText">Zoom Out</string> <string name="zoomInButtonText">Zoom In</string></resources>
gulshankumarar231
Android-Animation
Picked
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Android SDK and it's Components
Android RecyclerView in Kotlin
Broadcast Receiver in Android With Example
Navigation Drawer in Android
How to Create and Add Data to SQLite Database in Android?
Android RecyclerView in Kotlin
Broadcast Receiver in Android With Example
Kotlin Array
How to Add Views Dynamically and Store Data in Arraylist in Android?
Retrofit with Kotlin Coroutine in Android
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 375,
"s": 54,
"text": "Zoom In and Zoom Out animations are used to enlarge and reduce the size of a view in Android applications respectively. These types of animations are often used by developers to provide a dynamic nature to the applications. Users also feel the changes happening in the application by watching these kinds of animations. "
},
{
"code": null,
"e": 480,
"s": 375,
"text": "The characteristics of Zoom In and Zoom Out animations are defined in the XML files by using scale tag. "
},
{
"code": null,
"e": 660,
"s": 480,
"text": "The following example demonstrates the steps involved in implementing Zoom In and Zoom Out animation to an image file. An image file will be added in the activity using ImageView."
},
{
"code": null,
"e": 728,
"s": 660,
"text": "Note: Following steps are performed on Android Studio version 4.0 "
},
{
"code": null,
"e": 756,
"s": 728,
"text": "Step 1: Create new project "
},
{
"code": null,
"e": 862,
"s": 756,
"text": "Click on File, then New => New Project.Select language as Kotlin.Select the minimum SDK as per your need."
},
{
"code": null,
"e": 902,
"s": 862,
"text": "Click on File, then New => New Project."
},
{
"code": null,
"e": 929,
"s": 902,
"text": "Select language as Kotlin."
},
{
"code": null,
"e": 970,
"s": 929,
"text": "Select the minimum SDK as per your need."
},
{
"code": null,
"e": 1113,
"s": 970,
"text": "Step 2: Modify activity_main.xml fileBelow is the code for activity_main.xml file to add a TextView, ImageView and two Buttons in an activity."
},
{
"code": null,
"e": 1141,
"s": 1113,
"text": "Filename: activity_main.xml"
},
{
"code": null,
"e": 1145,
"s": 1141,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"#168BC34A\" tools:context=\".MainActivity\" > <TextView android:id=\"@+id/textView\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:fontFamily=\"@font/roboto\" android:text=\"@string/heading\" android:textAlignment=\"center\" android:textColor=\"@android:color/holo_green_light\" android:textSize=\"36sp\" android:textStyle=\"bold\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"0.060000002\" /> <ImageView android:id=\"@+id/imageView\" android:layout_width=\"179dp\" android:layout_height=\"172dp\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/textView\" app:layout_constraintVertical_bias=\"0.31\" app:srcCompat=\"@drawable/logo\" /> <Button android:id=\"@+id/zoomInButton\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:background=\"#AB4CAF50\" android:fontFamily=\"@font/roboto\" android:padding=\"5dp\" android:text=\"@string/zoomInButtonText\" android:textSize=\"18sp\" android:textStyle=\"bold\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toStartOf=\"@+id/zoomOutButton\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/imageView\" app:layout_constraintVertical_bias=\"0.76\" /> <Button android:id=\"@+id/zoomOutButton\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:background=\"#AB4CAF50\" android:fontFamily=\"@font/roboto\" android:padding=\"5dp\" android:text=\"@string/zoomOutButtonText\" android:textSize=\"18sp\" android:textStyle=\"bold\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.77\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/imageView\" app:layout_constraintVertical_bias=\"0.76\" /></androidx.constraintlayout.widget.ConstraintLayout>",
"e": 3975,
"s": 1145,
"text": null
},
{
"code": null,
"e": 4430,
"s": 3975,
"text": "Step 3: Define XML file for Zoom In and Zoom Out animation of the imageCreate a new directory in the res folder of the application through right-click on res => New => Android Resource Directory. Select Resource Type as anim and Directory name should also be anim. In this directory create 2 Animation Resource File namely zoom_in and zoom_out. These 2 files are the XML file which holds the details of the animation. Below is the code for both the file."
},
{
"code": null,
"e": 4452,
"s": 4430,
"text": "Filename: zoom_in.xml"
},
{
"code": null,
"e": 4456,
"s": 4452,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><set xmlns:android=\"http://schemas.android.com/apk/res/android\" android:fillAfter = \"true\"> <scale xmlns:android = \"http://schemas.android.com/apk/res/android\" android:duration = \"1000\" android:fromXScal = \"1\" android:fromYScale = \"1\" android:pivotX = \"50%\" android:pivotY = \"50%\" android:toXScale = \"2\" android:toYScale = \"2\"/> </set>",
"e": 4893,
"s": 4456,
"text": null
},
{
"code": null,
"e": 4915,
"s": 4893,
"text": "Filename: zoom_out.xm"
},
{
"code": null,
"e": 4919,
"s": 4915,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><set xmlns:android=\"http://schemas.android.com/apk/res/android\" android:fillAfter = \"true\"> <scale xmlns:android=\"http://schemas.android.com/apk/res/android\" android:duration = \"2500\" android:fromXScale = \"1\" android:fromYScale = \"1\" android:pivotX = \"50%\" android:pivotY = \"50%\" android:toXScale = \".2\" android:toYScale = \".2\" /> </set>",
"e": 5358,
"s": 4919,
"text": null
},
{
"code": null,
"e": 5489,
"s": 5358,
"text": "The android:fillAfter attribute under set tag is used to fix the final size of the image file until any other animation happens. "
},
{
"code": null,
"e": 5668,
"s": 5489,
"text": "Step 4: Modify MainActivity.kt fileBelow is the code for MainActivity.kt file to load and start the animation on the ImageView widget according to the button clicked by the user."
},
{
"code": null,
"e": 5694,
"s": 5668,
"text": "Filename: MainActivity.kt"
},
{
"code": null,
"e": 5699,
"s": 5694,
"text": "Java"
},
{
"code": "package com.example.zomminout import android.os.Bundleimport android.view.animation.AnimationUtilsimport android.widget.Buttonimport android.widget.ImageViewimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // assigning id of the button // which zoom in the image val buttonZoomIn: Button = findViewById(R.id.zoomInButton) // assigning id of the button // which zoom out the image val buttonZoomOut: Button = findViewById(R.id.zoomOutButton) // assigning id of imageview on // which zoom in/out will be performed val image: ImageView = findViewById(R.id.imageView) // actions to be performed when // \"Zoom In\" button is clicked buttonZoomIn.setOnClickListener() { // loading the animation of // zoom_in.xml file into a variable val animZoomIn = AnimationUtils.loadAnimation(this, R.anim.zoom_in) // assigning that animation to // the image and start animation image.startAnimation(animZoomIn) } // actions to be performed when // \"Zoom Out\" button is clicked buttonZoomOut.setOnClickListener() { // loading the animation of // zoom_out.xml file into a variable val animZoomOut = AnimationUtils.loadAnimation(this, R.anim.zoom_out) // assigning that animation to // the image and start animation image.startAnimation(animZoomOut) } }}",
"e": 7488,
"s": 5699,
"text": null
},
{
"code": null,
"e": 7591,
"s": 7488,
"text": "Step 5: Modify strings.xml fileAll the strings which are used in the activity are listed in this file."
},
{
"code": null,
"e": 7613,
"s": 7591,
"text": "Filename: strings.xml"
},
{
"code": null,
"e": 7617,
"s": 7613,
"text": "XML"
},
{
"code": "<resources> <string name=\"app_name\">ZoomInOut</string> <string name=\"heading\">Zoom In/Out in Android</string> <string name=\"zoomOutButtonText\">Zoom Out</string> <string name=\"zoomInButtonText\">Zoom In</string></resources>",
"e": 7851,
"s": 7617,
"text": null
},
{
"code": null,
"e": 7869,
"s": 7851,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 7887,
"s": 7869,
"text": "Android-Animation"
},
{
"code": null,
"e": 7894,
"s": 7887,
"text": "Picked"
},
{
"code": null,
"e": 7902,
"s": 7894,
"text": "Android"
},
{
"code": null,
"e": 7909,
"s": 7902,
"text": "Kotlin"
},
{
"code": null,
"e": 7917,
"s": 7909,
"text": "Android"
},
{
"code": null,
"e": 8015,
"s": 7917,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8047,
"s": 8015,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 8078,
"s": 8047,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 8121,
"s": 8078,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 8150,
"s": 8121,
"text": "Navigation Drawer in Android"
},
{
"code": null,
"e": 8208,
"s": 8150,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 8239,
"s": 8208,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 8282,
"s": 8239,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 8295,
"s": 8282,
"text": "Kotlin Array"
},
{
"code": null,
"e": 8364,
"s": 8295,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
}
] |
if-else Statement in JavaScript
|
24 Nov, 2021
In this article, we will learn about the conditional statement (ie, if-else statement) in Javascript, along with understanding its implementation through the examples. The conditional statement will perform some action for the specific condition. If the condition meet then the particular block of action will be executed otherwise it will execute another block of action that satisfies that particular condition.
Decision Making in programming is similar to decision-making in real life. In programming also, we face some situations where we want a certain block of code to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program.
JavaScript’s conditional statements:
if
if-else
nested-if
if-else-if ladder
We will understand each conditional statements, its syntax, flowchart & examples. Please refer to the Switch Case in JavaScript article to understand the switch case. Let’s begin with if-statement.
if-statement: if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.
Syntax:
if(condition)
{
// Statements to execute if
// condition is true
}
Here, the condition after evaluation will be either true or false. if statement accepts boolean values – if the value is true then it will execute the block of statements under it. If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if statement will consider the immediate one statement to be inside its block. For example,
if(condition)
statement1;
statement2;
// Here if the condition is true, if block
// will consider only statement1 to be inside
// its block.
Flow chart:
if-condition statement
Example: This example describes the if-statement in Javascript.
Javascript
<script type = "text/javaScript"> // JavaScript program to illustrate If statementvar i = 10; if (i > 15) document.write("10 is less than 15"); // This statement will be executed// as if considers one statement by defaultdocument.write("I am Not in if");</script>
Output:
I am Not in if
if-else statement: The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the else statement. We can use the else statement with the if statement to execute a block of code when the condition is false.
Syntax:
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Flow chart:
if-else statement
Example: This example describes the if-else statement in Javascript.
JavaScript
<script type = "text/javaScript"> // JavaScript program to illustrate If-else statementvar i = 10; if (i < 15) document.write("10 is less than 15");else document.write("I am Not in if");</script>
Output:
i is smaller than 15
nested-if statement: A nested if is an if statement that is the target of another if or else. Nested if statements mean if statement inside another if statement. Yes, JavaScript allows us to nest if statements within if statements. i.e, we can place an if statement inside another if statement.
Syntax:
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
Flow chart:
nested-if statement
Example: This example describes the nested-if statement in Javascript.
JavaScript
<script type = "text/javaScript"> // JavaScript program to illustrate nested-if statementvar i = 10; if (i == 10) { // First if statement if (i < 15) document.write("i is smaller than 15"); // Nested - if statement // Will only be executed if statement above // it is true if (i < 12) document.write("i is smaller than 12 too"); else document.write("i is greater than 15");}</script>
Output:
i is smaller than 15
i is smaller than 12 too
if-else-if ladder statement: Here, a user can decide among multiple options.The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
Syntax:
if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;
Flow chart:
if-else-if ladder statement
Example: This example describes the if-else-if ladder statement in Javascript.
JavaScript
<script type = "text/javaScript"> // JavaScript program to illustrate nested-if statementvar i = 20; if (i == 10) document.write("i is 10");else if (i == 15) document.write("i is 15");else if (i == 20) document.write("i is 20");else document.write("i is not present");</script>
Output:
i is 20
Supported Browsers:
Google Chrome 1.0
Firefox 1.0
Microsoft Edge 12.0
Internet Explorer 3.0
Opera 3.0
Safari 1.0
samhitha
keerthiga ragu
bhaskargeeksforgeeks
gulshankumarar231
javascript-basics
JavaScript
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
Roadmap to Learn JavaScript For Beginners
Hide or show elements in HTML using display property
Difference Between PUT and PATCH Request
How to append HTML code to a div using JavaScript ?
File uploading in React.js
How to calculate the number of days between two dates in javascript?
How to Open URL in New Tab using JavaScript ?
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 467,
"s": 53,
"text": "In this article, we will learn about the conditional statement (ie, if-else statement) in Javascript, along with understanding its implementation through the examples. The conditional statement will perform some action for the specific condition. If the condition meet then the particular block of action will be executed otherwise it will execute another block of action that satisfies that particular condition."
},
{
"code": null,
"e": 910,
"s": 467,
"text": "Decision Making in programming is similar to decision-making in real life. In programming also, we face some situations where we want a certain block of code to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program."
},
{
"code": null,
"e": 947,
"s": 910,
"text": "JavaScript’s conditional statements:"
},
{
"code": null,
"e": 950,
"s": 947,
"text": "if"
},
{
"code": null,
"e": 958,
"s": 950,
"text": "if-else"
},
{
"code": null,
"e": 968,
"s": 958,
"text": "nested-if"
},
{
"code": null,
"e": 986,
"s": 968,
"text": "if-else-if ladder"
},
{
"code": null,
"e": 1185,
"s": 986,
"text": " We will understand each conditional statements, its syntax, flowchart & examples. Please refer to the Switch Case in JavaScript article to understand the switch case. Let’s begin with if-statement."
},
{
"code": null,
"e": 1442,
"s": 1185,
"text": "if-statement: if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not."
},
{
"code": null,
"e": 1450,
"s": 1442,
"text": "Syntax:"
},
{
"code": null,
"e": 1524,
"s": 1450,
"text": "if(condition) \n{\n // Statements to execute if\n // condition is true\n}"
},
{
"code": null,
"e": 1885,
"s": 1524,
"text": "Here, the condition after evaluation will be either true or false. if statement accepts boolean values – if the value is true then it will execute the block of statements under it. If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if statement will consider the immediate one statement to be inside its block. For example,"
},
{
"code": null,
"e": 2035,
"s": 1885,
"text": "if(condition)\n statement1;\n statement2;\n\n// Here if the condition is true, if block \n// will consider only statement1 to be inside \n// its block."
},
{
"code": null,
"e": 2047,
"s": 2035,
"text": "Flow chart:"
},
{
"code": null,
"e": 2070,
"s": 2047,
"text": "if-condition statement"
},
{
"code": null,
"e": 2134,
"s": 2070,
"text": "Example: This example describes the if-statement in Javascript."
},
{
"code": null,
"e": 2145,
"s": 2134,
"text": "Javascript"
},
{
"code": "<script type = \"text/javaScript\"> // JavaScript program to illustrate If statementvar i = 10; if (i > 15) document.write(\"10 is less than 15\"); // This statement will be executed// as if considers one statement by defaultdocument.write(\"I am Not in if\");</script>",
"e": 2409,
"s": 2145,
"text": null
},
{
"code": null,
"e": 2417,
"s": 2409,
"text": "Output:"
},
{
"code": null,
"e": 2432,
"s": 2417,
"text": "I am Not in if"
},
{
"code": null,
"e": 2796,
"s": 2432,
"text": "if-else statement: The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the else statement. We can use the else statement with the if statement to execute a block of code when the condition is false."
},
{
"code": null,
"e": 2804,
"s": 2796,
"text": "Syntax:"
},
{
"code": null,
"e": 2943,
"s": 2804,
"text": "if (condition)\n{\n // Executes this block if\n // condition is true\n}\nelse\n{\n // Executes this block if\n // condition is false\n}"
},
{
"code": null,
"e": 2955,
"s": 2943,
"text": "Flow chart:"
},
{
"code": null,
"e": 2973,
"s": 2955,
"text": "if-else statement"
},
{
"code": null,
"e": 3042,
"s": 2973,
"text": "Example: This example describes the if-else statement in Javascript."
},
{
"code": null,
"e": 3053,
"s": 3042,
"text": "JavaScript"
},
{
"code": "<script type = \"text/javaScript\"> // JavaScript program to illustrate If-else statementvar i = 10; if (i < 15) document.write(\"10 is less than 15\");else document.write(\"I am Not in if\");</script>",
"e": 3251,
"s": 3053,
"text": null
},
{
"code": null,
"e": 3259,
"s": 3251,
"text": "Output:"
},
{
"code": null,
"e": 3280,
"s": 3259,
"text": "i is smaller than 15"
},
{
"code": null,
"e": 3575,
"s": 3280,
"text": "nested-if statement: A nested if is an if statement that is the target of another if or else. Nested if statements mean if statement inside another if statement. Yes, JavaScript allows us to nest if statements within if statements. i.e, we can place an if statement inside another if statement."
},
{
"code": null,
"e": 3583,
"s": 3575,
"text": "Syntax:"
},
{
"code": null,
"e": 3715,
"s": 3583,
"text": "if (condition1) \n{\n // Executes when condition1 is true\n if (condition2) \n {\n // Executes when condition2 is true\n }\n}"
},
{
"code": null,
"e": 3727,
"s": 3715,
"text": "Flow chart:"
},
{
"code": null,
"e": 3747,
"s": 3727,
"text": "nested-if statement"
},
{
"code": null,
"e": 3818,
"s": 3747,
"text": "Example: This example describes the nested-if statement in Javascript."
},
{
"code": null,
"e": 3829,
"s": 3818,
"text": "JavaScript"
},
{
"code": "<script type = \"text/javaScript\"> // JavaScript program to illustrate nested-if statementvar i = 10; if (i == 10) { // First if statement if (i < 15) document.write(\"i is smaller than 15\"); // Nested - if statement // Will only be executed if statement above // it is true if (i < 12) document.write(\"i is smaller than 12 too\"); else document.write(\"i is greater than 15\");}</script>",
"e": 4231,
"s": 3829,
"text": null
},
{
"code": null,
"e": 4239,
"s": 4231,
"text": "Output:"
},
{
"code": null,
"e": 4285,
"s": 4239,
"text": "i is smaller than 15\ni is smaller than 12 too"
},
{
"code": null,
"e": 4646,
"s": 4285,
"text": "if-else-if ladder statement: Here, a user can decide among multiple options.The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed."
},
{
"code": null,
"e": 4654,
"s": 4646,
"text": "Syntax:"
},
{
"code": null,
"e": 4743,
"s": 4654,
"text": "if (condition)\n statement;\nelse if (condition)\n statement;\n.\n.\nelse\n statement;"
},
{
"code": null,
"e": 4755,
"s": 4743,
"text": "Flow chart:"
},
{
"code": null,
"e": 4783,
"s": 4755,
"text": "if-else-if ladder statement"
},
{
"code": null,
"e": 4862,
"s": 4783,
"text": "Example: This example describes the if-else-if ladder statement in Javascript."
},
{
"code": null,
"e": 4873,
"s": 4862,
"text": "JavaScript"
},
{
"code": "<script type = \"text/javaScript\"> // JavaScript program to illustrate nested-if statementvar i = 20; if (i == 10) document.write(\"i is 10\");else if (i == 15) document.write(\"i is 15\");else if (i == 20) document.write(\"i is 20\");else document.write(\"i is not present\");</script>",
"e": 5155,
"s": 4873,
"text": null
},
{
"code": null,
"e": 5163,
"s": 5155,
"text": "Output:"
},
{
"code": null,
"e": 5171,
"s": 5163,
"text": "i is 20"
},
{
"code": null,
"e": 5191,
"s": 5171,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 5209,
"s": 5191,
"text": "Google Chrome 1.0"
},
{
"code": null,
"e": 5221,
"s": 5209,
"text": "Firefox 1.0"
},
{
"code": null,
"e": 5241,
"s": 5221,
"text": "Microsoft Edge 12.0"
},
{
"code": null,
"e": 5263,
"s": 5241,
"text": "Internet Explorer 3.0"
},
{
"code": null,
"e": 5273,
"s": 5263,
"text": "Opera 3.0"
},
{
"code": null,
"e": 5284,
"s": 5273,
"text": "Safari 1.0"
},
{
"code": null,
"e": 5293,
"s": 5284,
"text": "samhitha"
},
{
"code": null,
"e": 5308,
"s": 5293,
"text": "keerthiga ragu"
},
{
"code": null,
"e": 5329,
"s": 5308,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 5347,
"s": 5329,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 5365,
"s": 5347,
"text": "javascript-basics"
},
{
"code": null,
"e": 5376,
"s": 5365,
"text": "JavaScript"
},
{
"code": null,
"e": 5474,
"s": 5376,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5535,
"s": 5474,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5607,
"s": 5535,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 5647,
"s": 5607,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 5689,
"s": 5647,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 5742,
"s": 5689,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 5783,
"s": 5742,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 5835,
"s": 5783,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 5862,
"s": 5835,
"text": "File uploading in React.js"
},
{
"code": null,
"e": 5931,
"s": 5862,
"text": "How to calculate the number of days between two dates in javascript?"
}
] |
semop() - Unix, Linux System Call
|
Unix - Home
Unix - Getting Started
Unix - File Management
Unix - Directories
Unix - File Permission
Unix - Environment
Unix - Basic Utilities
Unix - Pipes & Filters
Unix - Processes
Unix - Communication
Unix - The vi Editor
Unix - What is Shell?
Unix - Using Variables
Unix - Special Variables
Unix - Using Arrays
Unix - Basic Operators
Unix - Decision Making
Unix - Shell Loops
Unix - Loop Control
Unix - Shell Substitutions
Unix - Quoting Mechanisms
Unix - IO Redirections
Unix - Shell Functions
Unix - Manpage Help
Unix - Regular Expressions
Unix - File System Basics
Unix - User Administration
Unix - System Performance
Unix - System Logging
Unix - Signals and Traps
Unix - Useful Commands
Unix - Quick Guide
Unix - Builtin Functions
Unix - System Calls
Unix - Commands List
Unix Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
int semop(int semid, struct sembuf *sops, unsigned nsops);
int semtimedop(int semid, struct sembuf *sops, unsigned nsops, struct timespec *timeout);
unsigned short semval; /* semaphore value */
unsigned short semzcnt; /* # waiting for zero */
unsigned short semncnt; /* # waiting for increase */
pid_t sempid; /* process that did last op */
unsigned short sem_num; /* semaphore number */
short sem_op; /* semaphore operation */
short sem_flg; /* operation flags */
The set of operations contained in
sops is performed
atomically, that is, the operations are performed at the same time, and only
if they can all be simultaneously performed.
The behaviour of the system call if not all operations can be
performed immediately depends on the presence of the
IPC_NOWAIT flag in the individual
sem_flg fields, as noted below.
Each operation is performed on the
sem_num-th semaphore of the semaphore set, where the first semaphore of the set
is numbered 0.
There are three types of operation, distinguished by the value of
sem_op.
If
sem_op is a positive integer, the operation adds this value to
the semaphore value
(semval). Furthermore, if
SEM_UNDO is specified for this operation, the system updates the process undo count
(semadj) for this semaphore.
This operation can always proceed — it never forces a process to wait.
The calling process must have alter permission on the semaphore set.
If
sem_op is zero, the process must have read permission on the semaphore
set.
This is a "wait-for-zero" operation: if
semval is zero, the operation can immediately proceed.
Otherwise, if
IPC_NOWAIT is specified in
sem_flg, semop() fails with
errno set to
EAGAIN (and none of the operations in
sops is performed).
Otherwise
semzcnt (the count of processes waiting until this semaphore’s value becomes zero)
is incremented by one and the process sleeps until
one of the following occurs:
semtimedop() behaves identically to
semop() except that in those cases were the calling process would sleep,
the duration of that sleep is limited by the amount of elapsed
time specified by the
timespec structure whose address is passed in the
timeout parameter. If the specified time limit has been reached,
semtimedop() fails with
errno set to
EAGAIN (and none of the operations in
sops is performed).
If the
timeout parameter is NULL,
then
semtimedop() behaves exactly like
semop().
semop() is never automatically restarted after being interrupted by a signal handler,
regardless of the setting of the
SA_RESTART flag when establishing a signal handler.
semadj is a per-process integer which is simply the (negative) count
of all semaphore operations performed specifying the
SEM_UNDO flag.
When a semaphore’s value is directly set using the
SETVAL or
SETALL request to
semctl(2),
the corresponding
semadj values in all processes are cleared.
The semval, sempid, semzcnt, and semnct values
for a semaphore can all be retrieved using appropriate
semctl(2)
calls.
The following limits on semaphore set resources affect the
semop() call:
semtimedop() first appeared in Linux 2.5.52,
and was subsequently backported into kernel 2.4.22.
In kernels 2.6.x, x <= 10, there is a bug that in some circumstances
prevents a process that is waiting for a semaphore value to become
zero from being woken up when the value does actually become zero.
This bug is fixed in kernel 2.6.11.
|
[
{
"code": null,
"e": 1600,
"s": 1588,
"text": "Unix - Home"
},
{
"code": null,
"e": 1623,
"s": 1600,
"text": "Unix - Getting Started"
},
{
"code": null,
"e": 1646,
"s": 1623,
"text": "Unix - File Management"
},
{
"code": null,
"e": 1665,
"s": 1646,
"text": "Unix - Directories"
},
{
"code": null,
"e": 1688,
"s": 1665,
"text": "Unix - File Permission"
},
{
"code": null,
"e": 1707,
"s": 1688,
"text": "Unix - Environment"
},
{
"code": null,
"e": 1730,
"s": 1707,
"text": "Unix - Basic Utilities"
},
{
"code": null,
"e": 1753,
"s": 1730,
"text": "Unix - Pipes & Filters"
},
{
"code": null,
"e": 1770,
"s": 1753,
"text": "Unix - Processes"
},
{
"code": null,
"e": 1791,
"s": 1770,
"text": "Unix - Communication"
},
{
"code": null,
"e": 1812,
"s": 1791,
"text": "Unix - The vi Editor"
},
{
"code": null,
"e": 1834,
"s": 1812,
"text": "Unix - What is Shell?"
},
{
"code": null,
"e": 1857,
"s": 1834,
"text": "Unix - Using Variables"
},
{
"code": null,
"e": 1882,
"s": 1857,
"text": "Unix - Special Variables"
},
{
"code": null,
"e": 1902,
"s": 1882,
"text": "Unix - Using Arrays"
},
{
"code": null,
"e": 1925,
"s": 1902,
"text": "Unix - Basic Operators"
},
{
"code": null,
"e": 1948,
"s": 1925,
"text": "Unix - Decision Making"
},
{
"code": null,
"e": 1967,
"s": 1948,
"text": "Unix - Shell Loops"
},
{
"code": null,
"e": 1987,
"s": 1967,
"text": "Unix - Loop Control"
},
{
"code": null,
"e": 2014,
"s": 1987,
"text": "Unix - Shell Substitutions"
},
{
"code": null,
"e": 2040,
"s": 2014,
"text": "Unix - Quoting Mechanisms"
},
{
"code": null,
"e": 2063,
"s": 2040,
"text": "Unix - IO Redirections"
},
{
"code": null,
"e": 2086,
"s": 2063,
"text": "Unix - Shell Functions"
},
{
"code": null,
"e": 2106,
"s": 2086,
"text": "Unix - Manpage Help"
},
{
"code": null,
"e": 2133,
"s": 2106,
"text": "Unix - Regular Expressions"
},
{
"code": null,
"e": 2159,
"s": 2133,
"text": "Unix - File System Basics"
},
{
"code": null,
"e": 2186,
"s": 2159,
"text": "Unix - User Administration"
},
{
"code": null,
"e": 2212,
"s": 2186,
"text": "Unix - System Performance"
},
{
"code": null,
"e": 2234,
"s": 2212,
"text": "Unix - System Logging"
},
{
"code": null,
"e": 2259,
"s": 2234,
"text": "Unix - Signals and Traps"
},
{
"code": null,
"e": 2282,
"s": 2259,
"text": "Unix - Useful Commands"
},
{
"code": null,
"e": 2301,
"s": 2282,
"text": "Unix - Quick Guide"
},
{
"code": null,
"e": 2326,
"s": 2301,
"text": "Unix - Builtin Functions"
},
{
"code": null,
"e": 2346,
"s": 2326,
"text": "Unix - System Calls"
},
{
"code": null,
"e": 2367,
"s": 2346,
"text": "Unix - Commands List"
},
{
"code": null,
"e": 2389,
"s": 2367,
"text": "Unix Useful Resources"
},
{
"code": null,
"e": 2407,
"s": 2389,
"text": "Computer Glossary"
},
{
"code": null,
"e": 2418,
"s": 2407,
"text": "Who is Who"
},
{
"code": null,
"e": 2453,
"s": 2418,
"text": "Copyright © 2014 by tutorialspoint"
},
{
"code": null,
"e": 2525,
"s": 2453,
"text": " \n#include <sys/types.h>\n \n#include <sys/ipc.h>\n \n#include <sys/sem.h>\n"
},
{
"code": null,
"e": 2586,
"s": 2525,
"text": "\nint semop(int semid, struct sembuf *sops, unsigned nsops); "
},
{
"code": null,
"e": 2678,
"s": 2586,
"text": "\nint semtimedop(int semid, struct sembuf *sops, unsigned nsops, struct timespec *timeout); "
},
{
"code": null,
"e": 2895,
"s": 2681,
"text": "unsigned short semval; /* semaphore value */\nunsigned short semzcnt; /* # waiting for zero */\nunsigned short semncnt; /* # waiting for increase */\npid_t sempid; /* process that did last op */\n\n\n"
},
{
"code": null,
"e": 3050,
"s": 2901,
"text": "unsigned short sem_num; /* semaphore number */\nshort sem_op; /* semaphore operation */\nshort sem_flg; /* operation flags */\n\n\n"
},
{
"code": null,
"e": 3411,
"s": 3053,
"text": "\nThe set of operations contained in\nsops is performed\natomically, that is, the operations are performed at the same time, and only\nif they can all be simultaneously performed.\nThe behaviour of the system call if not all operations can be\nperformed immediately depends on the presence of the\nIPC_NOWAIT flag in the individual\nsem_flg fields, as noted below.\n"
},
{
"code": null,
"e": 3617,
"s": 3411,
"text": "\nEach operation is performed on the\nsem_num-th semaphore of the semaphore set, where the first semaphore of the set\nis numbered 0.\nThere are three types of operation, distinguished by the value of\nsem_op. "
},
{
"code": null,
"e": 3984,
"s": 3617,
"text": "\nIf\nsem_op is a positive integer, the operation adds this value to\nthe semaphore value\n(semval). Furthermore, if\nSEM_UNDO is specified for this operation, the system updates the process undo count\n(semadj) for this semaphore.\nThis operation can always proceed — it never forces a process to wait.\nThe calling process must have alter permission on the semaphore set.\n"
},
{
"code": null,
"e": 4473,
"s": 3984,
"text": "\nIf\nsem_op is zero, the process must have read permission on the semaphore\nset.\nThis is a \"wait-for-zero\" operation: if\nsemval is zero, the operation can immediately proceed.\nOtherwise, if\nIPC_NOWAIT is specified in\nsem_flg, semop() fails with\nerrno set to\nEAGAIN (and none of the operations in\nsops is performed).\nOtherwise\nsemzcnt (the count of processes waiting until this semaphore’s value becomes zero)\nis incremented by one and the process sleeps until\none of the following occurs:\n"
},
{
"code": null,
"e": 4962,
"s": 4473,
"text": "\nsemtimedop() behaves identically to\nsemop() except that in those cases were the calling process would sleep,\nthe duration of that sleep is limited by the amount of elapsed\ntime specified by the\ntimespec structure whose address is passed in the\ntimeout parameter. If the specified time limit has been reached,\nsemtimedop() fails with\nerrno set to\nEAGAIN (and none of the operations in\nsops is performed).\nIf the\ntimeout parameter is NULL,\nthen\nsemtimedop() behaves exactly like\nsemop(). "
},
{
"code": null,
"e": 5135,
"s": 4962,
"text": "\nsemop() is never automatically restarted after being interrupted by a signal handler,\nregardless of the setting of the\nSA_RESTART flag when establishing a signal handler.\n"
},
{
"code": null,
"e": 5426,
"s": 5135,
"text": "\nsemadj is a per-process integer which is simply the (negative) count\nof all semaphore operations performed specifying the\nSEM_UNDO flag.\nWhen a semaphore’s value is directly set using the\nSETVAL or\nSETALL request to\nsemctl(2),\nthe corresponding\nsemadj values in all processes are cleared.\n"
},
{
"code": null,
"e": 5547,
"s": 5426,
"text": "\nThe semval, sempid, semzcnt, and semnct values\nfor a semaphore can all be retrieved using appropriate\nsemctl(2)\ncalls.\n"
},
{
"code": null,
"e": 5622,
"s": 5547,
"text": "\nThe following limits on semaphore set resources affect the\nsemop() call:\n"
},
{
"code": null,
"e": 5721,
"s": 5622,
"text": "\nsemtimedop() first appeared in Linux 2.5.52,\nand was subsequently backported into kernel 2.4.22.\n"
}
] |
Python | Calculate Distance between two places using Geopy
|
19 Jul, 2019
GeoPy is a Python library that makes geographical calculations easier for the users. In this article, we will see how to calculate the distance between 2 points on the earth in two ways.
How to Install GeoPy ?
pip install geopy
Geodesic Distance:It is the length of the shortest path between 2 points on any surface. In our case, the surface is the earth. Below program illustrates how to calculate geodesic distance from latitude-longitude data.
# Importing the geodesic module from the libraryfrom geopy.distance import geodesic # Loading the lat-long data for Kolkata & Delhikolkata = (22.5726, 88.3639)delhi = (28.7041, 77.1025) # Print the distance calculated in kmprint(geodesic(kolkata, delhi).km)
Output:
1318.13891581683
Great Circle Distance:It is the length of the shortest path between 2 points on a sphere. In this case, the earth is assumed to be a perfect sphere. Below program illustrates how to calculate great-circle distance from latitude-longitude data.
# Importing the great_circle module from the libraryfrom geopy.distance import great_circle # Loading the lat-long data for Kolkata & Delhikolkata = (22.5726, 88.3639)delhi = (28.7041, 77.1025) # Print the distance calculated in kmprint(great_circle(kolkata, delhi).km)
Output:
1317.7554645657162
Reference: https://geopy.readthedocs.io/en/stable/
python-modules
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Jul, 2019"
},
{
"code": null,
"e": 215,
"s": 28,
"text": "GeoPy is a Python library that makes geographical calculations easier for the users. In this article, we will see how to calculate the distance between 2 points on the earth in two ways."
},
{
"code": null,
"e": 238,
"s": 215,
"text": "How to Install GeoPy ?"
},
{
"code": null,
"e": 256,
"s": 238,
"text": "pip install geopy"
},
{
"code": null,
"e": 476,
"s": 256,
"text": " Geodesic Distance:It is the length of the shortest path between 2 points on any surface. In our case, the surface is the earth. Below program illustrates how to calculate geodesic distance from latitude-longitude data."
},
{
"code": "# Importing the geodesic module from the libraryfrom geopy.distance import geodesic # Loading the lat-long data for Kolkata & Delhikolkata = (22.5726, 88.3639)delhi = (28.7041, 77.1025) # Print the distance calculated in kmprint(geodesic(kolkata, delhi).km)",
"e": 736,
"s": 476,
"text": null
},
{
"code": null,
"e": 744,
"s": 736,
"text": "Output:"
},
{
"code": null,
"e": 761,
"s": 744,
"text": "1318.13891581683"
},
{
"code": null,
"e": 1006,
"s": 761,
"text": " Great Circle Distance:It is the length of the shortest path between 2 points on a sphere. In this case, the earth is assumed to be a perfect sphere. Below program illustrates how to calculate great-circle distance from latitude-longitude data."
},
{
"code": "# Importing the great_circle module from the libraryfrom geopy.distance import great_circle # Loading the lat-long data for Kolkata & Delhikolkata = (22.5726, 88.3639)delhi = (28.7041, 77.1025) # Print the distance calculated in kmprint(great_circle(kolkata, delhi).km)",
"e": 1278,
"s": 1006,
"text": null
},
{
"code": null,
"e": 1286,
"s": 1278,
"text": "Output:"
},
{
"code": null,
"e": 1305,
"s": 1286,
"text": "1317.7554645657162"
},
{
"code": null,
"e": 1356,
"s": 1305,
"text": "Reference: https://geopy.readthedocs.io/en/stable/"
},
{
"code": null,
"e": 1371,
"s": 1356,
"text": "python-modules"
},
{
"code": null,
"e": 1386,
"s": 1371,
"text": "python-utility"
},
{
"code": null,
"e": 1393,
"s": 1386,
"text": "Python"
}
] |
Writing code faster during Competitive Programming in C++
|
11 May, 2022
This article focuses on how to implement your solutions and implement them fast while doing competitive programming.
Setup Please refer Setting up a C++ Competitive Programming Environment
Snippets Snippet is a programming term for a small region of re-usable source Code. A lot of modern text editors like Sublime provide you a functionality to automatically write a predefined snippet by just writing a keyword. One can speed up their implementation by using Snippets. So if you need to do a BFS or DFS(or any other code), you just need to press ‘Keyword+Tab’ to get it’s code.
How to add a snippet Adding a snippet in Sublime Text is pretty straightforward. Just navigate to Tools>Developers>New Snippet.
<snippet><content><![CDATA[
// Type your code here
]]></content><tabTrigger>ENTER KEYWORD HERE</tabTrigger></snippet>
Use this as your base template for a snippet and paste the code that you want to use in your Snippet by replacing the comment and trigger Keyword.
MacrosThey are a way to assign shorter notations to things that are usually longer to write.They can be easily written using #define.
Example 1:Before using Macros:
long long int a;vector<long long int> v;map<long long int, long long int> mp;
After using Macros:
// ll can be used instead of typing long long int#define ll long long int ll a;vector<ll> v;map<ll, ll> mp;
Example 2:Before using Macros:
for (int i = 0; i < N; i++) cin >> a[i]; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { cout << m[i][j] << endl; }}
After using Macros:
// Use this macro instead of typing the whole// for-loop syntax#define FOR(a, c) for (int(a) = 0; (a) < (c); (a)++) FOR(i, N)cin >> a[i]; FOR(i, N){ FOR(j, M) { cout << m[i][j] << endl; }}
Example 3:
vector v; for (int i = 0; i < N; i++) { cin >> x >> y; v.push_back(make_pair(x, y));}
After:
#define ll long long int#define MP make_pair#define pb push_back vector<ll, ll> v; for (int i = 0; i < N; i++) { cin >> x >> y; v.pb(MP(x, y));}
Note: Write your macros at the beginning of your code(refer to the template given below).
Using a TemplateUsing a template is one of the best idea to speed up your implementation. Keep your template ready that has your macros written in them already. This helps in reducing a lot of your time which otherwise would have gone in writing the whole code from scratch.I use the following template, you can use one that suits you.
#include "bits/stdc++.h"using namespace std;#define max(a, b) (a < b ? b : a)#define min(a, b) ((a > b) ? b : a)#define mod 1e9 + 7#define FOR(a, c) for (int(a) = 0; (a) < (c); (a)++)#define FORL(a, b, c) for (int(a) = (b); (a) <= (c); (a)++)#define FORR(a, b, c) for (int(a) = (b); (a) >= (c); (a)--)#define INF 1000000000000000003typedef long long int ll;typedef vector<int> vi;typedef pair<int, int> pi;#define F first#define S second#define PB push_back#define POB pop_back#define MP make_pairint main(){ ios::sync_with_stdio(0); cin.tie(0); int T; cin >> T; while (T--) { int N; cin >> N; ll a[N]; FOR(i, N) cin >> a[i]; } return 0;}
Thank you for reading, please let me know if you have some possible improvement or addition.
CPP-Competitive-Programming
C++
Competitive Programming
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
std::string class in C++
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Modulo 10^9+7 (1000000007)
Prefix Sum Array - Implementation and Applications in Competitive Programming
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 May, 2022"
},
{
"code": null,
"e": 169,
"s": 52,
"text": "This article focuses on how to implement your solutions and implement them fast while doing competitive programming."
},
{
"code": null,
"e": 241,
"s": 169,
"text": "Setup Please refer Setting up a C++ Competitive Programming Environment"
},
{
"code": null,
"e": 632,
"s": 241,
"text": "Snippets Snippet is a programming term for a small region of re-usable source Code. A lot of modern text editors like Sublime provide you a functionality to automatically write a predefined snippet by just writing a keyword. One can speed up their implementation by using Snippets. So if you need to do a BFS or DFS(or any other code), you just need to press ‘Keyword+Tab’ to get it’s code."
},
{
"code": null,
"e": 760,
"s": 632,
"text": "How to add a snippet Adding a snippet in Sublime Text is pretty straightforward. Just navigate to Tools>Developers>New Snippet."
},
{
"code": null,
"e": 788,
"s": 760,
"text": "<snippet><content><![CDATA["
},
{
"code": null,
"e": 811,
"s": 788,
"text": "// Type your code here"
},
{
"code": null,
"e": 878,
"s": 811,
"text": "]]></content><tabTrigger>ENTER KEYWORD HERE</tabTrigger></snippet>"
},
{
"code": null,
"e": 1025,
"s": 878,
"text": "Use this as your base template for a snippet and paste the code that you want to use in your Snippet by replacing the comment and trigger Keyword."
},
{
"code": null,
"e": 1159,
"s": 1025,
"text": "MacrosThey are a way to assign shorter notations to things that are usually longer to write.They can be easily written using #define."
},
{
"code": null,
"e": 1190,
"s": 1159,
"text": "Example 1:Before using Macros:"
},
{
"code": "long long int a;vector<long long int> v;map<long long int, long long int> mp;",
"e": 1268,
"s": 1190,
"text": null
},
{
"code": null,
"e": 1288,
"s": 1268,
"text": "After using Macros:"
},
{
"code": "// ll can be used instead of typing long long int#define ll long long int ll a;vector<ll> v;map<ll, ll> mp;",
"e": 1397,
"s": 1288,
"text": null
},
{
"code": null,
"e": 1428,
"s": 1397,
"text": "Example 2:Before using Macros:"
},
{
"code": "for (int i = 0; i < N; i++) cin >> a[i]; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { cout << m[i][j] << endl; }}",
"e": 1574,
"s": 1428,
"text": null
},
{
"code": null,
"e": 1594,
"s": 1574,
"text": "After using Macros:"
},
{
"code": "// Use this macro instead of typing the whole// for-loop syntax#define FOR(a, c) for (int(a) = 0; (a) < (c); (a)++) FOR(i, N)cin >> a[i]; FOR(i, N){ FOR(j, M) { cout << m[i][j] << endl; }}",
"e": 1801,
"s": 1594,
"text": null
},
{
"code": null,
"e": 1812,
"s": 1801,
"text": "Example 3:"
},
{
"code": "vector v; for (int i = 0; i < N; i++) { cin >> x >> y; v.push_back(make_pair(x, y));}",
"e": 1905,
"s": 1812,
"text": null
},
{
"code": null,
"e": 1912,
"s": 1905,
"text": "After:"
},
{
"code": "#define ll long long int#define MP make_pair#define pb push_back vector<ll, ll> v; for (int i = 0; i < N; i++) { cin >> x >> y; v.pb(MP(x, y));}",
"e": 2065,
"s": 1912,
"text": null
},
{
"code": null,
"e": 2155,
"s": 2065,
"text": "Note: Write your macros at the beginning of your code(refer to the template given below)."
},
{
"code": null,
"e": 2491,
"s": 2155,
"text": "Using a TemplateUsing a template is one of the best idea to speed up your implementation. Keep your template ready that has your macros written in them already. This helps in reducing a lot of your time which otherwise would have gone in writing the whole code from scratch.I use the following template, you can use one that suits you."
},
{
"code": "#include \"bits/stdc++.h\"using namespace std;#define max(a, b) (a < b ? b : a)#define min(a, b) ((a > b) ? b : a)#define mod 1e9 + 7#define FOR(a, c) for (int(a) = 0; (a) < (c); (a)++)#define FORL(a, b, c) for (int(a) = (b); (a) <= (c); (a)++)#define FORR(a, b, c) for (int(a) = (b); (a) >= (c); (a)--)#define INF 1000000000000000003typedef long long int ll;typedef vector<int> vi;typedef pair<int, int> pi;#define F first#define S second#define PB push_back#define POB pop_back#define MP make_pairint main(){ ios::sync_with_stdio(0); cin.tie(0); int T; cin >> T; while (T--) { int N; cin >> N; ll a[N]; FOR(i, N) cin >> a[i]; } return 0;}",
"e": 3186,
"s": 2491,
"text": null
},
{
"code": null,
"e": 3279,
"s": 3186,
"text": "Thank you for reading, please let me know if you have some possible improvement or addition."
},
{
"code": null,
"e": 3307,
"s": 3279,
"text": "CPP-Competitive-Programming"
},
{
"code": null,
"e": 3311,
"s": 3307,
"text": "C++"
},
{
"code": null,
"e": 3335,
"s": 3311,
"text": "Competitive Programming"
},
{
"code": null,
"e": 3339,
"s": 3335,
"text": "CPP"
},
{
"code": null,
"e": 3437,
"s": 3339,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3461,
"s": 3437,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 3481,
"s": 3461,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 3514,
"s": 3481,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 3558,
"s": 3514,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3583,
"s": 3558,
"text": "std::string class in C++"
},
{
"code": null,
"e": 3626,
"s": 3583,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 3669,
"s": 3626,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 3710,
"s": 3669,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 3737,
"s": 3710,
"text": "Modulo 10^9+7 (1000000007)"
}
] |
Class getSimpleName() method in Java with Examples - GeeksforGeeks
|
25 Jan, 2022
The getSimpleName() method of java.lang.Class class is used to get the simple name of this class, as given in the sourcecode. The method returns the simple name of this class in the form of String. If this class is anonymous, then this method returns empty string.Syntax:
public String getSimpleName()
Parameter: This method does not accept any parameter.Return Value: This method returns the simple name of this class in the form of String. If this class is anonymous, then this method returns empty string.Below programs demonstrate the getSimpleName() method.Example 1:
Java
// Java program to demonstrate getSimpleName() method import java.util.*; public class Test { public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName("Test"); System.out.println("Class represented by myClass: " + myClass.toString()); // Get the simple name of myClass // using getSimpleName() method System.out.println("SimpleName of myClass: " + myClass.getSimpleName()); }}
Class represented by myClass: class Test
SimpleName of myClass: Test
Example 2:
Java
// Java program to demonstrate getSimpleName() method import java.util.*; class Main { public Object obj; Main() { class Arr { }; obj = new Arr(); } public static void main(String[] args) throws ClassNotFoundException { Main t = new Main(); // returns the Class object Class myClass = t.obj.getClass(); // Get the simple name of myClass // using getSimpleName() method System.out.println("SimpleName of myClass: " + myClass.getSimpleName()); }}
SimpleName of myClass: Arr
Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getSimpleName–
adnanirshad158
Java-Functions
Java-lang package
Java.lang.Class
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
Strings in Java
How to remove an element from ArrayList in Java?
Difference between Abstract Class and Interface in Java
|
[
{
"code": null,
"e": 23557,
"s": 23529,
"text": "\n25 Jan, 2022"
},
{
"code": null,
"e": 23831,
"s": 23557,
"text": "The getSimpleName() method of java.lang.Class class is used to get the simple name of this class, as given in the sourcecode. The method returns the simple name of this class in the form of String. If this class is anonymous, then this method returns empty string.Syntax: "
},
{
"code": null,
"e": 23861,
"s": 23831,
"text": "public String getSimpleName()"
},
{
"code": null,
"e": 24133,
"s": 23861,
"text": "Parameter: This method does not accept any parameter.Return Value: This method returns the simple name of this class in the form of String. If this class is anonymous, then this method returns empty string.Below programs demonstrate the getSimpleName() method.Example 1: "
},
{
"code": null,
"e": 24138,
"s": 24133,
"text": "Java"
},
{
"code": "// Java program to demonstrate getSimpleName() method import java.util.*; public class Test { public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); // Get the simple name of myClass // using getSimpleName() method System.out.println(\"SimpleName of myClass: \" + myClass.getSimpleName()); }}",
"e": 24715,
"s": 24138,
"text": null
},
{
"code": null,
"e": 24784,
"s": 24715,
"text": "Class represented by myClass: class Test\nSimpleName of myClass: Test"
},
{
"code": null,
"e": 24798,
"s": 24786,
"text": "Example 2: "
},
{
"code": null,
"e": 24803,
"s": 24798,
"text": "Java"
},
{
"code": "// Java program to demonstrate getSimpleName() method import java.util.*; class Main { public Object obj; Main() { class Arr { }; obj = new Arr(); } public static void main(String[] args) throws ClassNotFoundException { Main t = new Main(); // returns the Class object Class myClass = t.obj.getClass(); // Get the simple name of myClass // using getSimpleName() method System.out.println(\"SimpleName of myClass: \" + myClass.getSimpleName()); }}",
"e": 25372,
"s": 24803,
"text": null
},
{
"code": null,
"e": 25399,
"s": 25372,
"text": "SimpleName of myClass: Arr"
},
{
"code": null,
"e": 25491,
"s": 25401,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getSimpleName– "
},
{
"code": null,
"e": 25506,
"s": 25491,
"text": "adnanirshad158"
},
{
"code": null,
"e": 25521,
"s": 25506,
"text": "Java-Functions"
},
{
"code": null,
"e": 25539,
"s": 25521,
"text": "Java-lang package"
},
{
"code": null,
"e": 25555,
"s": 25539,
"text": "Java.lang.Class"
},
{
"code": null,
"e": 25560,
"s": 25555,
"text": "Java"
},
{
"code": null,
"e": 25565,
"s": 25560,
"text": "Java"
},
{
"code": null,
"e": 25663,
"s": 25565,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25672,
"s": 25663,
"text": "Comments"
},
{
"code": null,
"e": 25685,
"s": 25672,
"text": "Old Comments"
},
{
"code": null,
"e": 25715,
"s": 25685,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 25730,
"s": 25715,
"text": "Stream In Java"
},
{
"code": null,
"e": 25751,
"s": 25730,
"text": "Constructors in Java"
},
{
"code": null,
"e": 25797,
"s": 25751,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 25816,
"s": 25797,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 25833,
"s": 25816,
"text": "Generics in Java"
},
{
"code": null,
"e": 25876,
"s": 25833,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 25892,
"s": 25876,
"text": "Strings in Java"
},
{
"code": null,
"e": 25941,
"s": 25892,
"text": "How to remove an element from ArrayList in Java?"
}
] |
Tryit Editor v3.7
|
Tryit: HTML src attribute
|
[] |
How to Disable / Enable a Button in TKinter?
|
There are various attributes and properties in each tkinter widget to help us extend the functionality of the application. Tkinter Button widgets can be enabled and disabled by defining its state in the Button Object. The state attribute generally accepts two values Normal and Disabled which are used for enabling and disabling the button, respectively.
#Import necessary Library
from tkinter import *
from tkinter import ttk
from tkinter.filedialog import asksaveasfile
#Create an instance of tkinter window
win= Tk()
#Set the geometry of tkinter window
win.geometry("750x250")
#Define the function to change the value in label widget
def change_text(label):
label.configure(text= "Hey, I am Label-2", background="gray91")
#Create a Label
label = Label(win, text= "Hey, I am Label-1", font= ('Helvetica
15 underline'), background="gray76")
label.pack(pady=20)
#Create a button
btn= ttk.Button(win,text= "Change", command=
lambda:change_text(label), state= DISABLED)
btn.pack(pady=10)
win.mainloop()
Running the above code will display a window that has a disabled button. We can change the state of the button to Normal.
Now, change the value of the state attribute to NORMAL to make the button active on the window.
|
[
{
"code": null,
"e": 1417,
"s": 1062,
"text": "There are various attributes and properties in each tkinter widget to help us extend the functionality of the application. Tkinter Button widgets can be enabled and disabled by defining its state in the Button Object. The state attribute generally accepts two values Normal and Disabled which are used for enabling and disabling the button, respectively."
},
{
"code": null,
"e": 2066,
"s": 1417,
"text": "#Import necessary Library\nfrom tkinter import *\nfrom tkinter import ttk\nfrom tkinter.filedialog import asksaveasfile\n#Create an instance of tkinter window\nwin= Tk()\n#Set the geometry of tkinter window\nwin.geometry(\"750x250\")\n#Define the function to change the value in label widget\ndef change_text(label):\n label.configure(text= \"Hey, I am Label-2\", background=\"gray91\")\n#Create a Label\nlabel = Label(win, text= \"Hey, I am Label-1\", font= ('Helvetica\n15 underline'), background=\"gray76\")\nlabel.pack(pady=20)\n#Create a button\nbtn= ttk.Button(win,text= \"Change\", command=\nlambda:change_text(label), state= DISABLED)\nbtn.pack(pady=10)\nwin.mainloop()"
},
{
"code": null,
"e": 2188,
"s": 2066,
"text": "Running the above code will display a window that has a disabled button. We can change the state of the button to Normal."
},
{
"code": null,
"e": 2284,
"s": 2188,
"text": "Now, change the value of the state attribute to NORMAL to make the button active on the window."
}
] |
Build a Multi-Layer Map Using Streamlit | by Alex Wagner | Towards Data Science
|
― Beryl Markham, West With the Night
When it comes to visualizing data, everyone loves a good map. I think that is because a map makes us feel we are a part of the story being told. It gives us a space we can share with data and makes for a richer and more powerful message.
Thankfully, working with maps has become more democratized as open-source libraries have extended the reach of more traditional geospatial software like ArcMap and QGIS.
In addition, web-application libraries like Streamlit and Dash allow maps to be easily displayed through a web browser.
However . . .
This tutorial outlines an easy process to add selectable point and polygon layers to a Streamlit project. In my experience, giving a user the ability to add and subtract layers as needed adds alot to their experience.
Our map will be a simple one of the United States with major cities represented as points and the cartographic boundaries of 500 US cities represented as polygons.
Before we start it will be helpful to establish some vocabulary encountered in this tutorial:
Layer: If you are coming from the world of Plotly/Dash this translates to a “trace”. Layers are spatial data sets that are literally ‘layered’ on one another to build complexity into a map
Vector data: Points, lines, or polygons. Also know as “not raster” data
Point: A spatial feature with a single x,y coordinate
Line: A spatial feature connecting at least two x,y coordinates
Polygon: A spatial feature comprised of at least three connected and closed vertices
CRS (Coordinate Reference System): A set of attributes that tells a software where to position your data in space as well which mathematical model to use to flatten the globe into a 2D surface. Spatial data is not spatial without the CRS
import streamlit as stimport jsonimport geopandas as gpdimport pyprojimport plotly.graph_objs as go
A quick note: If you are using an Anaconda install of python, I would recommend creating a new environment in which to import GeoPandas. It is an incredibly useful spatial library and it has a significant number of version-specific dependencies. I recommend doing a clean install of this first and then installing the rest of the packages into that environment.
Our first step is to read in our data. For this project I have uploaded point and polygon data to the project github page that you can download locally here: https://github.com/wagneaj/mapLayers.
Let’s start with the polygon data:
# reading in the polygon shapefilepolygon = gpd.read_file(r"\Downloads\CityBoundaries.shp")
Here we used GeoPandas to read in our first bit of data. This will now hold our data as a GeoDataFrame object that you can call and manipulate much as you would a Pandas DataFrame Object. The ‘.shp’ file type indicates a shapefile which is really a set of files that help to define both the spatial and tabular information of the data. Now we can view the tabular data in a Jupyter Notebook if we wish:
Now let’s create and new object and use that to apply a specific coordinate reference system (CRS) to our data:
# project GeoPandas dataframemap_df = polygon map_df.to_crs(pyproj.CRS.from_epsg(4326), inplace=True)
‘epsg 4326’ is a coded CRS within the European Petroleum Survey Group (EPSG). It maps to the WGS 84 CRS.
Next, we will do the same thing for our point data.
# reading in the points shapefilepoints = gpd.read_file(r"\Downloads\USA_Major_Cities.shp")# project GeoPandas dataframepoints.to_crs(pyproj.CRS.from_epsg(4326), inplace=True)# define lat, long for pointsLat = points['Lat']Long = points['Long']
One key difference is the additional step of designating which columns in our data set correspond to the latitude and longitude of the points. In this case, the columns are named ‘Lat’ and ‘Long’, respectively.
Once we have all our data read in and in the correct CRS we will need to covert the polygon data set into a GeoJSON file. This GeoJSON will be used as an argument when we call our Plotly Graph Objects library.
If you are unfamiliar, GeoJSON is an open standard file format specifically used to represent spatial data. It is based on the JSON format and is how we will communicate spatial references for our polygon data with Plotly.
# set GeoJSON file pathpath = r"C:\Users\project\geojson.json"# write GeoJSON to filemap_df.to_file(path, driver = "GeoJSON") with open(path) as geofile: j_file = json.load(geofile)# index geojsoni=1for feature in j_file["features"]: feature ['id'] = str(i).zfill(2) i += 1
Here, we have set a path to export the GeoJSON ; we have called the file back into our analysis; and then we indexed each record of the file.
After we have created and indexed the GeoJSON we have one more step before we put everything together and that is to generate a mapbox token.
Mapbox provides online maps which can be accessed via an API using a mapbox token. I have generated my own token but it is a fairly painless process to do so and directions can be found here: https://docs.mapbox.com/help/glossary/access-token
With a mapbox token generated we can now begin to put our map layers together.
# mapbox tokenmapboxt = 'MapBox Token' # define layers and plot mapchoro = go.Choroplethmapbox(z=map_df['STFIPS'], locations = map_df.index, colorscale = 'Viridis', geojson = j_file, text = map_df['NAME'], marker_line_width=0.1) scatt = go.Scattermapbox(lat=Lat, lon=Long,mode='markers+text', below='False', marker=dict( size=12, color ='rgb(56, 44, 100)'))layout = go.Layout(title_text ='USA Cities', title_x =0.5, width=950, height=700,mapbox = dict(center= dict(lat=37, lon=-95),accesstoken= mapboxt, zoom=4,style="stamen- terrain"))
Here we have defined our choropleth map layer, our scatterplot map layer, and our layout all using Plotly Graph Objects. Graph Objects are dictionary-like structures that can used to conveniently store and call different Plotly figures.
Lastly, we create a Streamlit multiselect widget for layer selection; we assign our Graph Objects figure; and we make a Streamlit call to display the final map.
# streamlit multiselect widgetlayer1 = st.multiselect('Layer Selection', [choro, scatt], format_func=lambda x: 'Polygon' if x==choro else 'Points')# assign Graph Objects figurefig = go.Figure(data=layer1, layout=layout)# display streamlit mapst.plotly_chart(fig)
That’s it! Now you have the structure to add and subtract layers to a multi-layer web map. Screenshots of the finished product are below.
A great introduction to Streamlit:
A great introduction to Streamlit:
towardsdatascience.com
2) If you prefer Dash for web apps:
plotly.com
3) What Makes Spatial Data Special:
|
[
{
"code": null,
"e": 208,
"s": 171,
"text": "― Beryl Markham, West With the Night"
},
{
"code": null,
"e": 446,
"s": 208,
"text": "When it comes to visualizing data, everyone loves a good map. I think that is because a map makes us feel we are a part of the story being told. It gives us a space we can share with data and makes for a richer and more powerful message."
},
{
"code": null,
"e": 616,
"s": 446,
"text": "Thankfully, working with maps has become more democratized as open-source libraries have extended the reach of more traditional geospatial software like ArcMap and QGIS."
},
{
"code": null,
"e": 736,
"s": 616,
"text": "In addition, web-application libraries like Streamlit and Dash allow maps to be easily displayed through a web browser."
},
{
"code": null,
"e": 750,
"s": 736,
"text": "However . . ."
},
{
"code": null,
"e": 968,
"s": 750,
"text": "This tutorial outlines an easy process to add selectable point and polygon layers to a Streamlit project. In my experience, giving a user the ability to add and subtract layers as needed adds alot to their experience."
},
{
"code": null,
"e": 1132,
"s": 968,
"text": "Our map will be a simple one of the United States with major cities represented as points and the cartographic boundaries of 500 US cities represented as polygons."
},
{
"code": null,
"e": 1226,
"s": 1132,
"text": "Before we start it will be helpful to establish some vocabulary encountered in this tutorial:"
},
{
"code": null,
"e": 1415,
"s": 1226,
"text": "Layer: If you are coming from the world of Plotly/Dash this translates to a “trace”. Layers are spatial data sets that are literally ‘layered’ on one another to build complexity into a map"
},
{
"code": null,
"e": 1487,
"s": 1415,
"text": "Vector data: Points, lines, or polygons. Also know as “not raster” data"
},
{
"code": null,
"e": 1541,
"s": 1487,
"text": "Point: A spatial feature with a single x,y coordinate"
},
{
"code": null,
"e": 1605,
"s": 1541,
"text": "Line: A spatial feature connecting at least two x,y coordinates"
},
{
"code": null,
"e": 1690,
"s": 1605,
"text": "Polygon: A spatial feature comprised of at least three connected and closed vertices"
},
{
"code": null,
"e": 1928,
"s": 1690,
"text": "CRS (Coordinate Reference System): A set of attributes that tells a software where to position your data in space as well which mathematical model to use to flatten the globe into a 2D surface. Spatial data is not spatial without the CRS"
},
{
"code": null,
"e": 2028,
"s": 1928,
"text": "import streamlit as stimport jsonimport geopandas as gpdimport pyprojimport plotly.graph_objs as go"
},
{
"code": null,
"e": 2390,
"s": 2028,
"text": "A quick note: If you are using an Anaconda install of python, I would recommend creating a new environment in which to import GeoPandas. It is an incredibly useful spatial library and it has a significant number of version-specific dependencies. I recommend doing a clean install of this first and then installing the rest of the packages into that environment."
},
{
"code": null,
"e": 2586,
"s": 2390,
"text": "Our first step is to read in our data. For this project I have uploaded point and polygon data to the project github page that you can download locally here: https://github.com/wagneaj/mapLayers."
},
{
"code": null,
"e": 2621,
"s": 2586,
"text": "Let’s start with the polygon data:"
},
{
"code": null,
"e": 2713,
"s": 2621,
"text": "# reading in the polygon shapefilepolygon = gpd.read_file(r\"\\Downloads\\CityBoundaries.shp\")"
},
{
"code": null,
"e": 3116,
"s": 2713,
"text": "Here we used GeoPandas to read in our first bit of data. This will now hold our data as a GeoDataFrame object that you can call and manipulate much as you would a Pandas DataFrame Object. The ‘.shp’ file type indicates a shapefile which is really a set of files that help to define both the spatial and tabular information of the data. Now we can view the tabular data in a Jupyter Notebook if we wish:"
},
{
"code": null,
"e": 3228,
"s": 3116,
"text": "Now let’s create and new object and use that to apply a specific coordinate reference system (CRS) to our data:"
},
{
"code": null,
"e": 3330,
"s": 3228,
"text": "# project GeoPandas dataframemap_df = polygon map_df.to_crs(pyproj.CRS.from_epsg(4326), inplace=True)"
},
{
"code": null,
"e": 3435,
"s": 3330,
"text": "‘epsg 4326’ is a coded CRS within the European Petroleum Survey Group (EPSG). It maps to the WGS 84 CRS."
},
{
"code": null,
"e": 3487,
"s": 3435,
"text": "Next, we will do the same thing for our point data."
},
{
"code": null,
"e": 3732,
"s": 3487,
"text": "# reading in the points shapefilepoints = gpd.read_file(r\"\\Downloads\\USA_Major_Cities.shp\")# project GeoPandas dataframepoints.to_crs(pyproj.CRS.from_epsg(4326), inplace=True)# define lat, long for pointsLat = points['Lat']Long = points['Long']"
},
{
"code": null,
"e": 3943,
"s": 3732,
"text": "One key difference is the additional step of designating which columns in our data set correspond to the latitude and longitude of the points. In this case, the columns are named ‘Lat’ and ‘Long’, respectively."
},
{
"code": null,
"e": 4153,
"s": 3943,
"text": "Once we have all our data read in and in the correct CRS we will need to covert the polygon data set into a GeoJSON file. This GeoJSON will be used as an argument when we call our Plotly Graph Objects library."
},
{
"code": null,
"e": 4376,
"s": 4153,
"text": "If you are unfamiliar, GeoJSON is an open standard file format specifically used to represent spatial data. It is based on the JSON format and is how we will communicate spatial references for our polygon data with Plotly."
},
{
"code": null,
"e": 4658,
"s": 4376,
"text": "# set GeoJSON file pathpath = r\"C:\\Users\\project\\geojson.json\"# write GeoJSON to filemap_df.to_file(path, driver = \"GeoJSON\") with open(path) as geofile: j_file = json.load(geofile)# index geojsoni=1for feature in j_file[\"features\"]: feature ['id'] = str(i).zfill(2) i += 1"
},
{
"code": null,
"e": 4800,
"s": 4658,
"text": "Here, we have set a path to export the GeoJSON ; we have called the file back into our analysis; and then we indexed each record of the file."
},
{
"code": null,
"e": 4942,
"s": 4800,
"text": "After we have created and indexed the GeoJSON we have one more step before we put everything together and that is to generate a mapbox token."
},
{
"code": null,
"e": 5185,
"s": 4942,
"text": "Mapbox provides online maps which can be accessed via an API using a mapbox token. I have generated my own token but it is a fairly painless process to do so and directions can be found here: https://docs.mapbox.com/help/glossary/access-token"
},
{
"code": null,
"e": 5264,
"s": 5185,
"text": "With a mapbox token generated we can now begin to put our map layers together."
},
{
"code": null,
"e": 5867,
"s": 5264,
"text": "# mapbox tokenmapboxt = 'MapBox Token' # define layers and plot mapchoro = go.Choroplethmapbox(z=map_df['STFIPS'], locations = map_df.index, colorscale = 'Viridis', geojson = j_file, text = map_df['NAME'], marker_line_width=0.1) scatt = go.Scattermapbox(lat=Lat, lon=Long,mode='markers+text', below='False', marker=dict( size=12, color ='rgb(56, 44, 100)'))layout = go.Layout(title_text ='USA Cities', title_x =0.5, width=950, height=700,mapbox = dict(center= dict(lat=37, lon=-95),accesstoken= mapboxt, zoom=4,style=\"stamen- terrain\"))"
},
{
"code": null,
"e": 6104,
"s": 5867,
"text": "Here we have defined our choropleth map layer, our scatterplot map layer, and our layout all using Plotly Graph Objects. Graph Objects are dictionary-like structures that can used to conveniently store and call different Plotly figures."
},
{
"code": null,
"e": 6265,
"s": 6104,
"text": "Lastly, we create a Streamlit multiselect widget for layer selection; we assign our Graph Objects figure; and we make a Streamlit call to display the final map."
},
{
"code": null,
"e": 6537,
"s": 6265,
"text": "# streamlit multiselect widgetlayer1 = st.multiselect('Layer Selection', [choro, scatt], format_func=lambda x: 'Polygon' if x==choro else 'Points')# assign Graph Objects figurefig = go.Figure(data=layer1, layout=layout)# display streamlit mapst.plotly_chart(fig)"
},
{
"code": null,
"e": 6675,
"s": 6537,
"text": "That’s it! Now you have the structure to add and subtract layers to a multi-layer web map. Screenshots of the finished product are below."
},
{
"code": null,
"e": 6710,
"s": 6675,
"text": "A great introduction to Streamlit:"
},
{
"code": null,
"e": 6745,
"s": 6710,
"text": "A great introduction to Streamlit:"
},
{
"code": null,
"e": 6768,
"s": 6745,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 6804,
"s": 6768,
"text": "2) If you prefer Dash for web apps:"
},
{
"code": null,
"e": 6815,
"s": 6804,
"text": "plotly.com"
}
] |
Maximize count of rows consisting of equal elements by flipping columns of a Matrix - GeeksforGeeks
|
02 Feb, 2022
Given a binary matrix, mat[][] of dimensions N * M, the task is to maximize the count of rows consisting only of equal elements by selecting any column of the matrix and flipping all the elements of that column in each operation. Print the maximum number of rows that can be made to form equal elements.
Examples:
Input: mat[][] = { { 0, 1, 0, 0, 1 }, { 1, 1, 0, 1, 1 }, { 1, 0, 1, 1, 0 } } Output: 2 Explanation: Select the 2nd column and flip all the elements of that column to modify mat[][] to { { 0, 0, 0, 0, 1 }, { 1, 0, 0, 1, 1 }, { 1, 1, 1, 1, 0 } } Select the 5th column and flip all the elements of that column to modify mat[][] to { { 0, 0, 0, 0, 0 }, { 1, 0, 0, 1, 0 }, { 1, 1, 1, 1, 1 } } Since all elements of the 1st row and the 3rd row of the matrix are equal and is also the maximum number of rows that can be made to contain equal elements only, the required output is 2.Input: mat[][] = { {0, 0}, {0, 1} } Output: 1
Naive Approach: The simplest approach to solve this problem is to count the number of rows which contains equal elements only, for every possible way of selecting a combination of columns and flipping its elements. Finally, print the maximum count obtained for any of the above combinations. Time Complexity: O(N * M * 2M) Auxiliary Space: O(N * M)
Efficient Approach: To optimize the above approach, the idea is based on the fact that, if one row is 1‘s complement of the other row or both rows are the same, then only both the rows will contain equal elements only by performing the given operations.
Illustration:Let us consider the following matrix:
In the above matrix, 1st and 2nd rows are 1’s complement of each other, and the 5th and 4th rows are 1’s complement of each other.
Follow the steps below to solve the problem:
Initialize a variable, say cntMaxRows, to store the maximum count of rows consisting of equal elements only.
Initialize a Map, say mp, to store all possible rows of the matrix.
Traverse each row of the matrix and store it in the Map.
Traverse each row of the matrix using variable row. Calculate 1‘s complement of row and update cntMaxRows = max(cntMaxRows, mp[row] + mp[1’s_comp_row])
Finally, print the value of cntMaxRows.
Below is the implementation of our approach:
C++
Java
C#
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to find the maximum number// of rows containing all equal elementsint maxEqrows(vector<vector<int> >& mat, int N, int M){ // Store each row of the matrix map<vector<int>, int> mp; // Traverse each row of the matrix for (int i = 0; i < N; i++) { // Update frequency of // current row mp[mat[i]]++; } // Stores maximum count of rows // containing all equal elements int cntMaxRows = 0; // Traverse each row of the matrix for (int i = 0; i < N; i++) { // Stores 1's complement // of the current row vector<int> onesCompRow(M, 0); // Traverse current row // of the given matrix for (int j = 0; j < M; j++) { // Stores 1s complement of // mat[i][j] onesCompRow[j] = (mat[i][j] ^ 1); } // Update cntMaxRows cntMaxRows = max(cntMaxRows, mp[mat[i]] + mp[onesCompRow]); } return cntMaxRows;} // Driver Codeint main(){ vector<vector<int> > mat = { { 0, 1, 0, 0, 1 }, { 1, 1, 0, 1, 1 }, { 1, 0, 1, 1, 0 } }; // Stores count of rows int N = mat.size(); // Stores count of columns int M = mat[0].size(); cout << maxEqrows(mat, N, M);}
// Java program to implementimport java.util.*;class GFG{ // Function to find the maximum number // of rows containing all equal elements static int maxEqrows(Vector<Vector<Integer>> mat, int N, int M) { // Store each row of the matrix HashMap<Vector<Integer>, Integer> mp = new HashMap<>(); // Traverse each row of the matrix for (int i = 0; i < N; i++) { // Update frequency of // current row if(mp.containsKey(mat.get(i))) { mp.put(mat.get(i), mp.get(mat.get(i)) + 1); } else { mp.put(mat.get(i), 1); } } // Stores maximum count of rows // containing all equal elements int cntMaxRows = 0; // Traverse each row of the matrix for (int i = 0; i < N; i++) { // Stores 1's complement // of the current row Vector<Integer> onesCompRow = new Vector<Integer>(); for(int j = 0; j < M; j++) { onesCompRow.add(0); } // Traverse current row // of the given matrix for (int j = 0; j < M; j++) { // Stores 1s complement of // mat[i][j] onesCompRow.set(j, mat.get(i).get(j) ^ 1); } // Update cntMaxRows if(!mp.containsKey(mat.get(i))) { cntMaxRows = Math.max(cntMaxRows, mp.get(onesCompRow)); } else if(!mp.containsKey(onesCompRow)) { cntMaxRows = Math.max(cntMaxRows, mp.get(mat.get(i))); } else { cntMaxRows = Math.max(cntMaxRows, mp.get(mat.get(i)) + mp.get(onesCompRow)); } } return cntMaxRows; } // Driver code public static void main(String[] args) { Vector<Vector<Integer>> mat = new Vector<Vector<Integer>>(); mat.add(new Vector<Integer>()); mat.add(new Vector<Integer>()); mat.add(new Vector<Integer>()); mat.get(0).add(0); mat.get(0).add(1); mat.get(0).add(0); mat.get(0).add(0); mat.get(0).add(1); mat.get(1).add(1); mat.get(1).add(1); mat.get(1).add(0); mat.get(1).add(1); mat.get(1).add(1); mat.get(2).add(1); mat.get(2).add(0); mat.get(2).add(1); mat.get(2).add(1); mat.get(2).add(0); // Stores count of rows int N = mat.size(); // Stores count of columns int M = mat.get(0).size(); System.out.println(maxEqrows(mat, N, M)); }} // This code is contributed by divyesh072019
// C# program to implement// the above approachusing System;using System.Collections.Generic; class GFG { // Function to find the maximum number // of rows containing all equal elements static int maxEqrows(List<List<int>> mat, int N, int M) { // Store each row of the matrix Dictionary<List<int>, int> mp = new Dictionary<List<int>, int>(); // Traverse each row of the matrix for (int i = 0; i < N; i++) { // Update frequency of // current row if(mp.ContainsKey(mat[i])) { mp[mat[i]]++; } else{ mp[mat[i]] = 1; } } // Stores maximum count of rows // containing all equal elements int cntMaxRows = 0; // Traverse each row of the matrix for (int i = 0; i < N; i++) { // Stores 1's complement // of the current row List<int> onesCompRow = new List<int>(); for(int j = 0; j < M; j++) { onesCompRow.Add(0); } // Traverse current row // of the given matrix for (int j = 0; j < M; j++) { // Stores 1s complement of // mat[i][j] onesCompRow[j] = (mat[i][j] ^ 1); } // Update cntMaxRows if(!mp.ContainsKey(mat[i])) { cntMaxRows = Math.Max(cntMaxRows, mp[onesCompRow] + 1); } else if(!mp.ContainsKey(onesCompRow)) { cntMaxRows = Math.Max(cntMaxRows, mp[mat[i]] + 1); } else{ cntMaxRows = Math.Max(cntMaxRows, mp[mat[i]] + mp[onesCompRow] + 1); } } return cntMaxRows; } // Driver code static void Main() { List<List<int>> mat = new List<List<int>>(); mat.Add(new List<int> { 0, 1, 0, 0, 1 }); mat.Add(new List<int> { 1, 1, 0, 1, 1 }); mat.Add(new List<int> { 1, 0, 1, 1, 0 }); // Stores count of rows int N = mat.Count; // Stores count of columns int M = mat[0].Count; Console.WriteLine(maxEqrows(mat, N, M)); }} // This code is contributed by divyeshrabadiya07
2
Time Complexity: O(N * M) Auxiliary Space: O(M)
divyeshrabadiya07
divyesh072019
sumitgumber28
array-rearrange
binary-representation
cpp-map
Bit Magic
Greedy
Hash
Mathematical
Matrix
Hash
Greedy
Mathematical
Bit Magic
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Cyclic Redundancy Check and Modulo-2 Division
Little and Big Endian Mystery
Binary representation of a given number
Add two numbers without using arithmetic operators
Program to find whether a given number is power of 2
Dijkstra's shortest path algorithm | Greedy Algo-7
Program for array rotation
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Huffman Coding | Greedy Algo-3
|
[
{
"code": null,
"e": 25139,
"s": 25111,
"text": "\n02 Feb, 2022"
},
{
"code": null,
"e": 25443,
"s": 25139,
"text": "Given a binary matrix, mat[][] of dimensions N * M, the task is to maximize the count of rows consisting only of equal elements by selecting any column of the matrix and flipping all the elements of that column in each operation. Print the maximum number of rows that can be made to form equal elements."
},
{
"code": null,
"e": 25453,
"s": 25443,
"text": "Examples:"
},
{
"code": null,
"e": 26076,
"s": 25453,
"text": "Input: mat[][] = { { 0, 1, 0, 0, 1 }, { 1, 1, 0, 1, 1 }, { 1, 0, 1, 1, 0 } } Output: 2 Explanation: Select the 2nd column and flip all the elements of that column to modify mat[][] to { { 0, 0, 0, 0, 1 }, { 1, 0, 0, 1, 1 }, { 1, 1, 1, 1, 0 } } Select the 5th column and flip all the elements of that column to modify mat[][] to { { 0, 0, 0, 0, 0 }, { 1, 0, 0, 1, 0 }, { 1, 1, 1, 1, 1 } } Since all elements of the 1st row and the 3rd row of the matrix are equal and is also the maximum number of rows that can be made to contain equal elements only, the required output is 2.Input: mat[][] = { {0, 0}, {0, 1} } Output: 1 "
},
{
"code": null,
"e": 26425,
"s": 26076,
"text": "Naive Approach: The simplest approach to solve this problem is to count the number of rows which contains equal elements only, for every possible way of selecting a combination of columns and flipping its elements. Finally, print the maximum count obtained for any of the above combinations. Time Complexity: O(N * M * 2M) Auxiliary Space: O(N * M)"
},
{
"code": null,
"e": 26679,
"s": 26425,
"text": "Efficient Approach: To optimize the above approach, the idea is based on the fact that, if one row is 1‘s complement of the other row or both rows are the same, then only both the rows will contain equal elements only by performing the given operations."
},
{
"code": null,
"e": 26731,
"s": 26679,
"text": "Illustration:Let us consider the following matrix: "
},
{
"code": null,
"e": 26864,
"s": 26731,
"text": "In the above matrix, 1st and 2nd rows are 1’s complement of each other, and the 5th and 4th rows are 1’s complement of each other. "
},
{
"code": null,
"e": 26909,
"s": 26864,
"text": "Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 27018,
"s": 26909,
"text": "Initialize a variable, say cntMaxRows, to store the maximum count of rows consisting of equal elements only."
},
{
"code": null,
"e": 27086,
"s": 27018,
"text": "Initialize a Map, say mp, to store all possible rows of the matrix."
},
{
"code": null,
"e": 27143,
"s": 27086,
"text": "Traverse each row of the matrix and store it in the Map."
},
{
"code": null,
"e": 27297,
"s": 27143,
"text": "Traverse each row of the matrix using variable row. Calculate 1‘s complement of row and update cntMaxRows = max(cntMaxRows, mp[row] + mp[1’s_comp_row]) "
},
{
"code": null,
"e": 27337,
"s": 27297,
"text": "Finally, print the value of cntMaxRows."
},
{
"code": null,
"e": 27382,
"s": 27337,
"text": "Below is the implementation of our approach:"
},
{
"code": null,
"e": 27386,
"s": 27382,
"text": "C++"
},
{
"code": null,
"e": 27391,
"s": 27386,
"text": "Java"
},
{
"code": null,
"e": 27394,
"s": 27391,
"text": "C#"
},
{
"code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to find the maximum number// of rows containing all equal elementsint maxEqrows(vector<vector<int> >& mat, int N, int M){ // Store each row of the matrix map<vector<int>, int> mp; // Traverse each row of the matrix for (int i = 0; i < N; i++) { // Update frequency of // current row mp[mat[i]]++; } // Stores maximum count of rows // containing all equal elements int cntMaxRows = 0; // Traverse each row of the matrix for (int i = 0; i < N; i++) { // Stores 1's complement // of the current row vector<int> onesCompRow(M, 0); // Traverse current row // of the given matrix for (int j = 0; j < M; j++) { // Stores 1s complement of // mat[i][j] onesCompRow[j] = (mat[i][j] ^ 1); } // Update cntMaxRows cntMaxRows = max(cntMaxRows, mp[mat[i]] + mp[onesCompRow]); } return cntMaxRows;} // Driver Codeint main(){ vector<vector<int> > mat = { { 0, 1, 0, 0, 1 }, { 1, 1, 0, 1, 1 }, { 1, 0, 1, 1, 0 } }; // Stores count of rows int N = mat.size(); // Stores count of columns int M = mat[0].size(); cout << maxEqrows(mat, N, M);}",
"e": 28786,
"s": 27394,
"text": null
},
{
"code": "// Java program to implementimport java.util.*;class GFG{ // Function to find the maximum number // of rows containing all equal elements static int maxEqrows(Vector<Vector<Integer>> mat, int N, int M) { // Store each row of the matrix HashMap<Vector<Integer>, Integer> mp = new HashMap<>(); // Traverse each row of the matrix for (int i = 0; i < N; i++) { // Update frequency of // current row if(mp.containsKey(mat.get(i))) { mp.put(mat.get(i), mp.get(mat.get(i)) + 1); } else { mp.put(mat.get(i), 1); } } // Stores maximum count of rows // containing all equal elements int cntMaxRows = 0; // Traverse each row of the matrix for (int i = 0; i < N; i++) { // Stores 1's complement // of the current row Vector<Integer> onesCompRow = new Vector<Integer>(); for(int j = 0; j < M; j++) { onesCompRow.add(0); } // Traverse current row // of the given matrix for (int j = 0; j < M; j++) { // Stores 1s complement of // mat[i][j] onesCompRow.set(j, mat.get(i).get(j) ^ 1); } // Update cntMaxRows if(!mp.containsKey(mat.get(i))) { cntMaxRows = Math.max(cntMaxRows, mp.get(onesCompRow)); } else if(!mp.containsKey(onesCompRow)) { cntMaxRows = Math.max(cntMaxRows, mp.get(mat.get(i))); } else { cntMaxRows = Math.max(cntMaxRows, mp.get(mat.get(i)) + mp.get(onesCompRow)); } } return cntMaxRows; } // Driver code public static void main(String[] args) { Vector<Vector<Integer>> mat = new Vector<Vector<Integer>>(); mat.add(new Vector<Integer>()); mat.add(new Vector<Integer>()); mat.add(new Vector<Integer>()); mat.get(0).add(0); mat.get(0).add(1); mat.get(0).add(0); mat.get(0).add(0); mat.get(0).add(1); mat.get(1).add(1); mat.get(1).add(1); mat.get(1).add(0); mat.get(1).add(1); mat.get(1).add(1); mat.get(2).add(1); mat.get(2).add(0); mat.get(2).add(1); mat.get(2).add(1); mat.get(2).add(0); // Stores count of rows int N = mat.size(); // Stores count of columns int M = mat.get(0).size(); System.out.println(maxEqrows(mat, N, M)); }} // This code is contributed by divyesh072019",
"e": 31167,
"s": 28786,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;using System.Collections.Generic; class GFG { // Function to find the maximum number // of rows containing all equal elements static int maxEqrows(List<List<int>> mat, int N, int M) { // Store each row of the matrix Dictionary<List<int>, int> mp = new Dictionary<List<int>, int>(); // Traverse each row of the matrix for (int i = 0; i < N; i++) { // Update frequency of // current row if(mp.ContainsKey(mat[i])) { mp[mat[i]]++; } else{ mp[mat[i]] = 1; } } // Stores maximum count of rows // containing all equal elements int cntMaxRows = 0; // Traverse each row of the matrix for (int i = 0; i < N; i++) { // Stores 1's complement // of the current row List<int> onesCompRow = new List<int>(); for(int j = 0; j < M; j++) { onesCompRow.Add(0); } // Traverse current row // of the given matrix for (int j = 0; j < M; j++) { // Stores 1s complement of // mat[i][j] onesCompRow[j] = (mat[i][j] ^ 1); } // Update cntMaxRows if(!mp.ContainsKey(mat[i])) { cntMaxRows = Math.Max(cntMaxRows, mp[onesCompRow] + 1); } else if(!mp.ContainsKey(onesCompRow)) { cntMaxRows = Math.Max(cntMaxRows, mp[mat[i]] + 1); } else{ cntMaxRows = Math.Max(cntMaxRows, mp[mat[i]] + mp[onesCompRow] + 1); } } return cntMaxRows; } // Driver code static void Main() { List<List<int>> mat = new List<List<int>>(); mat.Add(new List<int> { 0, 1, 0, 0, 1 }); mat.Add(new List<int> { 1, 1, 0, 1, 1 }); mat.Add(new List<int> { 1, 0, 1, 1, 0 }); // Stores count of rows int N = mat.Count; // Stores count of columns int M = mat[0].Count; Console.WriteLine(maxEqrows(mat, N, M)); }} // This code is contributed by divyeshrabadiya07",
"e": 33098,
"s": 31167,
"text": null
},
{
"code": null,
"e": 33100,
"s": 33098,
"text": "2"
},
{
"code": null,
"e": 33150,
"s": 33102,
"text": "Time Complexity: O(N * M) Auxiliary Space: O(M)"
},
{
"code": null,
"e": 33168,
"s": 33150,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 33182,
"s": 33168,
"text": "divyesh072019"
},
{
"code": null,
"e": 33196,
"s": 33182,
"text": "sumitgumber28"
},
{
"code": null,
"e": 33212,
"s": 33196,
"text": "array-rearrange"
},
{
"code": null,
"e": 33234,
"s": 33212,
"text": "binary-representation"
},
{
"code": null,
"e": 33242,
"s": 33234,
"text": "cpp-map"
},
{
"code": null,
"e": 33252,
"s": 33242,
"text": "Bit Magic"
},
{
"code": null,
"e": 33259,
"s": 33252,
"text": "Greedy"
},
{
"code": null,
"e": 33264,
"s": 33259,
"text": "Hash"
},
{
"code": null,
"e": 33277,
"s": 33264,
"text": "Mathematical"
},
{
"code": null,
"e": 33284,
"s": 33277,
"text": "Matrix"
},
{
"code": null,
"e": 33289,
"s": 33284,
"text": "Hash"
},
{
"code": null,
"e": 33296,
"s": 33289,
"text": "Greedy"
},
{
"code": null,
"e": 33309,
"s": 33296,
"text": "Mathematical"
},
{
"code": null,
"e": 33319,
"s": 33309,
"text": "Bit Magic"
},
{
"code": null,
"e": 33326,
"s": 33319,
"text": "Matrix"
},
{
"code": null,
"e": 33424,
"s": 33326,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33433,
"s": 33424,
"text": "Comments"
},
{
"code": null,
"e": 33446,
"s": 33433,
"text": "Old Comments"
},
{
"code": null,
"e": 33492,
"s": 33446,
"text": "Cyclic Redundancy Check and Modulo-2 Division"
},
{
"code": null,
"e": 33522,
"s": 33492,
"text": "Little and Big Endian Mystery"
},
{
"code": null,
"e": 33562,
"s": 33522,
"text": "Binary representation of a given number"
},
{
"code": null,
"e": 33613,
"s": 33562,
"text": "Add two numbers without using arithmetic operators"
},
{
"code": null,
"e": 33666,
"s": 33613,
"text": "Program to find whether a given number is power of 2"
},
{
"code": null,
"e": 33717,
"s": 33666,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 33744,
"s": 33717,
"text": "Program for array rotation"
},
{
"code": null,
"e": 33795,
"s": 33744,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 33853,
"s": 33795,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
}
] |
Prime number program in Java.
|
Following is the required program.
Live Demo
public class Tester {
public static void main(String args[]) {
int i, m = 0, flag = 0;
int n = 41;// it is the number to be checked
m = n / 2;
if (n == 0 || n == 1) {
System.out.println(n + " not a prime number");
} else {
for (i = 2; i <= m; i++) {
if (n % i == 0) {
System.out.println(n + " not a prime number");
flag = 1;
break;
}
}
if (flag == 0) {
System.out.println(n + " is a prime number");
}
}
}
}
41 is a prime number.
|
[
{
"code": null,
"e": 1097,
"s": 1062,
"text": "Following is the required program."
},
{
"code": null,
"e": 1107,
"s": 1097,
"text": "Live Demo"
},
{
"code": null,
"e": 1682,
"s": 1107,
"text": "public class Tester {\n public static void main(String args[]) {\n int i, m = 0, flag = 0;\n int n = 41;// it is the number to be checked\n m = n / 2;\n if (n == 0 || n == 1) {\n System.out.println(n + \" not a prime number\");\n } else {\n for (i = 2; i <= m; i++) {\n if (n % i == 0) {\n System.out.println(n + \" not a prime number\");\n flag = 1;\n break;\n }\n }\n if (flag == 0) {\n System.out.println(n + \" is a prime number\");\n }\n }\n }\n}"
},
{
"code": null,
"e": 1704,
"s": 1682,
"text": "41 is a prime number."
}
] |
What are reference data types in Java?
|
Reference datatypes in java are those which contains reference/address of dynamically created objects. These are not predefined like primitive data types.
Following are the reference types in Java.
class types − This reference type points to an object of a class.
class types − This reference type points to an object of a class.
array types − This reference type points to an array.
array types − This reference type points to an array.
interface types − This reference type points to an object of a class which implements an interface.
interface types − This reference type points to an object of a class which implements an interface.
Once we create a variable of these types (i.e. when we create an array or object, class or interface).
These variables only store the address of these values.
These variables only store the address of these values.
Default value of any reference variable is null.
Default value of any reference variable is null.
A reference variable can be used to refer any object of the declared type or any compatible type.
A reference variable can be used to refer any object of the declared type or any compatible type.
Animal animal = new Animal("giraffe");
|
[
{
"code": null,
"e": 1217,
"s": 1062,
"text": "Reference datatypes in java are those which contains reference/address of dynamically created objects. These are not predefined like primitive data types."
},
{
"code": null,
"e": 1260,
"s": 1217,
"text": "Following are the reference types in Java."
},
{
"code": null,
"e": 1326,
"s": 1260,
"text": "class types − This reference type points to an object of a class."
},
{
"code": null,
"e": 1392,
"s": 1326,
"text": "class types − This reference type points to an object of a class."
},
{
"code": null,
"e": 1446,
"s": 1392,
"text": "array types − This reference type points to an array."
},
{
"code": null,
"e": 1500,
"s": 1446,
"text": "array types − This reference type points to an array."
},
{
"code": null,
"e": 1600,
"s": 1500,
"text": "interface types − This reference type points to an object of a class which implements an interface."
},
{
"code": null,
"e": 1700,
"s": 1600,
"text": "interface types − This reference type points to an object of a class which implements an interface."
},
{
"code": null,
"e": 1803,
"s": 1700,
"text": "Once we create a variable of these types (i.e. when we create an array or object, class or interface)."
},
{
"code": null,
"e": 1859,
"s": 1803,
"text": "These variables only store the address of these values."
},
{
"code": null,
"e": 1915,
"s": 1859,
"text": "These variables only store the address of these values."
},
{
"code": null,
"e": 1964,
"s": 1915,
"text": "Default value of any reference variable is null."
},
{
"code": null,
"e": 2013,
"s": 1964,
"text": "Default value of any reference variable is null."
},
{
"code": null,
"e": 2111,
"s": 2013,
"text": "A reference variable can be used to refer any object of the declared type or any compatible type."
},
{
"code": null,
"e": 2209,
"s": 2111,
"text": "A reference variable can be used to refer any object of the declared type or any compatible type."
},
{
"code": null,
"e": 2248,
"s": 2209,
"text": "Animal animal = new Animal(\"giraffe\");"
}
] |
BufferedInputStream reset() method in Java with Examples - GeeksforGeeks
|
05 Jun, 2020
The reset() method of BufferedInputStream class in Java is used to reset the position of the stream to the position at the time the mark method was last called. It is used with the combination of mark() method of the same class.
General Contract:There are two cases:
If mark() and reset() are supported i.e., if markSupported returns true,An IOException might be thrown if the mark() is not called since the creation of the input stream or the bytes that are read from the input stream since the last call of mark() method is greater than the argument to mark method at the last call.In case an IOException is not thrown, then the input stream is reset to a state such that all the bytes that are read after the most recent call of mark() is supplied again to subsequent callers of the read(). This is followed by the bytes that would have at reset() call.If mark() and reset() are not supported i.e., if markSupported returns false,Calling reset() method might throw an IOException.In case an IOException is not thrown, then input stream is reset to a fixed state that depends on the particular type of the input stream. The supplied bytes to subsequent callers of the read() depend on the particular type of the input stream.
If mark() and reset() are supported i.e., if markSupported returns true,An IOException might be thrown if the mark() is not called since the creation of the input stream or the bytes that are read from the input stream since the last call of mark() method is greater than the argument to mark method at the last call.In case an IOException is not thrown, then the input stream is reset to a state such that all the bytes that are read after the most recent call of mark() is supplied again to subsequent callers of the read(). This is followed by the bytes that would have at reset() call.
An IOException might be thrown if the mark() is not called since the creation of the input stream or the bytes that are read from the input stream since the last call of mark() method is greater than the argument to mark method at the last call.
In case an IOException is not thrown, then the input stream is reset to a state such that all the bytes that are read after the most recent call of mark() is supplied again to subsequent callers of the read(). This is followed by the bytes that would have at reset() call.
If mark() and reset() are not supported i.e., if markSupported returns false,Calling reset() method might throw an IOException.In case an IOException is not thrown, then input stream is reset to a fixed state that depends on the particular type of the input stream. The supplied bytes to subsequent callers of the read() depend on the particular type of the input stream.
Calling reset() method might throw an IOException.
In case an IOException is not thrown, then input stream is reset to a fixed state that depends on the particular type of the input stream. The supplied bytes to subsequent callers of the read() depend on the particular type of the input stream.
Syntax:
public void reset()
Overrides: The method overrides the reset class in FilterInputStream.
Parameters: This method does not accept any parameter.
Return value: This method does not return any value.
Exception: This method throws IOException if this stream has not been marked or mark has been invalidated or input stream has been closed by invoking the close() method or an I/O error occurs.
Below programs illustrates reset() method in BufferedInputStream class in IO package:
Program 1: Assume the existence of file “c:/demo.txt”.
// Java program to illustrate// BufferedInputStream reset() methodimport java.io.*;public class GFG { public static void main(String[] args) { // Create input stream 'demo.txt' // for reading containing text "GEEKS" FileInputStream inputStream = new FileInputStream( "c:/demo.txt"); // Convert inputStream to // bufferedInputStream BufferedInputStream buffInputStr = new BufferedInputStream( inputStream); // Read and print characters one by one System.out.println( "Char : " + (char)buffInputStr.read()); System.out.println( "Char : " + (char)buffInputStr.read()); System.out.println( "Char : " + (char)buffInputStr.read()); // Mark is set on the input stream buffInputStr.mark(0); System.out.println( "Char : " + (char)buffInputStr.read()); System.out.println( "reset() called"); // Reset() is invoked buffInputStr.reset(); // Read and print characters System.out.println( "Char : " + (char)buffInputStr.read()); System.out.println( "Char : " + (char)buffInputStr.read()); }}
Program 2: Assume the existence of file “c:/demo.txt”.
// Java program to illustrate// BufferedInputStream reset() methodimport java.io.*;public class GFG { public static void main(String[] args) { // Create input stream 'demo.txt' // for reading containing text // "GEEKSFORGEEKS" FileInputStream inputStream = new FileInputStream( "c:/demo.txt"); // Convert inputStream to // bufferedInputStream BufferedInputStream buffInputStr = new BufferedInputStream( inputStream); // Read and print characters one by one System.out.println( "Char : " + (char)buffInputStr.read()); System.out.println( "Char : " + (char)buffInputStr.read()); System.out.println( "Char : " + (char)buffInputStr.read()); System.out.println( "Char : " + (char)buffInputStr.read()); // Mark is set on the input stream buffInputStr.mark(0); System.out.println( "Char : " + (char)buffInputStr.read()); System.out.println( "reset() called"); // Reset() is invoked buffInputStr.reset(); // Read and print characters System.out.println( "Char : " + (char)buffInputStr.read()); System.out.println( "Char : " + (char)buffInputStr.read()); System.out.println( "Char : " + (char)buffInputStr.read()); System.out.println( "Char : " + (char)buffInputStr.read()); }}
References:https://docs.oracle.com/javase/10/docs/api/java/io/BufferedInputStream.html#reset()
Java-Functions
Java-IO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
Strings in Java
How to remove an element from ArrayList in Java?
Difference between Abstract Class and Interface in Java
|
[
{
"code": null,
"e": 23557,
"s": 23529,
"text": "\n05 Jun, 2020"
},
{
"code": null,
"e": 23786,
"s": 23557,
"text": "The reset() method of BufferedInputStream class in Java is used to reset the position of the stream to the position at the time the mark method was last called. It is used with the combination of mark() method of the same class."
},
{
"code": null,
"e": 23824,
"s": 23786,
"text": "General Contract:There are two cases:"
},
{
"code": null,
"e": 24785,
"s": 23824,
"text": "If mark() and reset() are supported i.e., if markSupported returns true,An IOException might be thrown if the mark() is not called since the creation of the input stream or the bytes that are read from the input stream since the last call of mark() method is greater than the argument to mark method at the last call.In case an IOException is not thrown, then the input stream is reset to a state such that all the bytes that are read after the most recent call of mark() is supplied again to subsequent callers of the read(). This is followed by the bytes that would have at reset() call.If mark() and reset() are not supported i.e., if markSupported returns false,Calling reset() method might throw an IOException.In case an IOException is not thrown, then input stream is reset to a fixed state that depends on the particular type of the input stream. The supplied bytes to subsequent callers of the read() depend on the particular type of the input stream."
},
{
"code": null,
"e": 25375,
"s": 24785,
"text": "If mark() and reset() are supported i.e., if markSupported returns true,An IOException might be thrown if the mark() is not called since the creation of the input stream or the bytes that are read from the input stream since the last call of mark() method is greater than the argument to mark method at the last call.In case an IOException is not thrown, then the input stream is reset to a state such that all the bytes that are read after the most recent call of mark() is supplied again to subsequent callers of the read(). This is followed by the bytes that would have at reset() call."
},
{
"code": null,
"e": 25621,
"s": 25375,
"text": "An IOException might be thrown if the mark() is not called since the creation of the input stream or the bytes that are read from the input stream since the last call of mark() method is greater than the argument to mark method at the last call."
},
{
"code": null,
"e": 25894,
"s": 25621,
"text": "In case an IOException is not thrown, then the input stream is reset to a state such that all the bytes that are read after the most recent call of mark() is supplied again to subsequent callers of the read(). This is followed by the bytes that would have at reset() call."
},
{
"code": null,
"e": 26266,
"s": 25894,
"text": "If mark() and reset() are not supported i.e., if markSupported returns false,Calling reset() method might throw an IOException.In case an IOException is not thrown, then input stream is reset to a fixed state that depends on the particular type of the input stream. The supplied bytes to subsequent callers of the read() depend on the particular type of the input stream."
},
{
"code": null,
"e": 26317,
"s": 26266,
"text": "Calling reset() method might throw an IOException."
},
{
"code": null,
"e": 26562,
"s": 26317,
"text": "In case an IOException is not thrown, then input stream is reset to a fixed state that depends on the particular type of the input stream. The supplied bytes to subsequent callers of the read() depend on the particular type of the input stream."
},
{
"code": null,
"e": 26570,
"s": 26562,
"text": "Syntax:"
},
{
"code": null,
"e": 26590,
"s": 26570,
"text": "public void reset()"
},
{
"code": null,
"e": 26660,
"s": 26590,
"text": "Overrides: The method overrides the reset class in FilterInputStream."
},
{
"code": null,
"e": 26715,
"s": 26660,
"text": "Parameters: This method does not accept any parameter."
},
{
"code": null,
"e": 26768,
"s": 26715,
"text": "Return value: This method does not return any value."
},
{
"code": null,
"e": 26961,
"s": 26768,
"text": "Exception: This method throws IOException if this stream has not been marked or mark has been invalidated or input stream has been closed by invoking the close() method or an I/O error occurs."
},
{
"code": null,
"e": 27047,
"s": 26961,
"text": "Below programs illustrates reset() method in BufferedInputStream class in IO package:"
},
{
"code": null,
"e": 27102,
"s": 27047,
"text": "Program 1: Assume the existence of file “c:/demo.txt”."
},
{
"code": "// Java program to illustrate// BufferedInputStream reset() methodimport java.io.*;public class GFG { public static void main(String[] args) { // Create input stream 'demo.txt' // for reading containing text \"GEEKS\" FileInputStream inputStream = new FileInputStream( \"c:/demo.txt\"); // Convert inputStream to // bufferedInputStream BufferedInputStream buffInputStr = new BufferedInputStream( inputStream); // Read and print characters one by one System.out.println( \"Char : \" + (char)buffInputStr.read()); System.out.println( \"Char : \" + (char)buffInputStr.read()); System.out.println( \"Char : \" + (char)buffInputStr.read()); // Mark is set on the input stream buffInputStr.mark(0); System.out.println( \"Char : \" + (char)buffInputStr.read()); System.out.println( \"reset() called\"); // Reset() is invoked buffInputStr.reset(); // Read and print characters System.out.println( \"Char : \" + (char)buffInputStr.read()); System.out.println( \"Char : \" + (char)buffInputStr.read()); }}",
"e": 28433,
"s": 27102,
"text": null
},
{
"code": null,
"e": 28488,
"s": 28433,
"text": "Program 2: Assume the existence of file “c:/demo.txt”."
},
{
"code": "// Java program to illustrate// BufferedInputStream reset() methodimport java.io.*;public class GFG { public static void main(String[] args) { // Create input stream 'demo.txt' // for reading containing text // \"GEEKSFORGEEKS\" FileInputStream inputStream = new FileInputStream( \"c:/demo.txt\"); // Convert inputStream to // bufferedInputStream BufferedInputStream buffInputStr = new BufferedInputStream( inputStream); // Read and print characters one by one System.out.println( \"Char : \" + (char)buffInputStr.read()); System.out.println( \"Char : \" + (char)buffInputStr.read()); System.out.println( \"Char : \" + (char)buffInputStr.read()); System.out.println( \"Char : \" + (char)buffInputStr.read()); // Mark is set on the input stream buffInputStr.mark(0); System.out.println( \"Char : \" + (char)buffInputStr.read()); System.out.println( \"reset() called\"); // Reset() is invoked buffInputStr.reset(); // Read and print characters System.out.println( \"Char : \" + (char)buffInputStr.read()); System.out.println( \"Char : \" + (char)buffInputStr.read()); System.out.println( \"Char : \" + (char)buffInputStr.read()); System.out.println( \"Char : \" + (char)buffInputStr.read()); }}",
"e": 30104,
"s": 28488,
"text": null
},
{
"code": null,
"e": 30199,
"s": 30104,
"text": "References:https://docs.oracle.com/javase/10/docs/api/java/io/BufferedInputStream.html#reset()"
},
{
"code": null,
"e": 30214,
"s": 30199,
"text": "Java-Functions"
},
{
"code": null,
"e": 30230,
"s": 30214,
"text": "Java-IO package"
},
{
"code": null,
"e": 30235,
"s": 30230,
"text": "Java"
},
{
"code": null,
"e": 30240,
"s": 30235,
"text": "Java"
},
{
"code": null,
"e": 30338,
"s": 30240,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30347,
"s": 30338,
"text": "Comments"
},
{
"code": null,
"e": 30360,
"s": 30347,
"text": "Old Comments"
},
{
"code": null,
"e": 30390,
"s": 30360,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 30405,
"s": 30390,
"text": "Stream In Java"
},
{
"code": null,
"e": 30426,
"s": 30405,
"text": "Constructors in Java"
},
{
"code": null,
"e": 30472,
"s": 30426,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 30491,
"s": 30472,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 30508,
"s": 30491,
"text": "Generics in Java"
},
{
"code": null,
"e": 30551,
"s": 30508,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 30567,
"s": 30551,
"text": "Strings in Java"
},
{
"code": null,
"e": 30616,
"s": 30567,
"text": "How to remove an element from ArrayList in Java?"
}
] |
Python IF...ELIF...ELSE Statements
|
An else statement can be combined with an if statement. An else statement contains the block of code that executes if the conditional expression in the if statement resolves to 0 or a FALSE value.
The else statement is an optional statement and there could be at most only one else statement following if.
The syntax of the if...else statement is −
if expression:
statement(s)
else:
statement(s)
#!/usr/bin/python
var1 = 100
if var1:
print "1 - Got a true expression value"
print var1
else:
print "1 - Got a false expression value"
print var1
var2 = 0
if var2:
print "2 - Got a true expression value"
print var2
else:
print "2 - Got a false expression value"
print var2
print "Good bye!"
When the above code is executed, it produces the following result −
1 - Got a true expression value
100
2 - Got a false expression value
0
Good bye!
The elif statement allows you to check multiple expressions for TRUE and execute a block of code as soon as one of the conditions evaluates to TRUE.
Similar to the else, the elif statement is optional. However, unlike else, for which there can be at most one statement, there can be an arbitrary number of elif statements following an if.
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
Core Python does not provide switch or case statements as in other languages, but we can use if..elif...statements to simulate switch case as follows −
#!/usr/bin/python
var = 100
if var == 200:
print "1 - Got a true expression value"
print var
elif var == 150:
print "2 - Got a true expression value"
print var
elif var == 100:
print "3 - Got a true expression value"
print var
else:
print "4 - Got a false expression value"
print var
print "Good bye!"
When the above code is executed, it produces the following result −
3 - Got a true expression value
100
Good bye!
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": 2441,
"s": 2244,
"text": "An else statement can be combined with an if statement. An else statement contains the block of code that executes if the conditional expression in the if statement resolves to 0 or a FALSE value."
},
{
"code": null,
"e": 2550,
"s": 2441,
"text": "The else statement is an optional statement and there could be at most only one else statement following if."
},
{
"code": null,
"e": 2593,
"s": 2550,
"text": "The syntax of the if...else statement is −"
},
{
"code": null,
"e": 2647,
"s": 2593,
"text": "if expression:\n statement(s)\nelse:\n statement(s)\n"
},
{
"code": null,
"e": 2966,
"s": 2647,
"text": "#!/usr/bin/python\n\nvar1 = 100\nif var1:\n print \"1 - Got a true expression value\"\n print var1\nelse:\n print \"1 - Got a false expression value\"\n print var1\n\nvar2 = 0\nif var2:\n print \"2 - Got a true expression value\"\n print var2\nelse:\n print \"2 - Got a false expression value\"\n print var2\n\nprint \"Good bye!\""
},
{
"code": null,
"e": 3034,
"s": 2966,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 3116,
"s": 3034,
"text": "1 - Got a true expression value\n100\n2 - Got a false expression value\n0\nGood bye!\n"
},
{
"code": null,
"e": 3265,
"s": 3116,
"text": "The elif statement allows you to check multiple expressions for TRUE and execute a block of code as soon as one of the conditions evaluates to TRUE."
},
{
"code": null,
"e": 3455,
"s": 3265,
"text": "Similar to the else, the elif statement is optional. However, unlike else, for which there can be at most one statement, there can be an arbitrary number of elif statements following an if."
},
{
"code": null,
"e": 3578,
"s": 3455,
"text": "if expression1:\n statement(s)\nelif expression2:\n statement(s)\nelif expression3:\n statement(s)\nelse:\n statement(s)\n"
},
{
"code": null,
"e": 3730,
"s": 3578,
"text": "Core Python does not provide switch or case statements as in other languages, but we can use if..elif...statements to simulate switch case as follows −"
},
{
"code": null,
"e": 4058,
"s": 3730,
"text": "#!/usr/bin/python\n\nvar = 100\nif var == 200:\n print \"1 - Got a true expression value\"\n print var\nelif var == 150:\n print \"2 - Got a true expression value\"\n print var\nelif var == 100:\n print \"3 - Got a true expression value\"\n print var\nelse:\n print \"4 - Got a false expression value\"\n print var\n\nprint \"Good bye!\""
},
{
"code": null,
"e": 4126,
"s": 4058,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 4173,
"s": 4126,
"text": "3 - Got a true expression value\n100\nGood bye!\n"
},
{
"code": null,
"e": 4210,
"s": 4173,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4226,
"s": 4210,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4259,
"s": 4226,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 4278,
"s": 4259,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4313,
"s": 4278,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 4335,
"s": 4313,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 4369,
"s": 4335,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 4397,
"s": 4369,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4432,
"s": 4397,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 4446,
"s": 4432,
"text": " Lets Kode It"
},
{
"code": null,
"e": 4479,
"s": 4446,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4496,
"s": 4479,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 4503,
"s": 4496,
"text": " Print"
},
{
"code": null,
"e": 4514,
"s": 4503,
"text": " Add Notes"
}
] |
How to remove object from array in MongoDB?
|
You can use $pull operator to remove the object from an array in MongoDB. To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.removeObjectFromArrayDemo.insertOne(
... {
...
... "StudentName": "John",
... "StudentAcademicProjectDetails":
... [{
... "StudentProjectId": 101,
... "StudentProjectName": "Pig Dice Game"
... },
... {
... "StudentProjectId": 110,
... "StudentProjectName": "Library Management System"
... },
...
... {
... "StudentProjectId": 120,
... "StudentProjectName": "Phonebook Management System"
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8ad13d6cea1f28b7aa0817")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.removeObjectFromArrayDemo.find().pretty();
The following is the output −
{
"_id" : ObjectId("5c8ad13d6cea1f28b7aa0817"),
"StudentName" : "John",
"StudentAcademicProjectDetails" : [
{
"StudentProjectId" : 101,
"StudentProjectName" : "Pig Dice Game"
},
{
"StudentProjectId" : 110,
"StudentProjectName" : "Library Management System"
},
{
"StudentProjectId" : 120,
"StudentProjectName" : "Phonebook Management System"
}
]
}
Here is the query to remove the object from an array in MongoDB −
> db.removeObjectFromArrayDemo.update(
... {'_id': ObjectId("5c8ad13d6cea1f28b7aa0817")},
... { $pull: { "StudentAcademicProjectDetails" : { StudentProjectId: 101 } } },
... false,
... true
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us check the documents from collection to check the object has been removed from an array or not. The query is as follows −
> db.removeObjectFromArrayDemo.find().pretty();
The following is the output −
{
"_id" : ObjectId("5c8ad13d6cea1f28b7aa0817"),
"StudentName" : "John",
"StudentAcademicProjectDetails" : [
{
"StudentProjectId" : 110,
"StudentProjectName" : "Library Management System"
},
{
"StudentProjectId" : 120,
"StudentProjectName" : "Phonebook Management System"
}
]
}
Look at the above sample output, the field “StudentProjectId” with 101 has been removed.
|
[
{
"code": null,
"e": 1274,
"s": 1062,
"text": "You can use $pull operator to remove the object from an array in MongoDB. To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −"
},
{
"code": null,
"e": 1884,
"s": 1274,
"text": "> db.removeObjectFromArrayDemo.insertOne(\n... {\n ...\n ... \"StudentName\": \"John\",\n ... \"StudentAcademicProjectDetails\":\n ... [{\n ... \"StudentProjectId\": 101,\n ... \"StudentProjectName\": \"Pig Dice Game\"\n ... },\n ... {\n ... \"StudentProjectId\": 110,\n ... \"StudentProjectName\": \"Library Management System\"\n ... },\n ...\n ... {\n ... \"StudentProjectId\": 120,\n ... \"StudentProjectName\": \"Phonebook Management System\"\n ... }\n ... ]\n ... }\n... );\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c8ad13d6cea1f28b7aa0817\")\n}"
},
{
"code": null,
"e": 1982,
"s": 1884,
"text": "Display all documents from a collection with the help of find() method. The query is as follows −"
},
{
"code": null,
"e": 2030,
"s": 1982,
"text": "> db.removeObjectFromArrayDemo.find().pretty();"
},
{
"code": null,
"e": 2060,
"s": 2030,
"text": "The following is the output −"
},
{
"code": null,
"e": 2509,
"s": 2060,
"text": "{\n \"_id\" : ObjectId(\"5c8ad13d6cea1f28b7aa0817\"),\n \"StudentName\" : \"John\",\n \"StudentAcademicProjectDetails\" : [\n {\n \"StudentProjectId\" : 101,\n \"StudentProjectName\" : \"Pig Dice Game\"\n },\n {\n \"StudentProjectId\" : 110,\n \"StudentProjectName\" : \"Library Management System\"\n },\n {\n \"StudentProjectId\" : 120,\n \"StudentProjectName\" : \"Phonebook Management System\"\n }\n ]\n}"
},
{
"code": null,
"e": 2575,
"s": 2509,
"text": "Here is the query to remove the object from an array in MongoDB −"
},
{
"code": null,
"e": 2850,
"s": 2575,
"text": "> db.removeObjectFromArrayDemo.update(\n ... {'_id': ObjectId(\"5c8ad13d6cea1f28b7aa0817\")},\n ... { $pull: { \"StudentAcademicProjectDetails\" : { StudentProjectId: 101 } } },\n ... false,\n ... true\n... );\nWriteResult({ \"nMatched\" : 1, \"nUpserted\" : 0, \"nModified\" : 1 })"
},
{
"code": null,
"e": 2978,
"s": 2850,
"text": "Let us check the documents from collection to check the object has been removed from an array or not. The query is as follows −"
},
{
"code": null,
"e": 3026,
"s": 2978,
"text": "> db.removeObjectFromArrayDemo.find().pretty();"
},
{
"code": null,
"e": 3056,
"s": 3026,
"text": "The following is the output −"
},
{
"code": null,
"e": 3405,
"s": 3056,
"text": "{\n \"_id\" : ObjectId(\"5c8ad13d6cea1f28b7aa0817\"),\n \"StudentName\" : \"John\",\n \"StudentAcademicProjectDetails\" : [\n {\n \"StudentProjectId\" : 110,\n \"StudentProjectName\" : \"Library Management System\"\n },\n {\n \"StudentProjectId\" : 120,\n \"StudentProjectName\" : \"Phonebook Management System\"\n }\n ]\n}"
},
{
"code": null,
"e": 3494,
"s": 3405,
"text": "Look at the above sample output, the field “StudentProjectId” with 101 has been removed."
}
] |
What’s the Best Pokémon Type? The Power of Metrics | by Luciano Strika | Towards Data Science
|
We all know what the best type is (It’s Psychic. Prove me wrong.), but what does the data say?
Sometimes, Data Science is about making hard choices, or earning a company tons of money. Other times though, Data Science can just be a fun hobby in a rainy weekend.
This week I’ve been very busy with a college assignment: a few classmates and I have had to code the PageRank algorithm — the one Google used to use for searches, before AI and NLP ate everything else.
PageRank is an algorithm used to get a ranking for connected parts of a system — perfect for ranking websites, its original purpose.
Based on its original task, it measures and ranks the importance or influence of many nodes (websites) that link to each other (edges).
The algorithm takes as its input a directed Graph, and returns a ranking of its nodes -along with some scorings between 0 and 1- with a few criteria:
You rank higher if more nodes link to you.
Linking to another node is less relevant if you link to more nodes.
Being linked by higher ranked nodes is better.
This is coherent with the idea that a big site, like Medium, will be linked by a lot of sources, whereas being linked by a big site (say, Facebook’s home page) also means your site’s pretty relevant. You could also use it to model relevance of scientific papers or publications (using citations as the links), or probabilities that an animal gets eaten in a given ecosystem (with a food chain as graph).
So I’d been meaning to write an article about something fun, and I had this PageRank implementation laying around... I couldn’t miss the chance.
First I got down to getting the data.
Since all I wanted to model was the type relationships, I was about to use Bulbapedia (Pokémon’s Wiki) — but then I figured someone else had probably already coded that bit. Effectively, a few seconds of search got me to this awesome link, from which I took the Python matrix of type advantages in the game. This uses the types and relationships from the 6th generation. I haven’t gotten around to playing the 7th one yet, so I didn’t mind.
Having the raw matrix already loaded in Python, I had to give it the correct format: The links in the kind of graph PageRank takes as input carry no weight — they’re binary: either you link to something or you don’t (if there are different implementations of PageRank that address this, please let me know in the comments!).
In case you haven’t played Pokémon or you’re fuzzy on the details, each type can either be neutral towards another type (most types are mutually neutral), have an advantage (does 2x the damage), a disadvantage (does 1/2 the damage) or an immunity (receives 0 damage).
The way I moved that format (4 different relationships) to a binary domain was simply doing two different graphs: one for attackers, and one for defenders. I also bunched immunity and resistance into the same category (defensive advantage, if you will) — I hope that won’t offend any hardcore fans.
There’s also another issue: PageRank doesn’t take into account sites linking to themselves, and so we can’t use data about a pokémon type being weak to itself or effective against itself. (Full disclosure: I didn’t realize this in the first draft of this article, a reader made me notice my mistake. Results have changed.)
Here are the results I got from modeling attacking types. I only linked type A to type B if type A was very effective against type B, without linking any types to themselves (since that goes againt PageRanks preconditions).
As I anticipated, Psychic came out in the top 3. Dragon had a pretty bad spot, which surprised me a lot, except one of Dragon’s advantages is being very effective against other dragons, which can’t really be captured by this algorithm. Electric type came out last, though that should be evened out by Water being the most frequent pokémon type.
Meanwhile, the results for defending types were also quite surprising:
Dragon comes out last, with Ice close on its tail. On the other hand Fighting and Bug come out on top, being some of the types with the most resistances.Even though Bug is not a very strong defensive type, it is resistant to three different types, and one of them is Fighting, which came out first on the ranking, so that kinda explains why it would be so close to the top.
(Disclaimer: in the previous draft I said Ice was resistant to Dragon, when it’s just Dragon being weak to Ice. Sorry.)
I feel like the results aren’t too intuitive though, and maybe a different model would work better. For instance, this model can’t capture a type being weak against itself, nor does it deal with how much more frequently a Water-type pokémon will appear than, say, a Dragon type one.
Here’s a link to the raw results, in case you wanna visualize them differently.
I am quite happy with my results on the attacking side, but there’s no way a ranking of defensive pokémon with Fighting on the top can be that good. So I set out to look for other metrics.
I thought maybe a simple metric of
sum (Damage modifier)*(#pokémon of that type) over every type
Could yield more intuitive results, akin to an ‘expected damage’. Let’s see what I got.
I found a redditor who kindly collected the quantity of pokémon of each type, so I am citing him as my source.
For every type, I am counting each pokémon twice if they’re weak against it, 0 if they’re immune, by half if they’re resistant, and once otherwise.
This time
Bug is the second weakest.
Grass comes out last. It came out first in the other ranking.
Rock, Ground, Ice and Flying come as the very close top-4.
Rock has done well in both attacking metrics.
It would appear even though Grass-type is stronger against many types, there are less pokémon of those types. rock seems to be consistently good though. In the future, I may look again at these numbers without considering legendary pokémon, since they can’t be used in competitions anyway.
If I do the opposite, and calculate the ‘expected damage’ a pokémon should receive based on type alone, these are the key insights:
Steel is the best defending pokémon type, probably due to its immunity to Poison and many resistances. It wins by an over 20% margin against the second type.
The worst defensive type is, ironically, Ice with a 50% more expected damage than Steel.
Ground and Rock, which are consistently good Damage dealers, come across as very bad defending types, which keeps the playground fair.
Unsurprisingly, Bug is not only a bad attacker, it is also a bad defender.
Personally, I find these rankings to be more intuitive than the first ones.
For those who want to see the entire results of this analysis, the numbers are available in this gist.
After seeing these numbers, I feel like I have a better intuition about the pokémon types. To be honest, what has surprised me the most is how fair this system is: the best pokémon by some metrics are the worst by others, and most just fall in the middle. Some of the assumptions most player make have been confirmed: Bug is not a very strong type (its lack of strong attacks would make it even weaker, if that factored into the analysis), Rock and Ground are very good glass-cannons (So keep teaching Earthquake to non-Ground types pokémon), and most types just fall in the middle. Also, Steel makes for a pretty sweet tank.
In the future, I may come back to this and do another, more granular analysis looking into the state of the current meta, or maybe looking at pokémon stats by type, especially dividing them into special tanks, physical tanks, special DPS and physical DPS.
I hope you’ve found this entertaining, and maybe even thought provoking. I will gladly receive any criticisms or ideas. What do you think about this article, or these results? What other problems do you think could be well modeled by PageRank? What other analysis do you think would be fun to do?Please let me know the answers to all that in the comments!
Follow me for more Data Science and Analytics articles, and if you liked reading this please consider supporting my writing habits.
|
[
{
"code": null,
"e": 266,
"s": 171,
"text": "We all know what the best type is (It’s Psychic. Prove me wrong.), but what does the data say?"
},
{
"code": null,
"e": 433,
"s": 266,
"text": "Sometimes, Data Science is about making hard choices, or earning a company tons of money. Other times though, Data Science can just be a fun hobby in a rainy weekend."
},
{
"code": null,
"e": 635,
"s": 433,
"text": "This week I’ve been very busy with a college assignment: a few classmates and I have had to code the PageRank algorithm — the one Google used to use for searches, before AI and NLP ate everything else."
},
{
"code": null,
"e": 768,
"s": 635,
"text": "PageRank is an algorithm used to get a ranking for connected parts of a system — perfect for ranking websites, its original purpose."
},
{
"code": null,
"e": 904,
"s": 768,
"text": "Based on its original task, it measures and ranks the importance or influence of many nodes (websites) that link to each other (edges)."
},
{
"code": null,
"e": 1054,
"s": 904,
"text": "The algorithm takes as its input a directed Graph, and returns a ranking of its nodes -along with some scorings between 0 and 1- with a few criteria:"
},
{
"code": null,
"e": 1097,
"s": 1054,
"text": "You rank higher if more nodes link to you."
},
{
"code": null,
"e": 1165,
"s": 1097,
"text": "Linking to another node is less relevant if you link to more nodes."
},
{
"code": null,
"e": 1212,
"s": 1165,
"text": "Being linked by higher ranked nodes is better."
},
{
"code": null,
"e": 1616,
"s": 1212,
"text": "This is coherent with the idea that a big site, like Medium, will be linked by a lot of sources, whereas being linked by a big site (say, Facebook’s home page) also means your site’s pretty relevant. You could also use it to model relevance of scientific papers or publications (using citations as the links), or probabilities that an animal gets eaten in a given ecosystem (with a food chain as graph)."
},
{
"code": null,
"e": 1761,
"s": 1616,
"text": "So I’d been meaning to write an article about something fun, and I had this PageRank implementation laying around... I couldn’t miss the chance."
},
{
"code": null,
"e": 1799,
"s": 1761,
"text": "First I got down to getting the data."
},
{
"code": null,
"e": 2241,
"s": 1799,
"text": "Since all I wanted to model was the type relationships, I was about to use Bulbapedia (Pokémon’s Wiki) — but then I figured someone else had probably already coded that bit. Effectively, a few seconds of search got me to this awesome link, from which I took the Python matrix of type advantages in the game. This uses the types and relationships from the 6th generation. I haven’t gotten around to playing the 7th one yet, so I didn’t mind."
},
{
"code": null,
"e": 2566,
"s": 2241,
"text": "Having the raw matrix already loaded in Python, I had to give it the correct format: The links in the kind of graph PageRank takes as input carry no weight — they’re binary: either you link to something or you don’t (if there are different implementations of PageRank that address this, please let me know in the comments!)."
},
{
"code": null,
"e": 2835,
"s": 2566,
"text": "In case you haven’t played Pokémon or you’re fuzzy on the details, each type can either be neutral towards another type (most types are mutually neutral), have an advantage (does 2x the damage), a disadvantage (does 1/2 the damage) or an immunity (receives 0 damage)."
},
{
"code": null,
"e": 3134,
"s": 2835,
"text": "The way I moved that format (4 different relationships) to a binary domain was simply doing two different graphs: one for attackers, and one for defenders. I also bunched immunity and resistance into the same category (defensive advantage, if you will) — I hope that won’t offend any hardcore fans."
},
{
"code": null,
"e": 3458,
"s": 3134,
"text": "There’s also another issue: PageRank doesn’t take into account sites linking to themselves, and so we can’t use data about a pokémon type being weak to itself or effective against itself. (Full disclosure: I didn’t realize this in the first draft of this article, a reader made me notice my mistake. Results have changed.)"
},
{
"code": null,
"e": 3682,
"s": 3458,
"text": "Here are the results I got from modeling attacking types. I only linked type A to type B if type A was very effective against type B, without linking any types to themselves (since that goes againt PageRanks preconditions)."
},
{
"code": null,
"e": 4028,
"s": 3682,
"text": "As I anticipated, Psychic came out in the top 3. Dragon had a pretty bad spot, which surprised me a lot, except one of Dragon’s advantages is being very effective against other dragons, which can’t really be captured by this algorithm. Electric type came out last, though that should be evened out by Water being the most frequent pokémon type."
},
{
"code": null,
"e": 4099,
"s": 4028,
"text": "Meanwhile, the results for defending types were also quite surprising:"
},
{
"code": null,
"e": 4473,
"s": 4099,
"text": "Dragon comes out last, with Ice close on its tail. On the other hand Fighting and Bug come out on top, being some of the types with the most resistances.Even though Bug is not a very strong defensive type, it is resistant to three different types, and one of them is Fighting, which came out first on the ranking, so that kinda explains why it would be so close to the top."
},
{
"code": null,
"e": 4593,
"s": 4473,
"text": "(Disclaimer: in the previous draft I said Ice was resistant to Dragon, when it’s just Dragon being weak to Ice. Sorry.)"
},
{
"code": null,
"e": 4877,
"s": 4593,
"text": "I feel like the results aren’t too intuitive though, and maybe a different model would work better. For instance, this model can’t capture a type being weak against itself, nor does it deal with how much more frequently a Water-type pokémon will appear than, say, a Dragon type one."
},
{
"code": null,
"e": 4957,
"s": 4877,
"text": "Here’s a link to the raw results, in case you wanna visualize them differently."
},
{
"code": null,
"e": 5147,
"s": 4957,
"text": "I am quite happy with my results on the attacking side, but there’s no way a ranking of defensive pokémon with Fighting on the top can be that good. So I set out to look for other metrics."
},
{
"code": null,
"e": 5182,
"s": 5147,
"text": "I thought maybe a simple metric of"
},
{
"code": null,
"e": 5245,
"s": 5182,
"text": "sum (Damage modifier)*(#pokémon of that type) over every type"
},
{
"code": null,
"e": 5333,
"s": 5245,
"text": "Could yield more intuitive results, akin to an ‘expected damage’. Let’s see what I got."
},
{
"code": null,
"e": 5445,
"s": 5333,
"text": "I found a redditor who kindly collected the quantity of pokémon of each type, so I am citing him as my source."
},
{
"code": null,
"e": 5594,
"s": 5445,
"text": "For every type, I am counting each pokémon twice if they’re weak against it, 0 if they’re immune, by half if they’re resistant, and once otherwise."
},
{
"code": null,
"e": 5604,
"s": 5594,
"text": "This time"
},
{
"code": null,
"e": 5631,
"s": 5604,
"text": "Bug is the second weakest."
},
{
"code": null,
"e": 5693,
"s": 5631,
"text": "Grass comes out last. It came out first in the other ranking."
},
{
"code": null,
"e": 5752,
"s": 5693,
"text": "Rock, Ground, Ice and Flying come as the very close top-4."
},
{
"code": null,
"e": 5798,
"s": 5752,
"text": "Rock has done well in both attacking metrics."
},
{
"code": null,
"e": 6090,
"s": 5798,
"text": "It would appear even though Grass-type is stronger against many types, there are less pokémon of those types. rock seems to be consistently good though. In the future, I may look again at these numbers without considering legendary pokémon, since they can’t be used in competitions anyway."
},
{
"code": null,
"e": 6223,
"s": 6090,
"text": "If I do the opposite, and calculate the ‘expected damage’ a pokémon should receive based on type alone, these are the key insights:"
},
{
"code": null,
"e": 6382,
"s": 6223,
"text": "Steel is the best defending pokémon type, probably due to its immunity to Poison and many resistances. It wins by an over 20% margin against the second type."
},
{
"code": null,
"e": 6471,
"s": 6382,
"text": "The worst defensive type is, ironically, Ice with a 50% more expected damage than Steel."
},
{
"code": null,
"e": 6606,
"s": 6471,
"text": "Ground and Rock, which are consistently good Damage dealers, come across as very bad defending types, which keeps the playground fair."
},
{
"code": null,
"e": 6681,
"s": 6606,
"text": "Unsurprisingly, Bug is not only a bad attacker, it is also a bad defender."
},
{
"code": null,
"e": 6757,
"s": 6681,
"text": "Personally, I find these rankings to be more intuitive than the first ones."
},
{
"code": null,
"e": 6860,
"s": 6757,
"text": "For those who want to see the entire results of this analysis, the numbers are available in this gist."
},
{
"code": null,
"e": 7489,
"s": 6860,
"text": "After seeing these numbers, I feel like I have a better intuition about the pokémon types. To be honest, what has surprised me the most is how fair this system is: the best pokémon by some metrics are the worst by others, and most just fall in the middle. Some of the assumptions most player make have been confirmed: Bug is not a very strong type (its lack of strong attacks would make it even weaker, if that factored into the analysis), Rock and Ground are very good glass-cannons (So keep teaching Earthquake to non-Ground types pokémon), and most types just fall in the middle. Also, Steel makes for a pretty sweet tank."
},
{
"code": null,
"e": 7746,
"s": 7489,
"text": "In the future, I may come back to this and do another, more granular analysis looking into the state of the current meta, or maybe looking at pokémon stats by type, especially dividing them into special tanks, physical tanks, special DPS and physical DPS."
},
{
"code": null,
"e": 8102,
"s": 7746,
"text": "I hope you’ve found this entertaining, and maybe even thought provoking. I will gladly receive any criticisms or ideas. What do you think about this article, or these results? What other problems do you think could be well modeled by PageRank? What other analysis do you think would be fun to do?Please let me know the answers to all that in the comments!"
}
] |
Use pre-trained Huggingface models in TensorFlow Serving | by Luis Duarte | Towards Data Science
|
HuggingFace simplifies NLP to the point that with a few lines of code you have a complete pipeline capable to perform tasks from sentiment analysis to text generation. Being a Hub for pre-trained models and with its open-source framework Transformers, a lot of the hard work that we used to do is simplified. This allows us to write applications capable of solving complex NLP tasks, but with the downside that we don’t know what is happening behind the curtains. Despite this amazing simplification that HuggingFace and Transformers perform we might want some abstraction from all that code and just simply use one of many available pre-trained models. In this post, we will learn how we can use one of many pre-trained models with TensorFlow Serving, a popular service to put machine learning models into production.
I will use this Distilbert pre-trained model for Sentiment Analysis which will predict if a given text is positive or negative. Unfortunately, Transformers doesn’t have a direct export functionality to TensorFlow Serve so we will have to do a bit of working around to achieve our goals. First, we need to install Tensorflow, Transformers and NumPy libraries.
pip install transformerspip install tensorflowpip install numpy
In this first section of code, we will load both the model and the tokenizer from Transformers and then save it on disk with the correct format to use in TensorFlow Serve.
from transformers import TFAutoModelForSequenceClassificationimport tensorflow as tfMAX_SEQ_LEN = 100model = TFAutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased-finetuned-sst-2-english")callable = tf.function(model.call)concrete_function = callable.get_concrete_function([tf.TensorSpec([None, MAX_SEQ_LEN], tf.int32, name="input_ids"), tf.TensorSpec([None, MAX_SEQ_LEN], tf.int32, name="attention_mask")])model.save('saved_model/distilbert/1', signatures=concrete_function)
First of all, we load the model with TFAutoModelForSequenceClassification. One crucial aspect in loading transformers models is choosing the right Class. Since we are using a pre-trained model for Sentiment Analysis we will use the loader for TensorFlow (that’s why we import the TFAutoModel class) for Sequence Classification. If you are unsure what Class to load just check the model card or “Use in transformers” info on Huggingface model page for which class to use.
In the code snippet, we declared a signature function that is necessary to use with TensorFlow Serve. This function is necessary for declaring the input shape of our data to the servable model in TF Serve, which is defined by the variable MAX_SEQ_LEN. In this case, I have defined that the model will accept two inputs, two lists with a size of 200, for the input_ids (the ids that we obtain from the tokenizer) and the attention_mask (used if the input sequence length is smaller than the max input sequence length). It is also important to remember the name we declare for each input because it’s the parameter we will later define in the HTTP request to send to our model. After executing these few lines we should have a new directory with the following files on our working directory:
saved_models
distilbert
1
assets
saved_model.pb
variables
variables.data-00000-of-00001
variables.index
distilbert
1
assets
saved_model.pb
variables
variables.data-00000-of-00001
variables.index
1
assets
saved_model.pb
variables
variables.data-00000-of-00001
variables.index
assets
saved_model.pb
variables
variables.data-00000-of-00001
variables.index
variables.data-00000-of-00001
variables.index
If you haven’t installed TensorFlow Serve (I recommend using it with Docker) do it now. After we have installed we can pull the image from Docker and start running our service with the Distilbert model loaded with the following command:
docker run -p 8501:8501 --mount type=bind, source=/PATH_TO_YOUR_DIRECTORY/saved_models/distilbert, target=/models/distilbert -e MODEL_NAME=distilbert -t tensorflow/serving
This will cause TensorFlow Serve to load Distilbert (The model files must be under a directory named with a number or else TF Serve won’t load the model) in port 8501 which we can request by HTTP. In the next section, I will show how we can make predictions for our loaded model.
import requestsfrom transformers import AutoTokenizer, AutoConfigtokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased-finetuned-sst-2-english")text = "I like you. I love you"encoded_input = tokenizer(text, pad_to_max_length=MAX_SEQ_LEN, max_length=MAX_SEQ_LEN)#TF Serve endpointurl = "http://localhost:8501/v1/models/distilbert:predict"payload={"instances": [{"input_ids": encoded_input['input_ids'], "attention_mask": encoded_input['attention_mask']}]}print(payload)>> { "input_ids": [101, 1045, 2066, 2017, 1012, 1045, 2293, 2017, 102, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "attention_mask": [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] }headers = { 'Content-Type': 'application/json'}response = requests.request("POST", url, headers=headers, data=json.dumps(payload))print(json.loads(response.text)['predictions'])>>[[-4.2159214, 4.58923769]]
We start by calling the model tokenizer from transformers to convert our input text into a list of ids and its corresponding attention mask, both with padding, to obtain the necessary format to send to our loaded model. After tokenizing we perform a POST request to TensorFlow Serving with the correct payload where we obtain the presented values. But wait, isn’t the model suppose to classify the sentiment in our text? Well, we are missing one last step, applying the softmax function to our result vector.
import numpy as npdef softmax(x): e_x = np.exp(x - np.max(x)) return e_x / e_x.sum(axis=0)print(softmax(json.loads(response.text)['predictions'][0]))>>[0.0001 0.9999]
The resulting vector is the probability of the input text to be negative or positive. In this case, a probability of 0.0001 to be negative and 0.9999 to belong to the positive class. If we compare the result with the output from loading the pipeline with transformers we can see both are the same.
Concluding this post we have used one of many huggingface pre-trained models and loaded it up on TensorFlow Serve so we can make HTTP requests and easily scale these models into production. We also learned how we can make requests to our loaded model with the model tokenizer and how we need to apply the softmax function to our results to obtain the desired values. In my next post, I will show how we can abstract ourselves from the transformers library completely by writing our tokenizer and use it to make requests to our loaded models. Like always feel free to comment with suggestions or improvements and hope that this post helped you achieve your goals.
|
[
{
"code": null,
"e": 991,
"s": 172,
"text": "HuggingFace simplifies NLP to the point that with a few lines of code you have a complete pipeline capable to perform tasks from sentiment analysis to text generation. Being a Hub for pre-trained models and with its open-source framework Transformers, a lot of the hard work that we used to do is simplified. This allows us to write applications capable of solving complex NLP tasks, but with the downside that we don’t know what is happening behind the curtains. Despite this amazing simplification that HuggingFace and Transformers perform we might want some abstraction from all that code and just simply use one of many available pre-trained models. In this post, we will learn how we can use one of many pre-trained models with TensorFlow Serving, a popular service to put machine learning models into production."
},
{
"code": null,
"e": 1350,
"s": 991,
"text": "I will use this Distilbert pre-trained model for Sentiment Analysis which will predict if a given text is positive or negative. Unfortunately, Transformers doesn’t have a direct export functionality to TensorFlow Serve so we will have to do a bit of working around to achieve our goals. First, we need to install Tensorflow, Transformers and NumPy libraries."
},
{
"code": null,
"e": 1414,
"s": 1350,
"text": "pip install transformerspip install tensorflowpip install numpy"
},
{
"code": null,
"e": 1586,
"s": 1414,
"text": "In this first section of code, we will load both the model and the tokenizer from Transformers and then save it on disk with the correct format to use in TensorFlow Serve."
},
{
"code": null,
"e": 2086,
"s": 1586,
"text": "from transformers import TFAutoModelForSequenceClassificationimport tensorflow as tfMAX_SEQ_LEN = 100model = TFAutoModelForSequenceClassification.from_pretrained(\"distilbert-base-uncased-finetuned-sst-2-english\")callable = tf.function(model.call)concrete_function = callable.get_concrete_function([tf.TensorSpec([None, MAX_SEQ_LEN], tf.int32, name=\"input_ids\"), tf.TensorSpec([None, MAX_SEQ_LEN], tf.int32, name=\"attention_mask\")])model.save('saved_model/distilbert/1', signatures=concrete_function)"
},
{
"code": null,
"e": 2557,
"s": 2086,
"text": "First of all, we load the model with TFAutoModelForSequenceClassification. One crucial aspect in loading transformers models is choosing the right Class. Since we are using a pre-trained model for Sentiment Analysis we will use the loader for TensorFlow (that’s why we import the TFAutoModel class) for Sequence Classification. If you are unsure what Class to load just check the model card or “Use in transformers” info on Huggingface model page for which class to use."
},
{
"code": null,
"e": 3347,
"s": 2557,
"text": "In the code snippet, we declared a signature function that is necessary to use with TensorFlow Serve. This function is necessary for declaring the input shape of our data to the servable model in TF Serve, which is defined by the variable MAX_SEQ_LEN. In this case, I have defined that the model will accept two inputs, two lists with a size of 200, for the input_ids (the ids that we obtain from the tokenizer) and the attention_mask (used if the input sequence length is smaller than the max input sequence length). It is also important to remember the name we declare for each input because it’s the parameter we will later define in the HTTP request to send to our model. After executing these few lines we should have a new directory with the following files on our working directory:"
},
{
"code": null,
"e": 3463,
"s": 3347,
"text": "saved_models\n\ndistilbert\n\n1\n\nassets\nsaved_model.pb\nvariables\n\nvariables.data-00000-of-00001\nvariables.index\n\n\n\n\n\n\n\n"
},
{
"code": null,
"e": 3563,
"s": 3463,
"text": "distilbert\n\n1\n\nassets\nsaved_model.pb\nvariables\n\nvariables.data-00000-of-00001\nvariables.index\n\n\n\n\n\n"
},
{
"code": null,
"e": 3649,
"s": 3563,
"text": "1\n\nassets\nsaved_model.pb\nvariables\n\nvariables.data-00000-of-00001\nvariables.index\n\n\n\n"
},
{
"code": null,
"e": 3656,
"s": 3649,
"text": "assets"
},
{
"code": null,
"e": 3671,
"s": 3656,
"text": "saved_model.pb"
},
{
"code": null,
"e": 3730,
"s": 3671,
"text": "variables\n\nvariables.data-00000-of-00001\nvariables.index\n\n"
},
{
"code": null,
"e": 3760,
"s": 3730,
"text": "variables.data-00000-of-00001"
},
{
"code": null,
"e": 3776,
"s": 3760,
"text": "variables.index"
},
{
"code": null,
"e": 4013,
"s": 3776,
"text": "If you haven’t installed TensorFlow Serve (I recommend using it with Docker) do it now. After we have installed we can pull the image from Docker and start running our service with the Distilbert model loaded with the following command:"
},
{
"code": null,
"e": 4185,
"s": 4013,
"text": "docker run -p 8501:8501 --mount type=bind, source=/PATH_TO_YOUR_DIRECTORY/saved_models/distilbert, target=/models/distilbert -e MODEL_NAME=distilbert -t tensorflow/serving"
},
{
"code": null,
"e": 4465,
"s": 4185,
"text": "This will cause TensorFlow Serve to load Distilbert (The model files must be under a directory named with a number or else TF Serve won’t load the model) in port 8501 which we can request by HTTP. In the next section, I will show how we can make predictions for our loaded model."
},
{
"code": null,
"e": 5819,
"s": 4465,
"text": "import requestsfrom transformers import AutoTokenizer, AutoConfigtokenizer = AutoTokenizer.from_pretrained(\"distilbert-base-uncased-finetuned-sst-2-english\")text = \"I like you. I love you\"encoded_input = tokenizer(text, pad_to_max_length=MAX_SEQ_LEN, max_length=MAX_SEQ_LEN)#TF Serve endpointurl = \"http://localhost:8501/v1/models/distilbert:predict\"payload={\"instances\": [{\"input_ids\": encoded_input['input_ids'], \"attention_mask\": encoded_input['attention_mask']}]}print(payload)>> { \"input_ids\": [101, 1045, 2066, 2017, 1012, 1045, 2293, 2017, 102, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], \"attention_mask\": [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] }headers = { 'Content-Type': 'application/json'}response = requests.request(\"POST\", url, headers=headers, data=json.dumps(payload))print(json.loads(response.text)['predictions'])>>[[-4.2159214, 4.58923769]]"
},
{
"code": null,
"e": 6328,
"s": 5819,
"text": "We start by calling the model tokenizer from transformers to convert our input text into a list of ids and its corresponding attention mask, both with padding, to obtain the necessary format to send to our loaded model. After tokenizing we perform a POST request to TensorFlow Serving with the correct payload where we obtain the presented values. But wait, isn’t the model suppose to classify the sentiment in our text? Well, we are missing one last step, applying the softmax function to our result vector."
},
{
"code": null,
"e": 6501,
"s": 6328,
"text": "import numpy as npdef softmax(x): e_x = np.exp(x - np.max(x)) return e_x / e_x.sum(axis=0)print(softmax(json.loads(response.text)['predictions'][0]))>>[0.0001 0.9999]"
},
{
"code": null,
"e": 6799,
"s": 6501,
"text": "The resulting vector is the probability of the input text to be negative or positive. In this case, a probability of 0.0001 to be negative and 0.9999 to belong to the positive class. If we compare the result with the output from loading the pipeline with transformers we can see both are the same."
}
] |
Dictionary elements() Method in Java with Examples - GeeksforGeeks
|
27 Dec, 2018
The keys() method of Dictionary class in Java is used to get the enumeration of the values present in the dictionary.
Syntax:
Enumeration enu = DICTIONARY.elements()
Parameters: The method does not take any parameters.
Return value: The method returns an enumeration of the values of the Dictionary.
Below programs are used to illustrate the working of the java.util.Dictionary.elements() method:Program 1:
// Java code to illustrate the elements() methodimport java.util.*; public class Dictionary_Demo { public static void main(String[] args) { // Creating an empty Dictionary Dictionary<Integer, String> dict = new Hashtable<Integer, String>(); // Inserting elements into the Dictionary dict.put(10, "Geeks"); dict.put(15, "4"); dict.put(20, "Geeks"); dict.put(25, "Welcomes"); dict.put(30, "You"); // Displaying the Dictionary System.out.println("The Dictionary is: " + dict); // Creating an empty enumeration to store Enumeration enu = dict.elements(); System.out.println("The enumeration of values are:"); // Displaying the Enumeration while (enu.hasMoreElements()) { System.out.println(enu.nextElement()); } }}
The Dictionary is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes}
The enumeration of values are:
Geeks
Geeks
You
4
Welcomes
Program 2:
// Java code to illustrate the elements() methodimport java.util.*; public class Dictionary_Demo { public static void main(String[] args) { // Creating an empty Dictionary Dictionary<String, Integer> dict = new Hashtable<String, Integer>(); // Inserting elements into the table dict.put("Geeks", 10); dict.put("4", 15); dict.put("Geeks", 20); dict.put("Welcomes", 25); dict.put("You", 30); // Displaying the Dictionary System.out.println("The Dictionary is: " + dict); // Creating an empty enumeration to store Enumeration enu = dict.elements(); System.out.println("The enumeration of values are:"); // Displaying the Enumeration while (enu.hasMoreElements()) { System.out.println(enu.nextElement()); } }}
The Dictionary is: {You=30, Welcomes=25, 4=15, Geeks=20}
The enumeration of values are:
30
25
15
20
Java - util package
Java-Collections
Java-Functions
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways of Reading a text file in Java
Stream In Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
HashMap get() Method in Java
Comparator Interface in Java with Examples
Strings in Java
StringBuilder Class in Java with Examples
|
[
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n27 Dec, 2018"
},
{
"code": null,
"e": 24066,
"s": 23948,
"text": "The keys() method of Dictionary class in Java is used to get the enumeration of the values present in the dictionary."
},
{
"code": null,
"e": 24074,
"s": 24066,
"text": "Syntax:"
},
{
"code": null,
"e": 24114,
"s": 24074,
"text": "Enumeration enu = DICTIONARY.elements()"
},
{
"code": null,
"e": 24167,
"s": 24114,
"text": "Parameters: The method does not take any parameters."
},
{
"code": null,
"e": 24248,
"s": 24167,
"text": "Return value: The method returns an enumeration of the values of the Dictionary."
},
{
"code": null,
"e": 24355,
"s": 24248,
"text": "Below programs are used to illustrate the working of the java.util.Dictionary.elements() method:Program 1:"
},
{
"code": "// Java code to illustrate the elements() methodimport java.util.*; public class Dictionary_Demo { public static void main(String[] args) { // Creating an empty Dictionary Dictionary<Integer, String> dict = new Hashtable<Integer, String>(); // Inserting elements into the Dictionary dict.put(10, \"Geeks\"); dict.put(15, \"4\"); dict.put(20, \"Geeks\"); dict.put(25, \"Welcomes\"); dict.put(30, \"You\"); // Displaying the Dictionary System.out.println(\"The Dictionary is: \" + dict); // Creating an empty enumeration to store Enumeration enu = dict.elements(); System.out.println(\"The enumeration of values are:\"); // Displaying the Enumeration while (enu.hasMoreElements()) { System.out.println(enu.nextElement()); } }}",
"e": 25222,
"s": 24355,
"text": null
},
{
"code": null,
"e": 25348,
"s": 25222,
"text": "The Dictionary is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes}\nThe enumeration of values are:\nGeeks\nGeeks\nYou\n4\nWelcomes\n"
},
{
"code": null,
"e": 25359,
"s": 25348,
"text": "Program 2:"
},
{
"code": "// Java code to illustrate the elements() methodimport java.util.*; public class Dictionary_Demo { public static void main(String[] args) { // Creating an empty Dictionary Dictionary<String, Integer> dict = new Hashtable<String, Integer>(); // Inserting elements into the table dict.put(\"Geeks\", 10); dict.put(\"4\", 15); dict.put(\"Geeks\", 20); dict.put(\"Welcomes\", 25); dict.put(\"You\", 30); // Displaying the Dictionary System.out.println(\"The Dictionary is: \" + dict); // Creating an empty enumeration to store Enumeration enu = dict.elements(); System.out.println(\"The enumeration of values are:\"); // Displaying the Enumeration while (enu.hasMoreElements()) { System.out.println(enu.nextElement()); } }}",
"e": 26221,
"s": 25359,
"text": null
},
{
"code": null,
"e": 26322,
"s": 26221,
"text": "The Dictionary is: {You=30, Welcomes=25, 4=15, Geeks=20}\nThe enumeration of values are:\n30\n25\n15\n20\n"
},
{
"code": null,
"e": 26342,
"s": 26322,
"text": "Java - util package"
},
{
"code": null,
"e": 26359,
"s": 26342,
"text": "Java-Collections"
},
{
"code": null,
"e": 26374,
"s": 26359,
"text": "Java-Functions"
},
{
"code": null,
"e": 26379,
"s": 26374,
"text": "Java"
},
{
"code": null,
"e": 26384,
"s": 26379,
"text": "Java"
},
{
"code": null,
"e": 26401,
"s": 26384,
"text": "Java-Collections"
},
{
"code": null,
"e": 26499,
"s": 26401,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26545,
"s": 26499,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 26560,
"s": 26545,
"text": "Stream In Java"
},
{
"code": null,
"e": 26581,
"s": 26560,
"text": "Constructors in Java"
},
{
"code": null,
"e": 26600,
"s": 26581,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 26617,
"s": 26600,
"text": "Generics in Java"
},
{
"code": null,
"e": 26647,
"s": 26617,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 26676,
"s": 26647,
"text": "HashMap get() Method in Java"
},
{
"code": null,
"e": 26719,
"s": 26676,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 26735,
"s": 26719,
"text": "Strings in Java"
}
] |
VueJS - Reactive Interface
|
VueJS provides options to add reactivity to properties, which are added dynamically. Consider that we have already created vue instance and need to add the watch property. It can be done as follows −
<html>
<head>
<title>VueJs Instance</title>
<script type = "text/javascript" src = "js/vue.js"></script>
</head>
<body>
<div id = "app">
<p style = "font-size:25px;">Counter: {{ counter }}</p>
<button @click = "counter++" style = "font-size:25px;">Click Me</button>
</div>
<script type = "text/javascript">
var vm = new Vue({
el: '#app',
data: {
counter: 1
}
});
vm.$watch('counter', function(nval, oval) {
alert('Counter is incremented :' + oval + ' to ' + nval + '!');
});
setTimeout(
function(){
vm.counter = 20;
},2000
);
</script>
</body>
</html>
There is a property counter defined as 1 in data object. The counter is incremented when we click the button.
Vue instance is already created. To add watch to it, we need to do it as follows −
vm.$watch('counter', function(nval, oval) {
alert('Counter is incremented :' + oval + ' to ' + nval + '!');
});
We need to use $watch to add watch outside the vue instance. There is an alert added, which shows the value change for the counter property. There is also a timer function added, i.e. setTimeout, which sets the counter value to 20.
setTimeout(
function(){
vm.counter = 20;
},2000
);
Whenever the counter is changed, the alert from the watch method will get fired as shown in the following screenshot.
VueJS cannot detect property addition and deletion. The best way is to always declare the properties, which needs to be reactive upfront in the Vue instance. In case we need to add properties at run time, we can make use of Vue global, Vue.set, and Vue.delete methods.
This method helps to set a property on an object. It is used to get around the limitation that Vue cannot detect property additions.
Vue.set( target, key, value )
Where,
target: Can be an object or an array
key : Can be a string or number
value: Can be any type
Let’s take a look at an example.
<html>
<head>
<title>VueJs Instance</title>
<script type = "text/javascript" src = "js/vue.js"></script>
</head>
<body>
<div id = "app">
<p style = "font-size:25px;">Counter: {{ products.id }}</p>
<button @click = "products.id++" style = "font-size:25px;">Click Me</button>
</div>
<script type = "text/javascript">
var myproduct = {"id":1, name:"book", "price":"20.00"};
var vm = new Vue({
el: '#app',
data: {
counter: 1,
products: myproduct
}
});
vm.products.qty = "1";
console.log(vm);
vm.$watch('counter', function(nval, oval) {
alert('Counter is incremented :' + oval + ' to ' + nval + '!');
});
</script>
</body>
</html>
In the above example, there is a variable myproduct created at the start using the following piece of code.
var myproduct = {"id":1, name:"book", "price":"20.00"};
It is given to the data object in Vue instance as follows −
var vm = new Vue({
el: '#app',
data: {
counter: 1,
products: myproduct
}
});
Consider, we want to add one more property to the myproduct array, after the Vue instance is created. It can be done as follows −
vm.products.qty = "1";
Let’s see the output in the console.
As seen above, in products the quantity is added. The get/set methods, which basically adds reactivity is available for the id, name, and price, and not available for qty.
We cannot achieve the reactivity by just adding vue object. VueJS mostly wants all its properties to be created at the start. However, in case we need to add it later, we can use Vue.set. For this, we need to set it using vue global, i.e. Vue.set.
<html>
<head>
<title>VueJs Instance</title>
<script type = "text/javascript" src = "js/vue.js"></script>
</head>
<body>
<div id = "app">
<p style = "font-size:25px;">Counter: {{ products.id }}</p>
<button @click = "products.id++" style = "font-size:25px;">Click Me</button>
</div>
<script type = "text/javascript">
var myproduct = {"id":1, name:"book", "price":"20.00"};
var vm = new Vue({
el: '#app',
data: {
counter: 1,
products: myproduct
}
});
Vue.set(myproduct, 'qty', 1);
console.log(vm);
vm.$watch('counter', function(nval, oval) {
alert('Counter is incremented :' + oval + ' to ' + nval + '!');
});
</script>
</body>
</html>
We have used Vue.set to add the qty to the array using the following piece of code.
Vue.set(myproduct, 'qty', 1);
We have consoled the vue object and following is the output.
Now, we can see the get/set for qty added using Vue.set.
This function is used to delete the property dynamically.
Vue.delete( target, key )
Where,
target: Can be an object or an array
key: Can be a string or a number
To delete any property, we can use Vue.delete as in the following code.
<html>
<head>
<title>VueJs Instance</title>
<script type = "text/javascript" src = "js/vue.js"></script>
</head>
<body>
<div id = "app">
<p style = "font-size:25px;">Counter: {{ products.id }}</p>
<button @click = "products.id++" style = "font-size:25px;">Click Me</button>
</div>
<script type = "text/javascript">
var myproduct = {"id":1, name:"book", "price":"20.00"};
var vm = new Vue({
el: '#app',
data: {
counter: 1,
products: myproduct
}
});
Vue.delete(myproduct, 'price');
console.log(vm);
vm.$watch('counter', function(nval, oval) {
alert('Counter is incremented :' + oval + ' to ' + nval + '!');
});
</script>
</body>
</html>
In the above example, we have used Vue.delete to delete the price from the array using the following piece of code.
Vue.delete(myproduct, 'price');
Following is the output, we see in the console.
After deletion, we can see only the id and name as the price is deleted. We can also notice that the get/set methods are deleted.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2136,
"s": 1936,
"text": "VueJS provides options to add reactivity to properties, which are added dynamically. Consider that we have already created vue instance and need to add the watch property. It can be done as follows −"
},
{
"code": null,
"e": 2910,
"s": 2136,
"text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"app\">\n <p style = \"font-size:25px;\">Counter: {{ counter }}</p>\n <button @click = \"counter++\" style = \"font-size:25px;\">Click Me</button>\n </div>\n <script type = \"text/javascript\">\n var vm = new Vue({\n el: '#app',\n data: {\n counter: 1\n }\n });\n vm.$watch('counter', function(nval, oval) {\n alert('Counter is incremented :' + oval + ' to ' + nval + '!');\n });\n setTimeout(\n function(){\n vm.counter = 20;\n },2000\n );\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 3020,
"s": 2910,
"text": "There is a property counter defined as 1 in data object. The counter is incremented when we click the button."
},
{
"code": null,
"e": 3103,
"s": 3020,
"text": "Vue instance is already created. To add watch to it, we need to do it as follows −"
},
{
"code": null,
"e": 3218,
"s": 3103,
"text": "vm.$watch('counter', function(nval, oval) {\n alert('Counter is incremented :' + oval + ' to ' + nval + '!');\n});"
},
{
"code": null,
"e": 3450,
"s": 3218,
"text": "We need to use $watch to add watch outside the vue instance. There is an alert added, which shows the value change for the counter property. There is also a timer function added, i.e. setTimeout, which sets the counter value to 20."
},
{
"code": null,
"e": 3513,
"s": 3450,
"text": "setTimeout(\n function(){\n vm.counter = 20;\n },2000\n);"
},
{
"code": null,
"e": 3631,
"s": 3513,
"text": "Whenever the counter is changed, the alert from the watch method will get fired as shown in the following screenshot."
},
{
"code": null,
"e": 3900,
"s": 3631,
"text": "VueJS cannot detect property addition and deletion. The best way is to always declare the properties, which needs to be reactive upfront in the Vue instance. In case we need to add properties at run time, we can make use of Vue global, Vue.set, and Vue.delete methods."
},
{
"code": null,
"e": 4033,
"s": 3900,
"text": "This method helps to set a property on an object. It is used to get around the limitation that Vue cannot detect property additions."
},
{
"code": null,
"e": 4064,
"s": 4033,
"text": "Vue.set( target, key, value )\n"
},
{
"code": null,
"e": 4071,
"s": 4064,
"text": "Where,"
},
{
"code": null,
"e": 4108,
"s": 4071,
"text": "target: Can be an object or an array"
},
{
"code": null,
"e": 4140,
"s": 4108,
"text": "key : Can be a string or number"
},
{
"code": null,
"e": 4163,
"s": 4140,
"text": "value: Can be any type"
},
{
"code": null,
"e": 4196,
"s": 4163,
"text": "Let’s take a look at an example."
},
{
"code": null,
"e": 5029,
"s": 4196,
"text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"app\">\n <p style = \"font-size:25px;\">Counter: {{ products.id }}</p>\n <button @click = \"products.id++\" style = \"font-size:25px;\">Click Me</button>\n </div>\n <script type = \"text/javascript\">\n var myproduct = {\"id\":1, name:\"book\", \"price\":\"20.00\"};\n var vm = new Vue({\n el: '#app',\n data: {\n counter: 1,\n products: myproduct\n }\n });\n vm.products.qty = \"1\";\n console.log(vm);\n vm.$watch('counter', function(nval, oval) {\n alert('Counter is incremented :' + oval + ' to ' + nval + '!');\n });\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 5137,
"s": 5029,
"text": "In the above example, there is a variable myproduct created at the start using the following piece of code."
},
{
"code": null,
"e": 5193,
"s": 5137,
"text": "var myproduct = {\"id\":1, name:\"book\", \"price\":\"20.00\"};"
},
{
"code": null,
"e": 5253,
"s": 5193,
"text": "It is given to the data object in Vue instance as follows −"
},
{
"code": null,
"e": 5351,
"s": 5253,
"text": "var vm = new Vue({\n el: '#app',\n data: {\n counter: 1,\n products: myproduct\n }\n});"
},
{
"code": null,
"e": 5481,
"s": 5351,
"text": "Consider, we want to add one more property to the myproduct array, after the Vue instance is created. It can be done as follows −"
},
{
"code": null,
"e": 5504,
"s": 5481,
"text": "vm.products.qty = \"1\";"
},
{
"code": null,
"e": 5541,
"s": 5504,
"text": "Let’s see the output in the console."
},
{
"code": null,
"e": 5713,
"s": 5541,
"text": "As seen above, in products the quantity is added. The get/set methods, which basically adds reactivity is available for the id, name, and price, and not available for qty."
},
{
"code": null,
"e": 5961,
"s": 5713,
"text": "We cannot achieve the reactivity by just adding vue object. VueJS mostly wants all its properties to be created at the start. However, in case we need to add it later, we can use Vue.set. For this, we need to set it using vue global, i.e. Vue.set."
},
{
"code": null,
"e": 6801,
"s": 5961,
"text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"app\">\n <p style = \"font-size:25px;\">Counter: {{ products.id }}</p>\n <button @click = \"products.id++\" style = \"font-size:25px;\">Click Me</button>\n </div>\n <script type = \"text/javascript\">\n var myproduct = {\"id\":1, name:\"book\", \"price\":\"20.00\"};\n var vm = new Vue({\n el: '#app',\n data: {\n counter: 1,\n products: myproduct\n }\n });\n Vue.set(myproduct, 'qty', 1);\n console.log(vm);\n vm.$watch('counter', function(nval, oval) {\n alert('Counter is incremented :' + oval + ' to ' + nval + '!');\n });\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 6885,
"s": 6801,
"text": "We have used Vue.set to add the qty to the array using the following piece of code."
},
{
"code": null,
"e": 6915,
"s": 6885,
"text": "Vue.set(myproduct, 'qty', 1);"
},
{
"code": null,
"e": 6976,
"s": 6915,
"text": "We have consoled the vue object and following is the output."
},
{
"code": null,
"e": 7033,
"s": 6976,
"text": "Now, we can see the get/set for qty added using Vue.set."
},
{
"code": null,
"e": 7091,
"s": 7033,
"text": "This function is used to delete the property dynamically."
},
{
"code": null,
"e": 7117,
"s": 7091,
"text": "Vue.delete( target, key )"
},
{
"code": null,
"e": 7124,
"s": 7117,
"text": "Where,"
},
{
"code": null,
"e": 7161,
"s": 7124,
"text": "target: Can be an object or an array"
},
{
"code": null,
"e": 7194,
"s": 7161,
"text": "key: Can be a string or a number"
},
{
"code": null,
"e": 7266,
"s": 7194,
"text": "To delete any property, we can use Vue.delete as in the following code."
},
{
"code": null,
"e": 8108,
"s": 7266,
"text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"app\">\n <p style = \"font-size:25px;\">Counter: {{ products.id }}</p>\n <button @click = \"products.id++\" style = \"font-size:25px;\">Click Me</button>\n </div>\n <script type = \"text/javascript\">\n var myproduct = {\"id\":1, name:\"book\", \"price\":\"20.00\"};\n var vm = new Vue({\n el: '#app',\n data: {\n counter: 1,\n products: myproduct\n }\n });\n Vue.delete(myproduct, 'price');\n console.log(vm);\n vm.$watch('counter', function(nval, oval) {\n alert('Counter is incremented :' + oval + ' to ' + nval + '!');\n });\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 8224,
"s": 8108,
"text": "In the above example, we have used Vue.delete to delete the price from the array using the following piece of code."
},
{
"code": null,
"e": 8256,
"s": 8224,
"text": "Vue.delete(myproduct, 'price');"
},
{
"code": null,
"e": 8304,
"s": 8256,
"text": "Following is the output, we see in the console."
},
{
"code": null,
"e": 8434,
"s": 8304,
"text": "After deletion, we can see only the id and name as the price is deleted. We can also notice that the get/set methods are deleted."
},
{
"code": null,
"e": 8441,
"s": 8434,
"text": " Print"
},
{
"code": null,
"e": 8452,
"s": 8441,
"text": " Add Notes"
}
] |
Java Program for Radix Sort - GeeksforGeeks
|
24 May, 2019
The Radix Sort Algorithm1) Do following for each digit i where i varies from least significant digit to the most significant digit..............a) Sort input array using counting sort (or any stable sort) according to the i\’th digit.
// Radix sort Java implementationimport java.io.*;import java.util.*; class Radix { // A utility function to get maximum value in arr[] static int getMax(int arr[], int n) { int mx = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > mx) mx = arr[i]; return mx; } // A function to do counting sort of arr[] according to // the digit represented by exp. static void countSort(int arr[], int n, int exp) { int output[] = new int[n]; // output array int i; int count[] = new int[10]; Arrays.fill(count,0); // Store count of occurrences in count[] for (i = 0; i < n; i++) count[ (arr[i]/exp)%10 ]++; // Change count[i] so that count[i] now contains // actual position of this digit in output[] for (i = 1; i < 10; i++) count[i] += count[i - 1]; // Build the output array for (i = n - 1; i >= 0; i--) { output[count[ (arr[i]/exp)%10 ] - 1] = arr[i]; count[ (arr[i]/exp)%10 ]--; } // Copy the output array to arr[], so that arr[] now // contains sorted numbers according to current digit for (i = 0; i < n; i++) arr[i] = output[i]; } // The main function to that sorts arr[] of size n using // Radix Sort static void radixsort(int arr[], int n) { // Find the maximum number to know number of digits int m = getMax(arr, n); // Do counting sort for every digit. Note that instead // of passing digit number, exp is passed. exp is 10^i // where i is current digit number for (int exp = 1; m/exp > 0; exp *= 10) countSort(arr, n, exp); } // A utility function to print an array static void print(int arr[], int n) { for (int i=0; i<n; i++) System.out.print(arr[i]+" "); } /*Driver function to check for above function*/ public static void main (String[] args) { int arr[] = {170, 45, 75, 90, 802, 24, 2, 66}; int n = arr.length; radixsort(arr, n); print(arr, n); }}/* This code is contributed by Devesh Agrawal */
Please refer complete article on Radix Sort for more details!
nidhi_biet
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Iterate HashMap in Java?
Iterate Over the Characters of a String in Java
How to Get Elements By Index from HashSet in Java?
Java Program to Write into a File
Modulo or Remainder Operator in Java
Java Program to Convert String to String Array
Java Program to Find Sum of Array Elements
How to Replace a Element in Java ArrayList?
How to Iterate LinkedList in Java?
How to convert Date to String in Java
|
[
{
"code": null,
"e": 24513,
"s": 24485,
"text": "\n24 May, 2019"
},
{
"code": null,
"e": 24748,
"s": 24513,
"text": "The Radix Sort Algorithm1) Do following for each digit i where i varies from least significant digit to the most significant digit..............a) Sort input array using counting sort (or any stable sort) according to the i\\’th digit."
},
{
"code": "// Radix sort Java implementationimport java.io.*;import java.util.*; class Radix { // A utility function to get maximum value in arr[] static int getMax(int arr[], int n) { int mx = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > mx) mx = arr[i]; return mx; } // A function to do counting sort of arr[] according to // the digit represented by exp. static void countSort(int arr[], int n, int exp) { int output[] = new int[n]; // output array int i; int count[] = new int[10]; Arrays.fill(count,0); // Store count of occurrences in count[] for (i = 0; i < n; i++) count[ (arr[i]/exp)%10 ]++; // Change count[i] so that count[i] now contains // actual position of this digit in output[] for (i = 1; i < 10; i++) count[i] += count[i - 1]; // Build the output array for (i = n - 1; i >= 0; i--) { output[count[ (arr[i]/exp)%10 ] - 1] = arr[i]; count[ (arr[i]/exp)%10 ]--; } // Copy the output array to arr[], so that arr[] now // contains sorted numbers according to current digit for (i = 0; i < n; i++) arr[i] = output[i]; } // The main function to that sorts arr[] of size n using // Radix Sort static void radixsort(int arr[], int n) { // Find the maximum number to know number of digits int m = getMax(arr, n); // Do counting sort for every digit. Note that instead // of passing digit number, exp is passed. exp is 10^i // where i is current digit number for (int exp = 1; m/exp > 0; exp *= 10) countSort(arr, n, exp); } // A utility function to print an array static void print(int arr[], int n) { for (int i=0; i<n; i++) System.out.print(arr[i]+\" \"); } /*Driver function to check for above function*/ public static void main (String[] args) { int arr[] = {170, 45, 75, 90, 802, 24, 2, 66}; int n = arr.length; radixsort(arr, n); print(arr, n); }}/* This code is contributed by Devesh Agrawal */",
"e": 26952,
"s": 24748,
"text": null
},
{
"code": null,
"e": 27014,
"s": 26952,
"text": "Please refer complete article on Radix Sort for more details!"
},
{
"code": null,
"e": 27025,
"s": 27014,
"text": "nidhi_biet"
},
{
"code": null,
"e": 27039,
"s": 27025,
"text": "Java Programs"
},
{
"code": null,
"e": 27137,
"s": 27039,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27146,
"s": 27137,
"text": "Comments"
},
{
"code": null,
"e": 27159,
"s": 27146,
"text": "Old Comments"
},
{
"code": null,
"e": 27191,
"s": 27159,
"text": "How to Iterate HashMap in Java?"
},
{
"code": null,
"e": 27239,
"s": 27191,
"text": "Iterate Over the Characters of a String in Java"
},
{
"code": null,
"e": 27290,
"s": 27239,
"text": "How to Get Elements By Index from HashSet in Java?"
},
{
"code": null,
"e": 27324,
"s": 27290,
"text": "Java Program to Write into a File"
},
{
"code": null,
"e": 27361,
"s": 27324,
"text": "Modulo or Remainder Operator in Java"
},
{
"code": null,
"e": 27408,
"s": 27361,
"text": "Java Program to Convert String to String Array"
},
{
"code": null,
"e": 27451,
"s": 27408,
"text": "Java Program to Find Sum of Array Elements"
},
{
"code": null,
"e": 27495,
"s": 27451,
"text": "How to Replace a Element in Java ArrayList?"
},
{
"code": null,
"e": 27530,
"s": 27495,
"text": "How to Iterate LinkedList in Java?"
}
] |
umask() - Unix, Linux System Call
|
Unix - Home
Unix - Getting Started
Unix - File Management
Unix - Directories
Unix - File Permission
Unix - Environment
Unix - Basic Utilities
Unix - Pipes & Filters
Unix - Processes
Unix - Communication
Unix - The vi Editor
Unix - What is Shell?
Unix - Using Variables
Unix - Special Variables
Unix - Using Arrays
Unix - Basic Operators
Unix - Decision Making
Unix - Shell Loops
Unix - Loop Control
Unix - Shell Substitutions
Unix - Quoting Mechanisms
Unix - IO Redirections
Unix - Shell Functions
Unix - Manpage Help
Unix - Regular Expressions
Unix - File System Basics
Unix - User Administration
Unix - System Performance
Unix - System Logging
Unix - Signals and Traps
Unix - Useful Commands
Unix - Quick Guide
Unix - Builtin Functions
Unix - System Calls
Unix - Commands List
Unix Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint
umask - set file mode creation mask
#include <sys/types.h>
#include <sys/stat.h>
mode_t umask(mode_t mask);
mode_t umask(mode_t mask);
umask() sets the calling process’s file mode creation mask (umask) to mask & 0777.
The umask is used by open(2),
mkdir(2),
and other system calls that create files
to modify the permissions placed on newly created files or directories.
Specifically, permissions in the umask are turned off from
the mode argument to
open(2)
and
mkdir(2).
The constants that should be used to specify
mask are described under
stat(2).
The typical default value for the process umask is
S_IWGRP | S_IWOTH
(octal 022).
In the usual case where the
mode argument to
open(2)
is specified as:
S_IRUSR | S_IWUSR | S_IRGRP | S_IWRGRP | S_IROTH | S_IWOTH
(octal 0666) when creating a new file, the permissions on the
resulting file will be:
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH
(because 0666 & ~022 = 0644; i.e., rw-r--r--).
This system call always succeeds and the previous value of the mask
is returned.
A child process created via
fork(2)
inherits its parent’s umask.
The umask is left unchanged by
execve(2).
SVr4, 4.3BSD, POSIX.1-2001.
chmod (2)
chmod (2)
mkdir (2)
mkdir (2)
open (2)
open (2)
stat (2)
stat (2)
Advertisements
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1466,
"s": 1454,
"text": "Unix - Home"
},
{
"code": null,
"e": 1489,
"s": 1466,
"text": "Unix - Getting Started"
},
{
"code": null,
"e": 1512,
"s": 1489,
"text": "Unix - File Management"
},
{
"code": null,
"e": 1531,
"s": 1512,
"text": "Unix - Directories"
},
{
"code": null,
"e": 1554,
"s": 1531,
"text": "Unix - File Permission"
},
{
"code": null,
"e": 1573,
"s": 1554,
"text": "Unix - Environment"
},
{
"code": null,
"e": 1596,
"s": 1573,
"text": "Unix - Basic Utilities"
},
{
"code": null,
"e": 1619,
"s": 1596,
"text": "Unix - Pipes & Filters"
},
{
"code": null,
"e": 1636,
"s": 1619,
"text": "Unix - Processes"
},
{
"code": null,
"e": 1657,
"s": 1636,
"text": "Unix - Communication"
},
{
"code": null,
"e": 1678,
"s": 1657,
"text": "Unix - The vi Editor"
},
{
"code": null,
"e": 1700,
"s": 1678,
"text": "Unix - What is Shell?"
},
{
"code": null,
"e": 1723,
"s": 1700,
"text": "Unix - Using Variables"
},
{
"code": null,
"e": 1748,
"s": 1723,
"text": "Unix - Special Variables"
},
{
"code": null,
"e": 1768,
"s": 1748,
"text": "Unix - Using Arrays"
},
{
"code": null,
"e": 1791,
"s": 1768,
"text": "Unix - Basic Operators"
},
{
"code": null,
"e": 1814,
"s": 1791,
"text": "Unix - Decision Making"
},
{
"code": null,
"e": 1833,
"s": 1814,
"text": "Unix - Shell Loops"
},
{
"code": null,
"e": 1853,
"s": 1833,
"text": "Unix - Loop Control"
},
{
"code": null,
"e": 1880,
"s": 1853,
"text": "Unix - Shell Substitutions"
},
{
"code": null,
"e": 1906,
"s": 1880,
"text": "Unix - Quoting Mechanisms"
},
{
"code": null,
"e": 1929,
"s": 1906,
"text": "Unix - IO Redirections"
},
{
"code": null,
"e": 1952,
"s": 1929,
"text": "Unix - Shell Functions"
},
{
"code": null,
"e": 1972,
"s": 1952,
"text": "Unix - Manpage Help"
},
{
"code": null,
"e": 1999,
"s": 1972,
"text": "Unix - Regular Expressions"
},
{
"code": null,
"e": 2025,
"s": 1999,
"text": "Unix - File System Basics"
},
{
"code": null,
"e": 2052,
"s": 2025,
"text": "Unix - User Administration"
},
{
"code": null,
"e": 2078,
"s": 2052,
"text": "Unix - System Performance"
},
{
"code": null,
"e": 2100,
"s": 2078,
"text": "Unix - System Logging"
},
{
"code": null,
"e": 2125,
"s": 2100,
"text": "Unix - Signals and Traps"
},
{
"code": null,
"e": 2148,
"s": 2125,
"text": "Unix - Useful Commands"
},
{
"code": null,
"e": 2167,
"s": 2148,
"text": "Unix - Quick Guide"
},
{
"code": null,
"e": 2192,
"s": 2167,
"text": "Unix - Builtin Functions"
},
{
"code": null,
"e": 2212,
"s": 2192,
"text": "Unix - System Calls"
},
{
"code": null,
"e": 2233,
"s": 2212,
"text": "Unix - Commands List"
},
{
"code": null,
"e": 2255,
"s": 2233,
"text": "Unix Useful Resources"
},
{
"code": null,
"e": 2273,
"s": 2255,
"text": "Computer Glossary"
},
{
"code": null,
"e": 2284,
"s": 2273,
"text": "Who is Who"
},
{
"code": null,
"e": 2319,
"s": 2284,
"text": "Copyright © 2014 by tutorialspoint"
},
{
"code": null,
"e": 2355,
"s": 2319,
"text": "umask - set file mode creation mask"
},
{
"code": null,
"e": 2430,
"s": 2355,
"text": "#include <sys/types.h>\n#include <sys/stat.h> \nmode_t umask(mode_t mask); \n"
},
{
"code": null,
"e": 2460,
"s": 2430,
"text": "\nmode_t umask(mode_t mask); \n"
},
{
"code": null,
"e": 2543,
"s": 2460,
"text": "umask() sets the calling process’s file mode creation mask (umask) to mask & 0777."
},
{
"code": null,
"e": 2798,
"s": 2543,
"text": "The umask is used by open(2),\nmkdir(2),\nand other system calls that create files\nto modify the permissions placed on newly created files or directories.\nSpecifically, permissions in the umask are turned off from\nthe mode argument to\nopen(2)\nand\nmkdir(2)."
},
{
"code": null,
"e": 2877,
"s": 2798,
"text": "The constants that should be used to specify\nmask are described under\nstat(2)."
},
{
"code": null,
"e": 3029,
"s": 2877,
"text": "The typical default value for the process umask is\nS_IWGRP | S_IWOTH\n(octal 022).\nIn the usual case where the\nmode argument to\nopen(2)\nis specified as:"
},
{
"code": null,
"e": 3089,
"s": 3029,
"text": "S_IRUSR | S_IWUSR | S_IRGRP | S_IWRGRP | S_IROTH | S_IWOTH\n"
},
{
"code": null,
"e": 3175,
"s": 3089,
"text": "(octal 0666) when creating a new file, the permissions on the\nresulting file will be:"
},
{
"code": null,
"e": 3214,
"s": 3175,
"text": "S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH\n"
},
{
"code": null,
"e": 3261,
"s": 3214,
"text": "(because 0666 & ~022 = 0644; i.e., rw-r--r--)."
},
{
"code": null,
"e": 3342,
"s": 3261,
"text": "This system call always succeeds and the previous value of the mask\nis returned."
},
{
"code": null,
"e": 3449,
"s": 3342,
"text": "A child process created via\nfork(2)\ninherits its parent’s umask.\nThe umask is left unchanged by\nexecve(2)."
},
{
"code": null,
"e": 3477,
"s": 3449,
"text": "SVr4, 4.3BSD, POSIX.1-2001."
},
{
"code": null,
"e": 3487,
"s": 3477,
"text": "chmod (2)"
},
{
"code": null,
"e": 3497,
"s": 3487,
"text": "chmod (2)"
},
{
"code": null,
"e": 3507,
"s": 3497,
"text": "mkdir (2)"
},
{
"code": null,
"e": 3517,
"s": 3507,
"text": "mkdir (2)"
},
{
"code": null,
"e": 3526,
"s": 3517,
"text": "open (2)"
},
{
"code": null,
"e": 3535,
"s": 3526,
"text": "open (2)"
},
{
"code": null,
"e": 3544,
"s": 3535,
"text": "stat (2)"
},
{
"code": null,
"e": 3553,
"s": 3544,
"text": "stat (2)"
},
{
"code": null,
"e": 3570,
"s": 3553,
"text": "\nAdvertisements\n"
},
{
"code": null,
"e": 3605,
"s": 3570,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 3633,
"s": 3605,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3667,
"s": 3633,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3684,
"s": 3667,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3717,
"s": 3684,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3728,
"s": 3717,
"text": " Pradeep D"
},
{
"code": null,
"e": 3763,
"s": 3728,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3779,
"s": 3763,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 3812,
"s": 3779,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3824,
"s": 3812,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 3856,
"s": 3824,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3864,
"s": 3856,
"text": " Uplatz"
},
{
"code": null,
"e": 3871,
"s": 3864,
"text": " Print"
},
{
"code": null,
"e": 3882,
"s": 3871,
"text": " Add Notes"
}
] |
How to add icons in the button in HTML ?
|
13 Jan, 2022
We can add icons on buttons in so many ways but we will try that in pure HTML.
We have to use external fonts links for the icons. Applying icons on the button makes the user easy to understand the functionality of that button.
Font Awesome icon in your form is an innovative idea, that will bring attention to your website. It is as simple as applying Font Awesome icon on any button. The <i> tag and <span> tag are used widely to add icons on the webpages. To add any icons on the web pages, it needs the font-awesome link inside the head section. The font-awesome icon can be placed by using the fa prefix before the icon’s name.CDN Link:
https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css
Example: In this example, we will take a form where the button is necessary. After that, we will place the font-awesome icon inside the button. We will use the CDN link to use the font-awesome icons. After the button, we will place our icon.
HTML
<!DOCTYPE html><html> <head> <!-- Add icon library --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <style> h1 { color: green; } .btn { background-color: light-green; padding: 12px 16px; font-size: 16px; } .btn:hover { background-color: green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h2>How to add icons in the button in HTML?</h2> <button class="btn"> <i class="fa fa-bolt"></i> </button> <button class="btn"> <i class="fa fa-fire"></i> </button> <button class="btn"> <i class="fa fa-tree"></i> </button> <button class="btn"> <i class="fa fa-trash"></i> </button> </center></body> </html>
Output:
HTML-Questions
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Angular File Upload
Form validation using jQuery
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Jan, 2022"
},
{
"code": null,
"e": 108,
"s": 28,
"text": "We can add icons on buttons in so many ways but we will try that in pure HTML. "
},
{
"code": null,
"e": 256,
"s": 108,
"text": "We have to use external fonts links for the icons. Applying icons on the button makes the user easy to understand the functionality of that button."
},
{
"code": null,
"e": 670,
"s": 256,
"text": "Font Awesome icon in your form is an innovative idea, that will bring attention to your website. It is as simple as applying Font Awesome icon on any button. The <i> tag and <span> tag are used widely to add icons on the webpages. To add any icons on the web pages, it needs the font-awesome link inside the head section. The font-awesome icon can be placed by using the fa prefix before the icon’s name.CDN Link:"
},
{
"code": null,
"e": 753,
"s": 670,
"text": "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"
},
{
"code": null,
"e": 995,
"s": 753,
"text": "Example: In this example, we will take a form where the button is necessary. After that, we will place the font-awesome icon inside the button. We will use the CDN link to use the font-awesome icons. After the button, we will place our icon."
},
{
"code": null,
"e": 1000,
"s": 995,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- Add icon library --> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\"> <style> h1 { color: green; } .btn { background-color: light-green; padding: 12px 16px; font-size: 16px; } .btn:hover { background-color: green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h2>How to add icons in the button in HTML?</h2> <button class=\"btn\"> <i class=\"fa fa-bolt\"></i> </button> <button class=\"btn\"> <i class=\"fa fa-fire\"></i> </button> <button class=\"btn\"> <i class=\"fa fa-tree\"></i> </button> <button class=\"btn\"> <i class=\"fa fa-trash\"></i> </button> </center></body> </html>",
"e": 1896,
"s": 1000,
"text": null
},
{
"code": null,
"e": 1904,
"s": 1896,
"text": "Output:"
},
{
"code": null,
"e": 1919,
"s": 1904,
"text": "HTML-Questions"
},
{
"code": null,
"e": 1926,
"s": 1919,
"text": "Picked"
},
{
"code": null,
"e": 1931,
"s": 1926,
"text": "HTML"
},
{
"code": null,
"e": 1948,
"s": 1931,
"text": "Web Technologies"
},
{
"code": null,
"e": 1953,
"s": 1948,
"text": "HTML"
},
{
"code": null,
"e": 2051,
"s": 1953,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2075,
"s": 2051,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 2114,
"s": 2075,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 2153,
"s": 2114,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 2173,
"s": 2153,
"text": "Angular File Upload"
},
{
"code": null,
"e": 2202,
"s": 2173,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 2235,
"s": 2202,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2296,
"s": 2235,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2339,
"s": 2296,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 2411,
"s": 2339,
"text": "Differences between Functional Components and Class Components in React"
}
] |
std::uniform_int_distribution class in C++
|
02 Jul, 2021
In Probability, Discrete Uniform Distribution Function refers to the distribution with constant probability for discrete values over a range and zero probability outside the range. The probability density function P(x) for uniform discrete distribution in interval [a, b] is constant for discrete values in the range [a, b] and zero otherwise. Mathematically the function is defined as:
C++ have introduced uniform_int_distribution class in the random library whose member function give random integer numbers or discrete values from a given input range with uniform probability.Public member functions in uniform_int_distribution class:
operator(): This function returns a random number from the given range of distribution. The probability for any number to be obtained from this function is same. Operator() function takes constant time for generation. Example:
operator(): This function returns a random number from the given range of distribution. The probability for any number to be obtained from this function is same. Operator() function takes constant time for generation. Example:
CPP
// C++ code to demonstrate the working of// operator() function #include <iostream> // for uniform_int_distribution function#include <random> using namespace std; int main(){ // Here default_random_engine object // is used as source of randomness // We can give seed also to default_random_engine // if psuedorandom numbers are required default_random_engine generator; int a = 0, b = 9; // Initializing of uniform_int_distribution class uniform_int_distribution<int> distribution(a, b); // number of experiments const int num_of_exp = 10000; int n = b - a + 1; int p[n] = {}; for (int i = 0; i < num_of_exp; ++i) { // using operator() function // to give random values int number = distribution(generator); ++p[number-a]; } cout << "Expected probability: " << float(1) / float(n) << endl; cout << "uniform_int_distribution (" << a << ", " << b << ")" << endl; // Displaying the probability of each number // after generating values 10000 times. for (int i = 0; i < n; ++i) cout << a + i << ": " << (float)p[i] / (float)(num_of_exp) << endl; return 0;}
Expected probability: 0.1
uniform_int_distribution (0, 9)
0: 0.0993
1: 0.1007
2: 0.0998
3: 0.0958
4: 0.1001
5: 0.1049
6: 0.0989
7: 0.0963
8: 0.1026
9: 0.1016
We could observe from the output that the probability of each number obtained from the random number is much closer to calculated probability.
a(): Returns the lower parameter of range. This specifies the lower bound of the range of values potentially returned by its member operator(). b(): Returns the higher parameter of range. This specifies the upper bound of the range of values potentially returned by its member operator(). max(): This function return the possible smallest upper bound of output possible from the operator() function. min(): This function return the possible highest lower bound of output possible from the operator() function. reset(): This function resets the distribution such that subsequent distributions are not dependent on the previously generated numbers.
a(): Returns the lower parameter of range. This specifies the lower bound of the range of values potentially returned by its member operator().
b(): Returns the higher parameter of range. This specifies the upper bound of the range of values potentially returned by its member operator().
max(): This function return the possible smallest upper bound of output possible from the operator() function.
min(): This function return the possible highest lower bound of output possible from the operator() function.
reset(): This function resets the distribution such that subsequent distributions are not dependent on the previously generated numbers.
Example:
CPP
// C++ code to demonstrate the working of// a(), b(), min(), max(), reset() function #include <iostream> // for uniform_int_distribution function#include <random> using namespace std; int main(){ int a = 10, b = 100; // Initializing of uniform_int_distribution class uniform_int_distribution<int> distribution(a, b); // Using a() and b() cout << "Lower Bound" << " " << distribution.a() << endl; cout << "Upper Bound" << " " << distribution.b() << endl; // Using min() and max() cout << "Minimum possible output" << " " << distribution.min() << endl; cout << "Maximum possible output" << " " << distribution.max() << endl; // Using reset() distribution.reset(); return 0;}
Lower Bound 10
Upper Bound 100
Minimum possible output 10
Maximum possible output 100
Reference: https://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution
AyushShukla8
khjoyfoysal
abhishek0719kadiyan
cpp-class
cpp-random
C++ Programs
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Passing a function as a parameter in C++
Const keyword in C++
cout in C++
Program to implement Singly Linked List in C++ using class
Different ways to print elements of vector
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n02 Jul, 2021"
},
{
"code": null,
"e": 440,
"s": 52,
"text": "In Probability, Discrete Uniform Distribution Function refers to the distribution with constant probability for discrete values over a range and zero probability outside the range. The probability density function P(x) for uniform discrete distribution in interval [a, b] is constant for discrete values in the range [a, b] and zero otherwise. Mathematically the function is defined as: "
},
{
"code": null,
"e": 699,
"s": 447,
"text": "C++ have introduced uniform_int_distribution class in the random library whose member function give random integer numbers or discrete values from a given input range with uniform probability.Public member functions in uniform_int_distribution class: "
},
{
"code": null,
"e": 928,
"s": 699,
"text": "operator(): This function returns a random number from the given range of distribution. The probability for any number to be obtained from this function is same. Operator() function takes constant time for generation. Example: "
},
{
"code": null,
"e": 1157,
"s": 928,
"text": "operator(): This function returns a random number from the given range of distribution. The probability for any number to be obtained from this function is same. Operator() function takes constant time for generation. Example: "
},
{
"code": null,
"e": 1161,
"s": 1157,
"text": "CPP"
},
{
"code": "// C++ code to demonstrate the working of// operator() function #include <iostream> // for uniform_int_distribution function#include <random> using namespace std; int main(){ // Here default_random_engine object // is used as source of randomness // We can give seed also to default_random_engine // if psuedorandom numbers are required default_random_engine generator; int a = 0, b = 9; // Initializing of uniform_int_distribution class uniform_int_distribution<int> distribution(a, b); // number of experiments const int num_of_exp = 10000; int n = b - a + 1; int p[n] = {}; for (int i = 0; i < num_of_exp; ++i) { // using operator() function // to give random values int number = distribution(generator); ++p[number-a]; } cout << \"Expected probability: \" << float(1) / float(n) << endl; cout << \"uniform_int_distribution (\" << a << \", \" << b << \")\" << endl; // Displaying the probability of each number // after generating values 10000 times. for (int i = 0; i < n; ++i) cout << a + i << \": \" << (float)p[i] / (float)(num_of_exp) << endl; return 0;}",
"e": 2358,
"s": 1161,
"text": null
},
{
"code": null,
"e": 2516,
"s": 2358,
"text": "Expected probability: 0.1\nuniform_int_distribution (0, 9)\n0: 0.0993\n1: 0.1007\n2: 0.0998\n3: 0.0958\n4: 0.1001\n5: 0.1049\n6: 0.0989\n7: 0.0963\n8: 0.1026\n9: 0.1016"
},
{
"code": null,
"e": 2663,
"s": 2518,
"text": "We could observe from the output that the probability of each number obtained from the random number is much closer to calculated probability. "
},
{
"code": null,
"e": 3316,
"s": 2663,
"text": "a(): Returns the lower parameter of range. This specifies the lower bound of the range of values potentially returned by its member operator(). b(): Returns the higher parameter of range. This specifies the upper bound of the range of values potentially returned by its member operator(). max(): This function return the possible smallest upper bound of output possible from the operator() function. min(): This function return the possible highest lower bound of output possible from the operator() function. reset(): This function resets the distribution such that subsequent distributions are not dependent on the previously generated numbers. "
},
{
"code": null,
"e": 3462,
"s": 3316,
"text": "a(): Returns the lower parameter of range. This specifies the lower bound of the range of values potentially returned by its member operator(). "
},
{
"code": null,
"e": 3609,
"s": 3462,
"text": "b(): Returns the higher parameter of range. This specifies the upper bound of the range of values potentially returned by its member operator(). "
},
{
"code": null,
"e": 3722,
"s": 3609,
"text": "max(): This function return the possible smallest upper bound of output possible from the operator() function. "
},
{
"code": null,
"e": 3834,
"s": 3722,
"text": "min(): This function return the possible highest lower bound of output possible from the operator() function. "
},
{
"code": null,
"e": 3973,
"s": 3834,
"text": "reset(): This function resets the distribution such that subsequent distributions are not dependent on the previously generated numbers. "
},
{
"code": null,
"e": 3983,
"s": 3973,
"text": "Example: "
},
{
"code": null,
"e": 3987,
"s": 3983,
"text": "CPP"
},
{
"code": "// C++ code to demonstrate the working of// a(), b(), min(), max(), reset() function #include <iostream> // for uniform_int_distribution function#include <random> using namespace std; int main(){ int a = 10, b = 100; // Initializing of uniform_int_distribution class uniform_int_distribution<int> distribution(a, b); // Using a() and b() cout << \"Lower Bound\" << \" \" << distribution.a() << endl; cout << \"Upper Bound\" << \" \" << distribution.b() << endl; // Using min() and max() cout << \"Minimum possible output\" << \" \" << distribution.min() << endl; cout << \"Maximum possible output\" << \" \" << distribution.max() << endl; // Using reset() distribution.reset(); return 0;}",
"e": 4732,
"s": 3987,
"text": null
},
{
"code": null,
"e": 4818,
"s": 4732,
"text": "Lower Bound 10\nUpper Bound 100\nMinimum possible output 10\nMaximum possible output 100"
},
{
"code": null,
"e": 4906,
"s": 4820,
"text": "Reference: https://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution "
},
{
"code": null,
"e": 4919,
"s": 4906,
"text": "AyushShukla8"
},
{
"code": null,
"e": 4931,
"s": 4919,
"text": "khjoyfoysal"
},
{
"code": null,
"e": 4951,
"s": 4931,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 4961,
"s": 4951,
"text": "cpp-class"
},
{
"code": null,
"e": 4972,
"s": 4961,
"text": "cpp-random"
},
{
"code": null,
"e": 4985,
"s": 4972,
"text": "C++ Programs"
},
{
"code": null,
"e": 4998,
"s": 4985,
"text": "Mathematical"
},
{
"code": null,
"e": 5011,
"s": 4998,
"text": "Mathematical"
},
{
"code": null,
"e": 5109,
"s": 5011,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5150,
"s": 5109,
"text": "Passing a function as a parameter in C++"
},
{
"code": null,
"e": 5171,
"s": 5150,
"text": "Const keyword in C++"
},
{
"code": null,
"e": 5183,
"s": 5171,
"text": "cout in C++"
},
{
"code": null,
"e": 5242,
"s": 5183,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 5285,
"s": 5242,
"text": "Different ways to print elements of vector"
},
{
"code": null,
"e": 5315,
"s": 5285,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 5358,
"s": 5315,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 5418,
"s": 5358,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 5433,
"s": 5418,
"text": "C++ Data Types"
}
] |
HTML <option> Tag
|
17 Mar, 2022
The <option> tag in HTML is used to choose an option from a Drop-Down menu. This tag can be used with or without any attributes and needed value can be sent to the server. The group of options can be created using <optgroup> Tag. It creates a group of related menu items.
Syntax:
<option> Contents... </option>
Attributes: The <option> tag contains four attributes which are listed below:
disabled: This attribute contains the value disabled which represents the option is disabled.
label: This attribute contains the text value which represents the shorted label for the option.
selected: This attribute contains the value selected which represents the item that is pre-selected when the browser loaded.
value: This attribute contains the value text sent to the server.
Example 1:
HTML
<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>HTML option Tag</h2> <select> <!-- option tag starts --> <option>Choose an option</option> <option value="html">HTML</option> <option value="java">JAVA</option> <option value="C++">C++</option> <option value="php">PHP</option> <option value="perl">PERL</option> <!-- option tag ends --> </select></body> </html>
Output:
Example 2:
HTML
<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>HTML option Tag</h2> <strong>Select City<br></strong> <select> <!-- option tag starts --> <option>Allahabad</option> <option>Pryagraj</option> <option>Jaipur</option> <option>Noida</option> <!-- option tag ends --> </select></body> </html>
Output:
Supported Browsers:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
ghoshsuman0129
HTML-Tags
HTML
HTML
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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
CSS to put icon inside an input element in a form
Design a Tribute Page using HTML & CSS
Types of CSS (Cascading Style Sheet)
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 Mar, 2022"
},
{
"code": null,
"e": 324,
"s": 52,
"text": "The <option> tag in HTML is used to choose an option from a Drop-Down menu. This tag can be used with or without any attributes and needed value can be sent to the server. The group of options can be created using <optgroup> Tag. It creates a group of related menu items."
},
{
"code": null,
"e": 333,
"s": 324,
"text": "Syntax: "
},
{
"code": null,
"e": 364,
"s": 333,
"text": "<option> Contents... </option>"
},
{
"code": null,
"e": 443,
"s": 364,
"text": "Attributes: The <option> tag contains four attributes which are listed below: "
},
{
"code": null,
"e": 537,
"s": 443,
"text": "disabled: This attribute contains the value disabled which represents the option is disabled."
},
{
"code": null,
"e": 634,
"s": 537,
"text": "label: This attribute contains the text value which represents the shorted label for the option."
},
{
"code": null,
"e": 759,
"s": 634,
"text": "selected: This attribute contains the value selected which represents the item that is pre-selected when the browser loaded."
},
{
"code": null,
"e": 825,
"s": 759,
"text": "value: This attribute contains the value text sent to the server."
},
{
"code": null,
"e": 837,
"s": 825,
"text": "Example 1: "
},
{
"code": null,
"e": 842,
"s": 837,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>HTML option Tag</h2> <select> <!-- option tag starts --> <option>Choose an option</option> <option value=\"html\">HTML</option> <option value=\"java\">JAVA</option> <option value=\"C++\">C++</option> <option value=\"php\">PHP</option> <option value=\"perl\">PERL</option> <!-- option tag ends --> </select></body> </html>",
"e": 1308,
"s": 842,
"text": null
},
{
"code": null,
"e": 1318,
"s": 1308,
"text": "Output: "
},
{
"code": null,
"e": 1330,
"s": 1318,
"text": "Example 2: "
},
{
"code": null,
"e": 1335,
"s": 1330,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>HTML option Tag</h2> <strong>Select City<br></strong> <select> <!-- option tag starts --> <option>Allahabad</option> <option>Pryagraj</option> <option>Jaipur</option> <option>Noida</option> <!-- option tag ends --> </select></body> </html>",
"e": 1714,
"s": 1335,
"text": null
},
{
"code": null,
"e": 1724,
"s": 1714,
"text": "Output: "
},
{
"code": null,
"e": 1745,
"s": 1724,
"text": "Supported Browsers: "
},
{
"code": null,
"e": 1759,
"s": 1745,
"text": "Google Chrome"
},
{
"code": null,
"e": 1777,
"s": 1759,
"text": "Internet Explorer"
},
{
"code": null,
"e": 1785,
"s": 1777,
"text": "Firefox"
},
{
"code": null,
"e": 1792,
"s": 1785,
"text": "Safari"
},
{
"code": null,
"e": 1798,
"s": 1792,
"text": "Opera"
},
{
"code": null,
"e": 1813,
"s": 1798,
"text": "ghoshsuman0129"
},
{
"code": null,
"e": 1823,
"s": 1813,
"text": "HTML-Tags"
},
{
"code": null,
"e": 1828,
"s": 1823,
"text": "HTML"
},
{
"code": null,
"e": 1833,
"s": 1828,
"text": "HTML"
},
{
"code": null,
"e": 1931,
"s": 1833,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1979,
"s": 1931,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 2041,
"s": 1979,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2091,
"s": 2041,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 2115,
"s": 2091,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 2168,
"s": 2115,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 2228,
"s": 2168,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 2289,
"s": 2228,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 2339,
"s": 2289,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 2378,
"s": 2339,
"text": "Design a Tribute Page using HTML & CSS"
}
] |
Check whether bitwise AND of a number with any subset of an array is zero or not
|
03 Mar, 2022
Given an array and a Number N. The task is to check whether there exists any subset of this array such that the bitwise AND of this subset with N is zero.Examples:
Input : arr[] = {1, 2, 4} ; N = 3
Output : YES
Explanation: The subsets are:
(1, 2 ), (1, 4), (1, 2, 4)
Input : arr[] = {1, 1, 1} ; N = 3
Output : NO
A Simple Approach is to find the bitwise-AND of all the subsets of the array and check whether the AND of N with any subset is zero or not.An Efficient Approach is to observe that bitwise-AND of any two numbers will always produce a number less than or equal to the smaller number. So our task is to find the subset which has the minimum value of bitwise AND. So as stated earlier the AND of any two numbers will always produce a number less than or equal to the minimum number so the minimum value of AND will be the AND of all the array elements. So the task now reduces to check the bitwise-AND of all the array elements and N and if it is zero we will print YES otherwise NO.Below is the implementation of the above approach:
C++
Java
Python 3
C#
PHP
Javascript
// C++ program to check whether bitwise AND of a number// with any subset of an array is zero or not#include <bits/stdc++.h>using namespace std; // Function to check whether bitwise AND of a number// with any subset of an array is zero or notvoid isSubsetAndZero(int array[], int length, int N){ // variable to store the // AND of all the elements int arrAnd = array[0]; // find the AND of all the elements // of the array for (int i = 1; i < length; i++) { arrAnd = arrAnd & array[i]; } // if the AND of all the array elements // and N is equal to zero if ((arrAnd & N) == 0) cout << "YES" << endl; else cout << "NO" << endl;} // Driver Codeint main(){ int array[] = { 1, 2, 4 }; int length = sizeof(array) / sizeof(int); int N = 3; isSubsetAndZero(array, length, N);}
// Java program to check whether bitwise AND of a number// with any subset of an array is zero or notimport java.io.*; public class GFG { // Function to check whether bitwise AND of a number// with any subset of an array is zero or notstatic void isSubsetAndZero(int array[], int length, int N){ // variable to store the // AND of all the elements int arrAnd = array[0]; // find the AND of all the elements // of the array for (int i = 1; i < length; i++) { arrAnd = arrAnd & array[i]; } // if the AND of all the array elements // and N is equal to zero if ((arrAnd & N) == 0) System.out.println( "YES"); else System.out.println( "NO");} // Driver Code public static void main (String[] args) { int array[] = { 1, 2, 4 }; int length = array.length; int N = 3; isSubsetAndZero(array, length, N); }}//This code is contributed by shs..
# Python 3 program to check whether# bitwise AND of a number with any# subset of an array is zero or not # Function to check whether bitwise# AND of a number with any subset# of an array is zero or notdef isSubsetAndZero(array, length, N): # variable to store the # AND of all the elements arrAnd = array[0] # find the AND of all # the elements of the array for i in range(1, length) : arrAnd = arrAnd & array[i] # if the AND of all the array # elements and N is equal to zero if ((arrAnd & N) == 0): print("YES") else: print("NO") # Driver Codeif __name__ == "__main__": array = [ 1, 2, 4 ] length = len(array) N = 3 isSubsetAndZero(array, length, N) # This code is contributed# by ChitraNayal
// C# program to check whether// bitwise AND of a number with// any subset of an array is zero or notusing System; class GFG{ // Function to check whether bitwise// AND of a number with any subset// of an array is zero or notstatic void isSubsetAndZero(int []array, int length, int N){ // variable to store the // AND of all the elements int arrAnd = array[0]; // find the AND of all the // elements of the array for (int i = 1; i < length; i++) { arrAnd = arrAnd & array[i]; } // if the AND of all the array // elements and N is equal to zero if ((arrAnd & N) == 0) Console.WriteLine( "YES"); else Console.WriteLine( "NO");} // Driver Codepublic static void Main (){ int []array = { 1, 2, 4 }; int length = array.Length; int N = 3; isSubsetAndZero(array, length, N);}} // This code is contributed// by inder_verma
<?php// PHP program to check whether// bitwise AND of a number with// any subset of an array is zero or not // Function to check whether// bitwise AND of a number with// any subset of an array is zero or notfunction isSubsetAndZero($array, $length, $N){ // variable to store the // AND of all the elements $arrAnd = $array[0]; // find the AND of all the // elements of the array for ($i = 1; $i <$length; $i++) { $arrAnd = $arrAnd & $array[$i]; } // if the AND of all the array // elements and N is equal to zero if (($arrAnd & $N) == 0) echo("YES"); else echo("NO");} // Driver Code$array = array( 1, 2, 4 );$length = count($array); $N = 3; isSubsetAndZero($array, $length, $N); // This code is contributed// by Shashank?>
<script> // Javascript implementation of the above approach // Function to check whether bitwise AND of a number// with any subset of an array is zero or notfunction isSubsetAndZero(array, len, N){ // variable to store the // AND of all the elements var arrAnd = array[0]; // find the AND of all the elements // of the array for (var i = 1; i < len; i++) { arrAnd = arrAnd & array[i]; } // if the AND of all the array elements // and N is equal to zero if ((arrAnd & N) == 0) document.write("YES"+"<br>"); else document.write("NO"+"<br>");} var array = [1, 2, 4 ];var len = array.length;var N = 3;isSubsetAndZero(array, len, N); // This code is contributed by SoumikMondal </script>
YES
Shashank12
inderDuMCA
ukasp
SoumikMondal
surinderdawra388
Bitwise-AND
subset
Bit Magic
Competitive Programming
Bit Magic
subset
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to find whether a given number is power of 2
Little and Big Endian Mystery
Binary representation of a given number
Josephus problem | Set 1 (A O(n) Solution)
Divide two integers without using multiplication, division and mod operator
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Modulo 10^9+7 (1000000007)
Prefix Sum Array - Implementation and Applications in Competitive Programming
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Mar, 2022"
},
{
"code": null,
"e": 218,
"s": 52,
"text": "Given an array and a Number N. The task is to check whether there exists any subset of this array such that the bitwise AND of this subset with N is zero.Examples: "
},
{
"code": null,
"e": 374,
"s": 218,
"text": "Input : arr[] = {1, 2, 4} ; N = 3\nOutput : YES\nExplanation: The subsets are:\n(1, 2 ), (1, 4), (1, 2, 4) \n\nInput : arr[] = {1, 1, 1} ; N = 3\nOutput : NO"
},
{
"code": null,
"e": 1108,
"s": 376,
"text": "A Simple Approach is to find the bitwise-AND of all the subsets of the array and check whether the AND of N with any subset is zero or not.An Efficient Approach is to observe that bitwise-AND of any two numbers will always produce a number less than or equal to the smaller number. So our task is to find the subset which has the minimum value of bitwise AND. So as stated earlier the AND of any two numbers will always produce a number less than or equal to the minimum number so the minimum value of AND will be the AND of all the array elements. So the task now reduces to check the bitwise-AND of all the array elements and N and if it is zero we will print YES otherwise NO.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1112,
"s": 1108,
"text": "C++"
},
{
"code": null,
"e": 1117,
"s": 1112,
"text": "Java"
},
{
"code": null,
"e": 1126,
"s": 1117,
"text": "Python 3"
},
{
"code": null,
"e": 1129,
"s": 1126,
"text": "C#"
},
{
"code": null,
"e": 1133,
"s": 1129,
"text": "PHP"
},
{
"code": null,
"e": 1144,
"s": 1133,
"text": "Javascript"
},
{
"code": "// C++ program to check whether bitwise AND of a number// with any subset of an array is zero or not#include <bits/stdc++.h>using namespace std; // Function to check whether bitwise AND of a number// with any subset of an array is zero or notvoid isSubsetAndZero(int array[], int length, int N){ // variable to store the // AND of all the elements int arrAnd = array[0]; // find the AND of all the elements // of the array for (int i = 1; i < length; i++) { arrAnd = arrAnd & array[i]; } // if the AND of all the array elements // and N is equal to zero if ((arrAnd & N) == 0) cout << \"YES\" << endl; else cout << \"NO\" << endl;} // Driver Codeint main(){ int array[] = { 1, 2, 4 }; int length = sizeof(array) / sizeof(int); int N = 3; isSubsetAndZero(array, length, N);}",
"e": 1984,
"s": 1144,
"text": null
},
{
"code": "// Java program to check whether bitwise AND of a number// with any subset of an array is zero or notimport java.io.*; public class GFG { // Function to check whether bitwise AND of a number// with any subset of an array is zero or notstatic void isSubsetAndZero(int array[], int length, int N){ // variable to store the // AND of all the elements int arrAnd = array[0]; // find the AND of all the elements // of the array for (int i = 1; i < length; i++) { arrAnd = arrAnd & array[i]; } // if the AND of all the array elements // and N is equal to zero if ((arrAnd & N) == 0) System.out.println( \"YES\"); else System.out.println( \"NO\");} // Driver Code public static void main (String[] args) { int array[] = { 1, 2, 4 }; int length = array.length; int N = 3; isSubsetAndZero(array, length, N); }}//This code is contributed by shs..",
"e": 2898,
"s": 1984,
"text": null
},
{
"code": "# Python 3 program to check whether# bitwise AND of a number with any# subset of an array is zero or not # Function to check whether bitwise# AND of a number with any subset# of an array is zero or notdef isSubsetAndZero(array, length, N): # variable to store the # AND of all the elements arrAnd = array[0] # find the AND of all # the elements of the array for i in range(1, length) : arrAnd = arrAnd & array[i] # if the AND of all the array # elements and N is equal to zero if ((arrAnd & N) == 0): print(\"YES\") else: print(\"NO\") # Driver Codeif __name__ == \"__main__\": array = [ 1, 2, 4 ] length = len(array) N = 3 isSubsetAndZero(array, length, N) # This code is contributed# by ChitraNayal",
"e": 3661,
"s": 2898,
"text": null
},
{
"code": "// C# program to check whether// bitwise AND of a number with// any subset of an array is zero or notusing System; class GFG{ // Function to check whether bitwise// AND of a number with any subset// of an array is zero or notstatic void isSubsetAndZero(int []array, int length, int N){ // variable to store the // AND of all the elements int arrAnd = array[0]; // find the AND of all the // elements of the array for (int i = 1; i < length; i++) { arrAnd = arrAnd & array[i]; } // if the AND of all the array // elements and N is equal to zero if ((arrAnd & N) == 0) Console.WriteLine( \"YES\"); else Console.WriteLine( \"NO\");} // Driver Codepublic static void Main (){ int []array = { 1, 2, 4 }; int length = array.Length; int N = 3; isSubsetAndZero(array, length, N);}} // This code is contributed// by inder_verma",
"e": 4584,
"s": 3661,
"text": null
},
{
"code": "<?php// PHP program to check whether// bitwise AND of a number with// any subset of an array is zero or not // Function to check whether// bitwise AND of a number with// any subset of an array is zero or notfunction isSubsetAndZero($array, $length, $N){ // variable to store the // AND of all the elements $arrAnd = $array[0]; // find the AND of all the // elements of the array for ($i = 1; $i <$length; $i++) { $arrAnd = $arrAnd & $array[$i]; } // if the AND of all the array // elements and N is equal to zero if (($arrAnd & $N) == 0) echo(\"YES\"); else echo(\"NO\");} // Driver Code$array = array( 1, 2, 4 );$length = count($array); $N = 3; isSubsetAndZero($array, $length, $N); // This code is contributed// by Shashank?>",
"e": 5367,
"s": 4584,
"text": null
},
{
"code": "<script> // Javascript implementation of the above approach // Function to check whether bitwise AND of a number// with any subset of an array is zero or notfunction isSubsetAndZero(array, len, N){ // variable to store the // AND of all the elements var arrAnd = array[0]; // find the AND of all the elements // of the array for (var i = 1; i < len; i++) { arrAnd = arrAnd & array[i]; } // if the AND of all the array elements // and N is equal to zero if ((arrAnd & N) == 0) document.write(\"YES\"+\"<br>\"); else document.write(\"NO\"+\"<br>\");} var array = [1, 2, 4 ];var len = array.length;var N = 3;isSubsetAndZero(array, len, N); // This code is contributed by SoumikMondal </script>",
"e": 6109,
"s": 5367,
"text": null
},
{
"code": null,
"e": 6113,
"s": 6109,
"text": "YES"
},
{
"code": null,
"e": 6126,
"s": 6115,
"text": "Shashank12"
},
{
"code": null,
"e": 6137,
"s": 6126,
"text": "inderDuMCA"
},
{
"code": null,
"e": 6143,
"s": 6137,
"text": "ukasp"
},
{
"code": null,
"e": 6156,
"s": 6143,
"text": "SoumikMondal"
},
{
"code": null,
"e": 6173,
"s": 6156,
"text": "surinderdawra388"
},
{
"code": null,
"e": 6185,
"s": 6173,
"text": "Bitwise-AND"
},
{
"code": null,
"e": 6192,
"s": 6185,
"text": "subset"
},
{
"code": null,
"e": 6202,
"s": 6192,
"text": "Bit Magic"
},
{
"code": null,
"e": 6226,
"s": 6202,
"text": "Competitive Programming"
},
{
"code": null,
"e": 6236,
"s": 6226,
"text": "Bit Magic"
},
{
"code": null,
"e": 6243,
"s": 6236,
"text": "subset"
},
{
"code": null,
"e": 6341,
"s": 6243,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6394,
"s": 6341,
"text": "Program to find whether a given number is power of 2"
},
{
"code": null,
"e": 6424,
"s": 6394,
"text": "Little and Big Endian Mystery"
},
{
"code": null,
"e": 6464,
"s": 6424,
"text": "Binary representation of a given number"
},
{
"code": null,
"e": 6507,
"s": 6464,
"text": "Josephus problem | Set 1 (A O(n) Solution)"
},
{
"code": null,
"e": 6583,
"s": 6507,
"text": "Divide two integers without using multiplication, division and mod operator"
},
{
"code": null,
"e": 6626,
"s": 6583,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 6669,
"s": 6626,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 6710,
"s": 6669,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 6737,
"s": 6710,
"text": "Modulo 10^9+7 (1000000007)"
}
] |
JavaScript Array fill() Method
|
12 Oct, 2021
Below is the example of the Array fill() method to fill with a single digit.
Example:
JavaScript
<script> // JavaScript code for fill() method function func() { var arr = [1, 23, 46, 58]; // fill array with 87 arr.fill(87); document.write(arr); } func();</script>
Output:
[87, 87, 87, 87]
The arr.fill() method is used to fill the array with a given static value. The value can be used to fill the entire array or it can be used to fill a part of the array. Syntax:
arr.fill(value, start, end)
Parameters: This method accepts three parameters as mentioned above and described below:
value: It defines the static value with which the array elements are to be replaced.
start (Optional): It defines the starting index from where the array is to be filled with the static value. If this value is not defined the starting index is taken as 0. If start is negative then the net start index is length+start.
end (Optional): This argument defines the last index up to which the array is to be filled with the static value. If this value is not defined then by default the last index of the i.e arr.length – 1 is taken as the end value. If the end is negative, then the net end is defined as length+end.
Return value: This method does not return a new array. Instead of it modifies the array on which this method is applied.Below examples illustrate the Array fill() method in JavaScript:
Example 1: In this example the method fill() fills the entire array with 87, replacing all the initial values present in the array.
var arr = [1, 23, 46, 58];
arr.fill(87);
Output:
[87, 87, 87, 87]
Example 2: In this example the method fill() fills the array from index 1 to 2 one less than the upper index with 87, replacing all the initial values present in the array.
var arr = [1, 23, 46, 58];
arr.fill(87, 1, 3);
Output:
[1, 87, 87, 58]
Example 3: In this example the method fill() fills the array from index 1 to 3 with 87, replacing all the initial values present in the array.
var arr = [1, 23, 46, 58];
arr.fill(87, 2);
Output:
[1, 23, 87, 87]
Codes for the above method are defined as follows:Program 1:
JavaScript
<script> // JavaScript code for fill() method function func() { var arr = [1, 23, 46, 58]; // Here value = 87, start index=1 arr.fill(87, 2); document.write(arr); } func();</script>
Output:
[1, 23, 87, 87]
Program 2:
JavaScript
<script> // JavaScript code for fill() method function func() { var arr = [1, 23, 46, 58]; // here value = 87, start index=1 and // and last index = 3 arr.fill(87, 1, 3); document.write(arr); } func();</script>
Output:
[1, 87, 87, 58]
Supported Browsers: The browsers supported by JavaScript Array fill() method are listed below:
Google Chrome 45.0
Microsoft Edge 12.0
Mozilla Firefox 31.0
Safari 7.1
Opera 32.0
nidhi_biet
Akanksha_Rai
as5853535
sumitgumber28
javascript-array
JavaScript-Methods
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to Open URL in New Tab using JavaScript ?
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": 28,
"s": 0,
"text": "\n12 Oct, 2021"
},
{
"code": null,
"e": 107,
"s": 28,
"text": "Below is the example of the Array fill() method to fill with a single digit. "
},
{
"code": null,
"e": 118,
"s": 107,
"text": "Example: "
},
{
"code": null,
"e": 129,
"s": 118,
"text": "JavaScript"
},
{
"code": "<script> // JavaScript code for fill() method function func() { var arr = [1, 23, 46, 58]; // fill array with 87 arr.fill(87); document.write(arr); } func();</script>",
"e": 337,
"s": 129,
"text": null
},
{
"code": null,
"e": 347,
"s": 337,
"text": "Output: "
},
{
"code": null,
"e": 364,
"s": 347,
"text": "[87, 87, 87, 87]"
},
{
"code": null,
"e": 543,
"s": 364,
"text": "The arr.fill() method is used to fill the array with a given static value. The value can be used to fill the entire array or it can be used to fill a part of the array. Syntax: "
},
{
"code": null,
"e": 571,
"s": 543,
"text": "arr.fill(value, start, end)"
},
{
"code": null,
"e": 662,
"s": 571,
"text": "Parameters: This method accepts three parameters as mentioned above and described below: "
},
{
"code": null,
"e": 747,
"s": 662,
"text": "value: It defines the static value with which the array elements are to be replaced."
},
{
"code": null,
"e": 981,
"s": 747,
"text": "start (Optional): It defines the starting index from where the array is to be filled with the static value. If this value is not defined the starting index is taken as 0. If start is negative then the net start index is length+start."
},
{
"code": null,
"e": 1275,
"s": 981,
"text": "end (Optional): This argument defines the last index up to which the array is to be filled with the static value. If this value is not defined then by default the last index of the i.e arr.length – 1 is taken as the end value. If the end is negative, then the net end is defined as length+end."
},
{
"code": null,
"e": 1461,
"s": 1275,
"text": "Return value: This method does not return a new array. Instead of it modifies the array on which this method is applied.Below examples illustrate the Array fill() method in JavaScript: "
},
{
"code": null,
"e": 1594,
"s": 1461,
"text": "Example 1: In this example the method fill() fills the entire array with 87, replacing all the initial values present in the array. "
},
{
"code": null,
"e": 1636,
"s": 1594,
"text": "var arr = [1, 23, 46, 58];\narr.fill(87); "
},
{
"code": null,
"e": 1646,
"s": 1636,
"text": "Output: "
},
{
"code": null,
"e": 1663,
"s": 1646,
"text": "[87, 87, 87, 87]"
},
{
"code": null,
"e": 1838,
"s": 1663,
"text": "Example 2: In this example the method fill() fills the array from index 1 to 2 one less than the upper index with 87, replacing all the initial values present in the array. "
},
{
"code": null,
"e": 1886,
"s": 1838,
"text": "var arr = [1, 23, 46, 58];\narr.fill(87, 1, 3); "
},
{
"code": null,
"e": 1896,
"s": 1886,
"text": "Output: "
},
{
"code": null,
"e": 1912,
"s": 1896,
"text": "[1, 87, 87, 58]"
},
{
"code": null,
"e": 2056,
"s": 1912,
"text": "Example 3: In this example the method fill() fills the array from index 1 to 3 with 87, replacing all the initial values present in the array. "
},
{
"code": null,
"e": 2101,
"s": 2056,
"text": "var arr = [1, 23, 46, 58];\narr.fill(87, 2); "
},
{
"code": null,
"e": 2111,
"s": 2101,
"text": "Output: "
},
{
"code": null,
"e": 2127,
"s": 2111,
"text": "[1, 23, 87, 87]"
},
{
"code": null,
"e": 2190,
"s": 2127,
"text": "Codes for the above method are defined as follows:Program 1: "
},
{
"code": null,
"e": 2201,
"s": 2190,
"text": "JavaScript"
},
{
"code": "<script> // JavaScript code for fill() method function func() { var arr = [1, 23, 46, 58]; // Here value = 87, start index=1 arr.fill(87, 2); document.write(arr); } func();</script>",
"e": 2425,
"s": 2201,
"text": null
},
{
"code": null,
"e": 2435,
"s": 2425,
"text": "Output: "
},
{
"code": null,
"e": 2451,
"s": 2435,
"text": "[1, 23, 87, 87]"
},
{
"code": null,
"e": 2464,
"s": 2451,
"text": "Program 2: "
},
{
"code": null,
"e": 2475,
"s": 2464,
"text": "JavaScript"
},
{
"code": "<script> // JavaScript code for fill() method function func() { var arr = [1, 23, 46, 58]; // here value = 87, start index=1 and // and last index = 3 arr.fill(87, 1, 3); document.write(arr); } func();</script>",
"e": 2735,
"s": 2475,
"text": null
},
{
"code": null,
"e": 2745,
"s": 2735,
"text": "Output: "
},
{
"code": null,
"e": 2761,
"s": 2745,
"text": "[1, 87, 87, 58]"
},
{
"code": null,
"e": 2858,
"s": 2761,
"text": "Supported Browsers: The browsers supported by JavaScript Array fill() method are listed below: "
},
{
"code": null,
"e": 2877,
"s": 2858,
"text": "Google Chrome 45.0"
},
{
"code": null,
"e": 2897,
"s": 2877,
"text": "Microsoft Edge 12.0"
},
{
"code": null,
"e": 2918,
"s": 2897,
"text": "Mozilla Firefox 31.0"
},
{
"code": null,
"e": 2929,
"s": 2918,
"text": "Safari 7.1"
},
{
"code": null,
"e": 2940,
"s": 2929,
"text": "Opera 32.0"
},
{
"code": null,
"e": 2953,
"s": 2942,
"text": "nidhi_biet"
},
{
"code": null,
"e": 2966,
"s": 2953,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 2976,
"s": 2966,
"text": "as5853535"
},
{
"code": null,
"e": 2990,
"s": 2976,
"text": "sumitgumber28"
},
{
"code": null,
"e": 3007,
"s": 2990,
"text": "javascript-array"
},
{
"code": null,
"e": 3026,
"s": 3007,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 3037,
"s": 3026,
"text": "JavaScript"
},
{
"code": null,
"e": 3054,
"s": 3037,
"text": "Web Technologies"
},
{
"code": null,
"e": 3152,
"s": 3054,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3213,
"s": 3152,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3285,
"s": 3213,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3325,
"s": 3285,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3366,
"s": 3325,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 3412,
"s": 3366,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 3474,
"s": 3412,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3507,
"s": 3474,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3568,
"s": 3507,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3618,
"s": 3568,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
SQLite - GROUP BY Clause
|
SQLite GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into groups.
GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER BY clause.
Following is the basic syntax of GROUP BY clause. GROUP BY clause must follow the conditions in the WHERE clause and must precede ORDER BY clause if one is used.
SELECT column-list
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2....columnN
ORDER BY column1, column2....columnN
You can use more than one column in the GROUP BY clause. Make sure whatever column you are using to group, that column should be available in the column-list.
Consider COMPANY table with the following records.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
If you want to know the total amount of salary on each customer, then GROUP BY query will be as follows −
sqlite> SELECT NAME, SUM(SALARY) FROM COMPANY GROUP BY NAME;
This will produce the following result −
NAME SUM(SALARY)
---------- -----------
Allen 15000.0
David 85000.0
James 10000.0
Kim 45000.0
Mark 65000.0
Paul 20000.0
Teddy 20000.0
Now, let us create three more records in COMPANY table using the following INSERT statements.
INSERT INTO COMPANY VALUES (8, 'Paul', 24, 'Houston', 20000.00 );
INSERT INTO COMPANY VALUES (9, 'James', 44, 'Norway', 5000.00 );
INSERT INTO COMPANY VALUES (10, 'James', 45, 'Texas', 5000.00 );
Now, our table has the following records with duplicate names.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
8 Paul 24 Houston 20000.0
9 James 44 Norway 5000.0
10 James 45 Texas 5000.0
Again, let us use the same statement to group-by all the records using NAME column as follows −
sqlite> SELECT NAME, SUM(SALARY) FROM COMPANY GROUP BY NAME ORDER BY NAME;
This will produce the following result.
NAME SUM(SALARY)
---------- -----------
Allen 15000
David 85000
James 20000
Kim 45000
Mark 65000
Paul 40000
Teddy 20000
Let us use ORDER BY clause along with GROUP BY clause as follows −
sqlite> SELECT NAME, SUM(SALARY)
FROM COMPANY GROUP BY NAME ORDER BY NAME DESC;
This will produce the following result.
|
[
{
"code": null,
"e": 2886,
"s": 2772,
"text": "SQLite GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into groups."
},
{
"code": null,
"e": 2983,
"s": 2886,
"text": "GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER BY clause."
},
{
"code": null,
"e": 3145,
"s": 2983,
"text": "Following is the basic syntax of GROUP BY clause. GROUP BY clause must follow the conditions in the WHERE clause and must precede ORDER BY clause if one is used."
},
{
"code": null,
"e": 3276,
"s": 3145,
"text": "SELECT column-list\nFROM table_name\nWHERE [ conditions ]\nGROUP BY column1, column2....columnN\nORDER BY column1, column2....columnN\n"
},
{
"code": null,
"e": 3435,
"s": 3276,
"text": "You can use more than one column in the GROUP BY clause. Make sure whatever column you are using to group, that column should be available in the column-list."
},
{
"code": null,
"e": 3486,
"s": 3435,
"text": "Consider COMPANY table with the following records."
},
{
"code": null,
"e": 3992,
"s": 3486,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 4098,
"s": 3992,
"text": "If you want to know the total amount of salary on each customer, then GROUP BY query will be as follows −"
},
{
"code": null,
"e": 4159,
"s": 4098,
"text": "sqlite> SELECT NAME, SUM(SALARY) FROM COMPANY GROUP BY NAME;"
},
{
"code": null,
"e": 4200,
"s": 4159,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 4389,
"s": 4200,
"text": "NAME SUM(SALARY)\n---------- -----------\nAllen 15000.0\nDavid 85000.0\nJames 10000.0\nKim 45000.0\nMark 65000.0\nPaul 20000.0\nTeddy 20000.0\n"
},
{
"code": null,
"e": 4483,
"s": 4389,
"text": "Now, let us create three more records in COMPANY table using the following INSERT statements."
},
{
"code": null,
"e": 4679,
"s": 4483,
"text": "INSERT INTO COMPANY VALUES (8, 'Paul', 24, 'Houston', 20000.00 );\nINSERT INTO COMPANY VALUES (9, 'James', 44, 'Norway', 5000.00 );\nINSERT INTO COMPANY VALUES (10, 'James', 45, 'Texas', 5000.00 );"
},
{
"code": null,
"e": 4742,
"s": 4679,
"text": "Now, our table has the following records with duplicate names."
},
{
"code": null,
"e": 5414,
"s": 4742,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0\n8 Paul 24 Houston 20000.0\n9 James 44 Norway 5000.0\n10 James 45 Texas 5000.0"
},
{
"code": null,
"e": 5510,
"s": 5414,
"text": "Again, let us use the same statement to group-by all the records using NAME column as follows −"
},
{
"code": null,
"e": 5585,
"s": 5510,
"text": "sqlite> SELECT NAME, SUM(SALARY) FROM COMPANY GROUP BY NAME ORDER BY NAME;"
},
{
"code": null,
"e": 5625,
"s": 5585,
"text": "This will produce the following result."
},
{
"code": null,
"e": 5800,
"s": 5625,
"text": "NAME SUM(SALARY)\n---------- -----------\nAllen 15000\nDavid 85000\nJames 20000\nKim 45000\nMark 65000\nPaul 40000\nTeddy 20000\n"
},
{
"code": null,
"e": 5867,
"s": 5800,
"text": "Let us use ORDER BY clause along with GROUP BY clause as follows −"
},
{
"code": null,
"e": 5952,
"s": 5867,
"text": "sqlite> SELECT NAME, SUM(SALARY) \n FROM COMPANY GROUP BY NAME ORDER BY NAME DESC;"
}
] |
HTTP headers | Access-Control-Allow-Methods
|
08 Jun, 2020
The Access-Control-Allow-Methods header is a Cross-Origin Resource Sharing(CORS) response-type header. It is used to indicate which HTTP methods are permitted while accessing the resources in response to the cross-origin requests.
Syntax:
Access-Control-Allow-Methods: <method>, <method>, ...
OR
Access-Control-Allow-Methods: *
Directives: This header accepts two directive as mentioned above and described below:
<method>: This directive consists of a list of HTTP request methods separated by a comma.
*: This directive is a wildcard value to indicate all the requests lacking credentials like HTTP cookies or HTTP authentication information.
Examples:
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Methods: *
Supported Browsers: The browsers are compatible with HTTP Access-Control-Allow-Methods header are listed below:
Google Chrome
Edge
Opera
Firefox
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Jun, 2020"
},
{
"code": null,
"e": 261,
"s": 28,
"text": "The Access-Control-Allow-Methods header is a Cross-Origin Resource Sharing(CORS) response-type header. It is used to indicate which HTTP methods are permitted while accessing the resources in response to the cross-origin requests. "
},
{
"code": null,
"e": 270,
"s": 261,
"text": "Syntax: "
},
{
"code": null,
"e": 325,
"s": 270,
"text": "Access-Control-Allow-Methods: <method>, <method>, ...\n"
},
{
"code": null,
"e": 328,
"s": 325,
"text": "OR"
},
{
"code": null,
"e": 361,
"s": 328,
"text": "Access-Control-Allow-Methods: *\n"
},
{
"code": null,
"e": 448,
"s": 361,
"text": "Directives: This header accepts two directive as mentioned above and described below:"
},
{
"code": null,
"e": 538,
"s": 448,
"text": "<method>: This directive consists of a list of HTTP request methods separated by a comma."
},
{
"code": null,
"e": 681,
"s": 538,
"text": "*: This directive is a wildcard value to indicate all the requests lacking credentials like HTTP cookies or HTTP authentication information. "
},
{
"code": null,
"e": 692,
"s": 681,
"text": "Examples: "
},
{
"code": null,
"e": 743,
"s": 692,
"text": "Access-Control-Allow-Methods: POST, GET, OPTIONS \n"
},
{
"code": null,
"e": 776,
"s": 743,
"text": "Access-Control-Allow-Methods: *\n"
},
{
"code": null,
"e": 891,
"s": 776,
"text": "Supported Browsers: The browsers are compatible with HTTP Access-Control-Allow-Methods header are listed below: "
},
{
"code": null,
"e": 906,
"s": 891,
"text": "Google Chrome "
},
{
"code": null,
"e": 912,
"s": 906,
"text": "Edge "
},
{
"code": null,
"e": 919,
"s": 912,
"text": "Opera "
},
{
"code": null,
"e": 928,
"s": 919,
"text": "Firefox "
},
{
"code": null,
"e": 941,
"s": 928,
"text": "HTTP-headers"
},
{
"code": null,
"e": 948,
"s": 941,
"text": "Picked"
},
{
"code": null,
"e": 965,
"s": 948,
"text": "Web Technologies"
}
] |
How to use tables to structure forms ?
|
20 Aug, 2021
Creating an HTML form is an important aspect when creating a website. Forms are a method of interacting with the users of the website. Thus it becomes necessary that the forms must be properly aligned and attractive when implemented on a website. The process of simply adding an HTML form to a webpage is as follows.
Example:
HTML
<!DOCTYPE html><html> <body> <h2>Welcome To GFG</h2> <p>Default code has been loaded into the Editor.</p> <form> <label for="name">Name</label> <input type="text" id="name" /> <label for="email">Email</label> <input type="email" id="email" /> <label for="telnum">Tel No.</label> <input type="telnum" id="telnum" /> <label for="Roll No.">Roll No.</label> <input type="number" id="rollno" /> </form></body> </html>
Output: With this code, we have simply created a form within the body of the page. In the output, it can be seen that the form fields and labels are all in one line which does not look good. Even if we use the <br> tag to separate them into different lines, it would still not be properly aligned.
Structuring the form using HTML Tables: We can take the help of HTML tables to structure our forms. The <table> tag not only helps in creating desired tables but can also be used to structure our content such as forms. The below steps show how to use HTML tables to structure forms.
Create an HTML table using the <table> element.
Now add the <form> element within this table.
Next, we will create form fields.
We add the required form fields to the form using the <tr> element that is used to add rows to a table.
We use the <td> element to add labels and fields for separate columns.
We can add as many fields as required to our form.
HTML
<!DOCTYPE html><html> <body> <h2>Welcome To GFG</h2> <p>Default code has been loaded into the Editor.</p> <table> <form> <tr> <td> <label for="name"> Name </label> </td> <td><input type="text" id="name" /> </td> </tr> <tr> <td><label for="email"> Email </label> </td> <td><input type="email" id="email" /> </td> </tr> <tr> <td><label for="telnum"> Tel No. </label> </td> <td><input type="telnum" id="telnum" /> </td> </tr> <tr> <td><label for="Roll No."> Roll No. </label> </td> <td><input type="number" id="rollno" /> </td> </tr> </form> </table></body> </html>
Output: As it is seen in the output that the form fields are appropriately added to new rows and are also properly aligned with the help of HTML tables. It can also be seen that all the input fields are of the same width and length. Thus there is no use in using the CSS to align the form fields.
HTML-Questions
HTML-Tags
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Angular File Upload
Design a web page using HTML and CSS
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n20 Aug, 2021"
},
{
"code": null,
"e": 369,
"s": 52,
"text": "Creating an HTML form is an important aspect when creating a website. Forms are a method of interacting with the users of the website. Thus it becomes necessary that the forms must be properly aligned and attractive when implemented on a website. The process of simply adding an HTML form to a webpage is as follows."
},
{
"code": null,
"e": 378,
"s": 369,
"text": "Example:"
},
{
"code": null,
"e": 383,
"s": 378,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h2>Welcome To GFG</h2> <p>Default code has been loaded into the Editor.</p> <form> <label for=\"name\">Name</label> <input type=\"text\" id=\"name\" /> <label for=\"email\">Email</label> <input type=\"email\" id=\"email\" /> <label for=\"telnum\">Tel No.</label> <input type=\"telnum\" id=\"telnum\" /> <label for=\"Roll No.\">Roll No.</label> <input type=\"number\" id=\"rollno\" /> </form></body> </html>",
"e": 868,
"s": 383,
"text": null
},
{
"code": null,
"e": 1166,
"s": 868,
"text": "Output: With this code, we have simply created a form within the body of the page. In the output, it can be seen that the form fields and labels are all in one line which does not look good. Even if we use the <br> tag to separate them into different lines, it would still not be properly aligned."
},
{
"code": null,
"e": 1449,
"s": 1166,
"text": "Structuring the form using HTML Tables: We can take the help of HTML tables to structure our forms. The <table> tag not only helps in creating desired tables but can also be used to structure our content such as forms. The below steps show how to use HTML tables to structure forms."
},
{
"code": null,
"e": 1497,
"s": 1449,
"text": "Create an HTML table using the <table> element."
},
{
"code": null,
"e": 1543,
"s": 1497,
"text": "Now add the <form> element within this table."
},
{
"code": null,
"e": 1577,
"s": 1543,
"text": "Next, we will create form fields."
},
{
"code": null,
"e": 1681,
"s": 1577,
"text": "We add the required form fields to the form using the <tr> element that is used to add rows to a table."
},
{
"code": null,
"e": 1752,
"s": 1681,
"text": "We use the <td> element to add labels and fields for separate columns."
},
{
"code": null,
"e": 1803,
"s": 1752,
"text": "We can add as many fields as required to our form."
},
{
"code": null,
"e": 1808,
"s": 1803,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h2>Welcome To GFG</h2> <p>Default code has been loaded into the Editor.</p> <table> <form> <tr> <td> <label for=\"name\"> Name </label> </td> <td><input type=\"text\" id=\"name\" /> </td> </tr> <tr> <td><label for=\"email\"> Email </label> </td> <td><input type=\"email\" id=\"email\" /> </td> </tr> <tr> <td><label for=\"telnum\"> Tel No. </label> </td> <td><input type=\"telnum\" id=\"telnum\" /> </td> </tr> <tr> <td><label for=\"Roll No.\"> Roll No. </label> </td> <td><input type=\"number\" id=\"rollno\" /> </td> </tr> </form> </table></body> </html>",
"e": 2916,
"s": 1808,
"text": null
},
{
"code": null,
"e": 3213,
"s": 2916,
"text": "Output: As it is seen in the output that the form fields are appropriately added to new rows and are also properly aligned with the help of HTML tables. It can also be seen that all the input fields are of the same width and length. Thus there is no use in using the CSS to align the form fields."
},
{
"code": null,
"e": 3228,
"s": 3213,
"text": "HTML-Questions"
},
{
"code": null,
"e": 3238,
"s": 3228,
"text": "HTML-Tags"
},
{
"code": null,
"e": 3245,
"s": 3238,
"text": "Picked"
},
{
"code": null,
"e": 3250,
"s": 3245,
"text": "HTML"
},
{
"code": null,
"e": 3267,
"s": 3250,
"text": "Web Technologies"
},
{
"code": null,
"e": 3272,
"s": 3267,
"text": "HTML"
},
{
"code": null,
"e": 3370,
"s": 3272,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3394,
"s": 3370,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 3433,
"s": 3394,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 3472,
"s": 3433,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 3492,
"s": 3472,
"text": "Angular File Upload"
},
{
"code": null,
"e": 3529,
"s": 3492,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 3562,
"s": 3529,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3623,
"s": 3562,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3666,
"s": 3623,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 3738,
"s": 3666,
"text": "Differences between Functional Components and Class Components in React"
}
] |
React-Bootstrap Popover Component
|
30 Apr, 2021
React-Bootstrap is a front-end framework that was designed keeping react in mind. Popover Component is a container-type element that hovers over the parent window. It is just like popup information that is trigger on some event over the parent window. We can use the following approach in ReactJS to use the react-bootstrap Popover Component.
Popover Props:
arrowProps: It is used to position the popover arrow.
content: It is used to create a Popover with a Popover.Content inside and passed directly to children when it is set to true.
id: It is just an HTML id attribute that is necessary for accessibility.
placement: It is used to set the positioned direction of Popover.
popper: It is of object type and indicates the popper property of the popover element.
show: It is used to indicate whether the popover is open or not.
title: It is used to define the title for the popover.
bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS.
PopoverContent Props:
as: It can be used as a custom element type for this component.
bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS.
PopoverTitle Props:
as: It can be used as a custom element type for this component.
bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS.
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 module using the following command:npm install react-bootstrap
npm install bootstrap
Step 3: After creating the ReactJS application, Install the required module using the following command:
npm install react-bootstrap
npm install bootstrap
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react';import 'bootstrap/dist/css/bootstrap.css';import OverlayTrigger from 'react-bootstrap/OverlayTrigger';import Popover from 'react-bootstrap/Popover'import Button from 'react-bootstrap/Button'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Bootstrap Popover Component</h4> <OverlayTrigger placement="bottom" trigger="click" overlay={( <Popover> <Popover.Title as="h3"> GeeksforGeeks </Popover.Title> <Popover.Content> Greetings from GeeksforGeeks </Popover.Content> </Popover> )}> <Button variant="success"> Open Popover </Button> </OverlayTrigger> </div> );}
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.github.io/components/overlays/#popovers
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": "\n30 Apr, 2021"
},
{
"code": null,
"e": 371,
"s": 28,
"text": "React-Bootstrap is a front-end framework that was designed keeping react in mind. Popover Component is a container-type element that hovers over the parent window. It is just like popup information that is trigger on some event over the parent window. We can use the following approach in ReactJS to use the react-bootstrap Popover Component."
},
{
"code": null,
"e": 386,
"s": 371,
"text": "Popover Props:"
},
{
"code": null,
"e": 440,
"s": 386,
"text": "arrowProps: It is used to position the popover arrow."
},
{
"code": null,
"e": 566,
"s": 440,
"text": "content: It is used to create a Popover with a Popover.Content inside and passed directly to children when it is set to true."
},
{
"code": null,
"e": 639,
"s": 566,
"text": "id: It is just an HTML id attribute that is necessary for accessibility."
},
{
"code": null,
"e": 705,
"s": 639,
"text": "placement: It is used to set the positioned direction of Popover."
},
{
"code": null,
"e": 792,
"s": 705,
"text": "popper: It is of object type and indicates the popper property of the popover element."
},
{
"code": null,
"e": 857,
"s": 792,
"text": "show: It is used to indicate whether the popover is open or not."
},
{
"code": null,
"e": 912,
"s": 857,
"text": "title: It is used to define the title for the popover."
},
{
"code": null,
"e": 996,
"s": 912,
"text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS."
},
{
"code": null,
"e": 1018,
"s": 996,
"text": "PopoverContent Props:"
},
{
"code": null,
"e": 1082,
"s": 1018,
"text": "as: It can be used as a custom element type for this component."
},
{
"code": null,
"e": 1166,
"s": 1082,
"text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS."
},
{
"code": null,
"e": 1186,
"s": 1166,
"text": "PopoverTitle Props:"
},
{
"code": null,
"e": 1250,
"s": 1186,
"text": "as: It can be used as a custom element type for this component."
},
{
"code": null,
"e": 1334,
"s": 1250,
"text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS."
},
{
"code": null,
"e": 1384,
"s": 1334,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 1479,
"s": 1384,
"text": "Step 1: Create a React application using the following command:npx create-react-app foldername"
},
{
"code": null,
"e": 1543,
"s": 1479,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 1575,
"s": 1543,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 1688,
"s": 1575,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername"
},
{
"code": null,
"e": 1788,
"s": 1688,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 1802,
"s": 1788,
"text": "cd foldername"
},
{
"code": null,
"e": 1957,
"s": 1802,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install react-bootstrap \nnpm install bootstrap"
},
{
"code": null,
"e": 2062,
"s": 1957,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:"
},
{
"code": null,
"e": 2113,
"s": 2062,
"text": "npm install react-bootstrap \nnpm install bootstrap"
},
{
"code": null,
"e": 2165,
"s": 2113,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 2183,
"s": 2165,
"text": "Project Structure"
},
{
"code": null,
"e": 2313,
"s": 2183,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 2320,
"s": 2313,
"text": "App.js"
},
{
"code": "import React from 'react';import 'bootstrap/dist/css/bootstrap.css';import OverlayTrigger from 'react-bootstrap/OverlayTrigger';import Popover from 'react-bootstrap/Popover'import Button from 'react-bootstrap/Button'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Bootstrap Popover Component</h4> <OverlayTrigger placement=\"bottom\" trigger=\"click\" overlay={( <Popover> <Popover.Title as=\"h3\"> GeeksforGeeks </Popover.Title> <Popover.Content> Greetings from GeeksforGeeks </Popover.Content> </Popover> )}> <Button variant=\"success\"> Open Popover </Button> </OverlayTrigger> </div> );}",
"e": 3170,
"s": 2320,
"text": null
},
{
"code": null,
"e": 3283,
"s": 3170,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 3293,
"s": 3283,
"text": "npm start"
},
{
"code": null,
"e": 3392,
"s": 3293,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 3467,
"s": 3392,
"text": "Reference: https://react-bootstrap.github.io/components/overlays/#popovers"
},
{
"code": null,
"e": 3483,
"s": 3467,
"text": "React-Bootstrap"
},
{
"code": null,
"e": 3491,
"s": 3483,
"text": "ReactJS"
},
{
"code": null,
"e": 3508,
"s": 3491,
"text": "Web Technologies"
}
] |
SQL Joins
|
A JOIN clause is used to combine rows from two or more tables, based on
a related column between them.
Let's look at a selection from the "Orders" table:
Then, look at a selection from the "Customers" table:
Notice that the "CustomerID" column in the "Orders" table refers to the
"CustomerID" in the "Customers" table. The relationship between the two tables above
is the "CustomerID" column.
Then, we can create the following SQL statement (that contains an
INNER JOIN),
that selects records that have matching values in both tables:
and it will produce something like this:
Here are the different types of the JOINs in SQL:
(INNER) JOIN: Returns records that have matching values in both tables
LEFT (OUTER) JOIN: Returns all records from the left table, and the matched records from the right table
RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched
records from the left table
FULL (OUTER) JOIN: Returns all records when there is a match in either left
or right table
Insert the missing parts in the JOIN clause to join the two tables Orders and Customers,
using the CustomerID field in both tables as the relationship between the two tables.
SELECT *
FROM Orders
LEFT JOIN Customers
=;
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 104,
"s": 0,
"text": "A JOIN clause is used to combine rows from two or more tables, based on \na related column between them."
},
{
"code": null,
"e": 155,
"s": 104,
"text": "Let's look at a selection from the \"Orders\" table:"
},
{
"code": null,
"e": 209,
"s": 155,
"text": "Then, look at a selection from the \"Customers\" table:"
},
{
"code": null,
"e": 396,
"s": 209,
"text": "Notice that the \"CustomerID\" column in the \"Orders\" table refers to the \n\"CustomerID\" in the \"Customers\" table. The relationship between the two tables above \nis the \"CustomerID\" column."
},
{
"code": null,
"e": 540,
"s": 396,
"text": "Then, we can create the following SQL statement (that contains an \nINNER JOIN), \nthat selects records that have matching values in both tables:"
},
{
"code": null,
"e": 581,
"s": 540,
"text": "and it will produce something like this:"
},
{
"code": null,
"e": 631,
"s": 581,
"text": "Here are the different types of the JOINs in SQL:"
},
{
"code": null,
"e": 702,
"s": 631,
"text": "(INNER) JOIN: Returns records that have matching values in both tables"
},
{
"code": null,
"e": 807,
"s": 702,
"text": "LEFT (OUTER) JOIN: Returns all records from the left table, and the matched records from the right table"
},
{
"code": null,
"e": 916,
"s": 807,
"text": "RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched \n records from the left table"
},
{
"code": null,
"e": 1010,
"s": 916,
"text": "FULL (OUTER) JOIN: Returns all records when there is a match in either left \n or right table"
},
{
"code": null,
"e": 1194,
"s": 1019,
"text": "Insert the missing parts in the JOIN clause to join the two tables Orders and Customers,\nusing the CustomerID field in both tables as the relationship between the two tables."
},
{
"code": null,
"e": 1239,
"s": 1194,
"text": "SELECT *\nFROM Orders\nLEFT JOIN Customers\n=;\n"
},
{
"code": null,
"e": 1258,
"s": 1239,
"text": "Start the Exercise"
},
{
"code": null,
"e": 1291,
"s": 1258,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1333,
"s": 1291,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1440,
"s": 1333,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 1459,
"s": 1440,
"text": "[email protected]"
}
] |
Matplotlib.axis.Axis.get_major_ticks() function in Python - GeeksforGeeks
|
03 Jun, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack.
The Axis.get_major_ticks() function in axis module of matplotlib library is used to get the tick instances.
Syntax: Axis.get_major_ticks(self, numticks=None)
Parameters: This method accepts the following parameter.
numticks : This parameter is the number of ticks.
Return value: This method returns the tick instances.
Below examples illustrate the matplotlib.axis.Axis.get_major_ticks() function in matplotlib.axis:
Example 1:
Python3
# Implementation of matplotlib function import numpy as npfrom matplotlib.axis import Axis import matplotlib.pyplot as pltimport matplotlib.ticker as ticker np.random.seed(19680801) fig, ax = plt.subplots()ax.plot(100*np.random.rand(20)) formatter = ticker.FormatStrFormatter('%1.2f')Axis.set_major_formatter(ax.yaxis, formatter) print("Value of get_major_ticks() :")for tick in ax.yaxis.get_major_ticks(2): tick.label1.set_color('green') print(tick) plt.title("Matplotlib.axis.Axis.get_major_ticks()\n\Function Example", fontsize = 12, fontweight ='bold') plt.show()
Output:
Value of get_major_ticks() :
<matplotlib.axis.XTick object at 0x08A46250>
<matplotlib.axis.XTick object at 0x08A46230>
Example 2:
Python3
# Implementation of matplotlib function import numpy as npfrom matplotlib.axis import Axis import matplotlib.pyplot as pltimport matplotlib.ticker as ticker np.random.seed(19680801) fig, ax = plt.subplots()ax.plot(100*np.random.rand(20)) formatter = ticker.FormatStrFormatter('%1.2f')Axis.set_major_formatter(ax.yaxis, formatter) print("Value of get_major_ticks() :")for tick in ax.xaxis.get_major_ticks(): tick.label1.set_color('red') print(tick) plt.title("Matplotlib.axis.Axis.get_major_ticks()\n\Function Example", fontsize = 12, fontweight ='bold') plt.show()
Output:
Value of get_major_ticks() :
<matplotlib.axis.YTick object at 0x07EB79F0>
<matplotlib.axis.YTick object at 0x07EB7670>
<matplotlib.axis.YTick object at 0x07EA8EB0>
<matplotlib.axis.YTick object at 0x090A30B0>
<matplotlib.axis.YTick object at 0x090A32D0>
<matplotlib.axis.YTick object at 0x090A3570>
<matplotlib.axis.YTick object at 0x090A3830>
Matplotlib-Axis Class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Create a Pandas DataFrame from Lists
Python | Get dictionary keys as a list
Enumerate() in Python
Python Dictionary
Bar Plot in Matplotlib
Multithreading in Python | Set 2 (Synchronization)
Python Dictionary keys() method
loops in python
Python - Call function from another file
Ways to filter Pandas DataFrame by column values
|
[
{
"code": null,
"e": 24485,
"s": 24457,
"text": "\n03 Jun, 2020"
},
{
"code": null,
"e": 24706,
"s": 24485,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack."
},
{
"code": null,
"e": 24815,
"s": 24706,
"text": "The Axis.get_major_ticks() function in axis module of matplotlib library is used to get the tick instances. "
},
{
"code": null,
"e": 24867,
"s": 24815,
"text": "Syntax: Axis.get_major_ticks(self, numticks=None) "
},
{
"code": null,
"e": 24925,
"s": 24867,
"text": "Parameters: This method accepts the following parameter. "
},
{
"code": null,
"e": 24975,
"s": 24925,
"text": "numticks : This parameter is the number of ticks."
},
{
"code": null,
"e": 25030,
"s": 24975,
"text": "Return value: This method returns the tick instances. "
},
{
"code": null,
"e": 25128,
"s": 25030,
"text": "Below examples illustrate the matplotlib.axis.Axis.get_major_ticks() function in matplotlib.axis:"
},
{
"code": null,
"e": 25139,
"s": 25128,
"text": "Example 1:"
},
{
"code": null,
"e": 25147,
"s": 25139,
"text": "Python3"
},
{
"code": "# Implementation of matplotlib function import numpy as npfrom matplotlib.axis import Axis import matplotlib.pyplot as pltimport matplotlib.ticker as ticker np.random.seed(19680801) fig, ax = plt.subplots()ax.plot(100*np.random.rand(20)) formatter = ticker.FormatStrFormatter('%1.2f')Axis.set_major_formatter(ax.yaxis, formatter) print(\"Value of get_major_ticks() :\")for tick in ax.yaxis.get_major_ticks(2): tick.label1.set_color('green') print(tick) plt.title(\"Matplotlib.axis.Axis.get_major_ticks()\\n\\Function Example\", fontsize = 12, fontweight ='bold') plt.show()",
"e": 25732,
"s": 25147,
"text": null
},
{
"code": null,
"e": 25742,
"s": 25732,
"text": "Output: "
},
{
"code": null,
"e": 25864,
"s": 25744,
"text": "Value of get_major_ticks() :\n<matplotlib.axis.XTick object at 0x08A46250>\n<matplotlib.axis.XTick object at 0x08A46230>\n"
},
{
"code": null,
"e": 25875,
"s": 25864,
"text": "Example 2:"
},
{
"code": null,
"e": 25883,
"s": 25875,
"text": "Python3"
},
{
"code": "# Implementation of matplotlib function import numpy as npfrom matplotlib.axis import Axis import matplotlib.pyplot as pltimport matplotlib.ticker as ticker np.random.seed(19680801) fig, ax = plt.subplots()ax.plot(100*np.random.rand(20)) formatter = ticker.FormatStrFormatter('%1.2f')Axis.set_major_formatter(ax.yaxis, formatter) print(\"Value of get_major_ticks() :\")for tick in ax.xaxis.get_major_ticks(): tick.label1.set_color('red') print(tick) plt.title(\"Matplotlib.axis.Axis.get_major_ticks()\\n\\Function Example\", fontsize = 12, fontweight ='bold') plt.show()",
"e": 26465,
"s": 25883,
"text": null
},
{
"code": null,
"e": 26475,
"s": 26465,
"text": "Output: "
},
{
"code": null,
"e": 26822,
"s": 26477,
"text": "Value of get_major_ticks() :\n<matplotlib.axis.YTick object at 0x07EB79F0>\n<matplotlib.axis.YTick object at 0x07EB7670>\n<matplotlib.axis.YTick object at 0x07EA8EB0>\n<matplotlib.axis.YTick object at 0x090A30B0>\n<matplotlib.axis.YTick object at 0x090A32D0>\n<matplotlib.axis.YTick object at 0x090A3570>\n<matplotlib.axis.YTick object at 0x090A3830>\n"
},
{
"code": null,
"e": 26846,
"s": 26824,
"text": "Matplotlib-Axis Class"
},
{
"code": null,
"e": 26864,
"s": 26846,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 26871,
"s": 26864,
"text": "Python"
},
{
"code": null,
"e": 26969,
"s": 26871,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26978,
"s": 26969,
"text": "Comments"
},
{
"code": null,
"e": 26991,
"s": 26978,
"text": "Old Comments"
},
{
"code": null,
"e": 27028,
"s": 26991,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27067,
"s": 27028,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27089,
"s": 27067,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27107,
"s": 27089,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27130,
"s": 27107,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 27181,
"s": 27130,
"text": "Multithreading in Python | Set 2 (Synchronization)"
},
{
"code": null,
"e": 27213,
"s": 27181,
"text": "Python Dictionary keys() method"
},
{
"code": null,
"e": 27229,
"s": 27213,
"text": "loops in python"
},
{
"code": null,
"e": 27270,
"s": 27229,
"text": "Python - Call function from another file"
}
] |
How to reload page after specific seconds in jQuery ? - GeeksforGeeks
|
03 Aug, 2021
A page can be reloaded after a specific number of seconds in jQuery using two approaches.
Using location.reload() Method
Using history.go(0) Method
Using location.reload() Method: This method is used to reload the current page imitating the action of the refresh button of the browser. It has an optional Boolean parameter which can be used to denote that the page is reloaded from the server instead of being loaded from the browser cache.
The refresh code can be executed after a certain period of time using the setTimeout() function. This function has a delay parameter which denotes the time after which the function will execute. This value is given in milliseconds. The amount of time in seconds to be delayed in multiplied by 1000 to convert it to milliseconds.
The setTimeout code can be called after the document has finished loading by selecting the document object and using the ready() method on it. This will cause the page to reload after the specified amount of seconds.
Syntax:$(document).ready(function () {
setTimeout(function () {
alert('Reloading Page');
location.reload(true);
}, 5000);
});
$(document).ready(function () {
setTimeout(function () {
alert('Reloading Page');
location.reload(true);
}, 5000);
});
Example:<!DOCTYPE html><html><head> <title> How to reload page after specific seconds? </title></head><body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to reload page after specific seconds? </b> <p> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. </p> <p> The page will be reloaded in 5 seconds. </p> <script src="https://code.jquery.com/jquery-3.3.1.min.js"> </script> <script type="text/javascript"> $(document).ready(function () { setTimeout(function () { alert('Reloading Page'); location.reload(true); }, 5000); }); </script></body></html>
<!DOCTYPE html><html><head> <title> How to reload page after specific seconds? </title></head><body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to reload page after specific seconds? </b> <p> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. </p> <p> The page will be reloaded in 5 seconds. </p> <script src="https://code.jquery.com/jquery-3.3.1.min.js"> </script> <script type="text/javascript"> $(document).ready(function () { setTimeout(function () { alert('Reloading Page'); location.reload(true); }, 5000); }); </script></body></html>
Output:After loading the page:After 5 seconds:
After 5 seconds:
Using history.go(0) Method: This method loads a URL from the browser’s history depending on the parameter passed to it. If the parameter passed is ‘0’, it reloads the current page.
The refresh code can be executed after a certain period of time using the setTimeout() function. This function has a delay parameter which denotes the time after which the function will execute. This value is given in milliseconds. The amount of time in seconds to be delayed in multiplied by 1000 to convert it to milliseconds.
This code can be called after the document has finished loading by selecting the document object and using the ready() method on it. This will cause the page to reload after the specified amount of seconds.
Syntax:$(document).ready(function () {
setTimeout(function () {
alert('Reloading Page');
history.go(0);
}, 5000);
});
$(document).ready(function () {
setTimeout(function () {
alert('Reloading Page');
history.go(0);
}, 5000);
});
Example:<!DOCTYPE html><html><head> <title> How to reload page after specific seconds? </title></head><body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to reload page after specific seconds? </b> <p> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. </p> <p> The page will be reloaded in 5 seconds. </p> <script src="https://code.jquery.com/jquery-3.3.1.min.js"> </script> <script type="text/javascript"> $(document).ready(function () { setTimeout(function () { alert('Reloading Page'); history.go(0); }, 5000); }); </script></body></html>Output:
<!DOCTYPE html><html><head> <title> How to reload page after specific seconds? </title></head><body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to reload page after specific seconds? </b> <p> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. </p> <p> The page will be reloaded in 5 seconds. </p> <script src="https://code.jquery.com/jquery-3.3.1.min.js"> </script> <script type="text/javascript"> $(document).ready(function () { setTimeout(function () { alert('Reloading Page'); history.go(0); }, 5000); }); </script></body></html>
Output:
After loading the page:After 5 seconds:
jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.
jQuery-Misc
Picked
JQuery
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Scroll to the top of the page using JavaScript/jQuery
How to get the ID of the clicked button using JavaScript / jQuery ?
jQuery | children() with Examples
How to redirect to a particular section of a page using HTML or jQuery?
How to prevent Body from scrolling when a modal is opened using jQuery ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24555,
"s": 24527,
"text": "\n03 Aug, 2021"
},
{
"code": null,
"e": 24645,
"s": 24555,
"text": "A page can be reloaded after a specific number of seconds in jQuery using two approaches."
},
{
"code": null,
"e": 24676,
"s": 24645,
"text": "Using location.reload() Method"
},
{
"code": null,
"e": 24703,
"s": 24676,
"text": "Using history.go(0) Method"
},
{
"code": null,
"e": 24996,
"s": 24703,
"text": "Using location.reload() Method: This method is used to reload the current page imitating the action of the refresh button of the browser. It has an optional Boolean parameter which can be used to denote that the page is reloaded from the server instead of being loaded from the browser cache."
},
{
"code": null,
"e": 25325,
"s": 24996,
"text": "The refresh code can be executed after a certain period of time using the setTimeout() function. This function has a delay parameter which denotes the time after which the function will execute. This value is given in milliseconds. The amount of time in seconds to be delayed in multiplied by 1000 to convert it to milliseconds."
},
{
"code": null,
"e": 25542,
"s": 25325,
"text": "The setTimeout code can be called after the document has finished loading by selecting the document object and using the ready() method on it. This will cause the page to reload after the specified amount of seconds."
},
{
"code": null,
"e": 25700,
"s": 25542,
"text": "Syntax:$(document).ready(function () {\n setTimeout(function () {\n alert('Reloading Page');\n location.reload(true);\n }, 5000);\n });"
},
{
"code": null,
"e": 25851,
"s": 25700,
"text": "$(document).ready(function () {\n setTimeout(function () {\n alert('Reloading Page');\n location.reload(true);\n }, 5000);\n });"
},
{
"code": null,
"e": 26609,
"s": 25851,
"text": "Example:<!DOCTYPE html><html><head> <title> How to reload page after specific seconds? </title></head><body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to reload page after specific seconds? </b> <p> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. </p> <p> The page will be reloaded in 5 seconds. </p> <script src=\"https://code.jquery.com/jquery-3.3.1.min.js\"> </script> <script type=\"text/javascript\"> $(document).ready(function () { setTimeout(function () { alert('Reloading Page'); location.reload(true); }, 5000); }); </script></body></html>"
},
{
"code": "<!DOCTYPE html><html><head> <title> How to reload page after specific seconds? </title></head><body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to reload page after specific seconds? </b> <p> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. </p> <p> The page will be reloaded in 5 seconds. </p> <script src=\"https://code.jquery.com/jquery-3.3.1.min.js\"> </script> <script type=\"text/javascript\"> $(document).ready(function () { setTimeout(function () { alert('Reloading Page'); location.reload(true); }, 5000); }); </script></body></html>",
"e": 27359,
"s": 26609,
"text": null
},
{
"code": null,
"e": 27406,
"s": 27359,
"text": "Output:After loading the page:After 5 seconds:"
},
{
"code": null,
"e": 27423,
"s": 27406,
"text": "After 5 seconds:"
},
{
"code": null,
"e": 27604,
"s": 27423,
"text": "Using history.go(0) Method: This method loads a URL from the browser’s history depending on the parameter passed to it. If the parameter passed is ‘0’, it reloads the current page."
},
{
"code": null,
"e": 27933,
"s": 27604,
"text": "The refresh code can be executed after a certain period of time using the setTimeout() function. This function has a delay parameter which denotes the time after which the function will execute. This value is given in milliseconds. The amount of time in seconds to be delayed in multiplied by 1000 to convert it to milliseconds."
},
{
"code": null,
"e": 28140,
"s": 27933,
"text": "This code can be called after the document has finished loading by selecting the document object and using the ready() method on it. This will cause the page to reload after the specified amount of seconds."
},
{
"code": null,
"e": 28290,
"s": 28140,
"text": "Syntax:$(document).ready(function () {\n setTimeout(function () {\n alert('Reloading Page');\n history.go(0);\n }, 5000);\n });"
},
{
"code": null,
"e": 28433,
"s": 28290,
"text": "$(document).ready(function () {\n setTimeout(function () {\n alert('Reloading Page');\n history.go(0);\n }, 5000);\n });"
},
{
"code": null,
"e": 29191,
"s": 28433,
"text": "Example:<!DOCTYPE html><html><head> <title> How to reload page after specific seconds? </title></head><body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to reload page after specific seconds? </b> <p> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. </p> <p> The page will be reloaded in 5 seconds. </p> <script src=\"https://code.jquery.com/jquery-3.3.1.min.js\"> </script> <script type=\"text/javascript\"> $(document).ready(function () { setTimeout(function () { alert('Reloading Page'); history.go(0); }, 5000); }); </script></body></html>Output:"
},
{
"code": "<!DOCTYPE html><html><head> <title> How to reload page after specific seconds? </title></head><body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to reload page after specific seconds? </b> <p> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. </p> <p> The page will be reloaded in 5 seconds. </p> <script src=\"https://code.jquery.com/jquery-3.3.1.min.js\"> </script> <script type=\"text/javascript\"> $(document).ready(function () { setTimeout(function () { alert('Reloading Page'); history.go(0); }, 5000); }); </script></body></html>",
"e": 29934,
"s": 29191,
"text": null
},
{
"code": null,
"e": 29942,
"s": 29934,
"text": "Output:"
},
{
"code": null,
"e": 29982,
"s": 29942,
"text": "After loading the page:After 5 seconds:"
},
{
"code": null,
"e": 30250,
"s": 29982,
"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": 30262,
"s": 30250,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 30269,
"s": 30262,
"text": "Picked"
},
{
"code": null,
"e": 30276,
"s": 30269,
"text": "JQuery"
},
{
"code": null,
"e": 30293,
"s": 30276,
"text": "Web Technologies"
},
{
"code": null,
"e": 30320,
"s": 30293,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 30418,
"s": 30320,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30427,
"s": 30418,
"text": "Comments"
},
{
"code": null,
"e": 30440,
"s": 30427,
"text": "Old Comments"
},
{
"code": null,
"e": 30494,
"s": 30440,
"text": "Scroll to the top of the page using JavaScript/jQuery"
},
{
"code": null,
"e": 30562,
"s": 30494,
"text": "How to get the ID of the clicked button using JavaScript / jQuery ?"
},
{
"code": null,
"e": 30596,
"s": 30562,
"text": "jQuery | children() with Examples"
},
{
"code": null,
"e": 30668,
"s": 30596,
"text": "How to redirect to a particular section of a page using HTML or jQuery?"
},
{
"code": null,
"e": 30741,
"s": 30668,
"text": "How to prevent Body from scrolling when a modal is opened using jQuery ?"
},
{
"code": null,
"e": 30797,
"s": 30741,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 30830,
"s": 30797,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30892,
"s": 30830,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 30935,
"s": 30892,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Sorting arrays using bubble sort in JavaScript
|
We are required to write a JavaScript function that takes in an array of literals and sorts it using bubble sort.
The code for this will be −
const arr = [4, 56, 4, 23, 8, 4, 23, 2, 7, 8, 8, 45];
const swap = (items, firstIndex, secondIndex) => {
var temp = items[firstIndex];
items[firstIndex] = items[secondIndex];
items[secondIndex] = temp;
};
const bubbleSort = items => {
var len = items.length,
i, j;
for (i=len-1; i >= 0; i--){
for (j=len-i; j >= 0; j--){
if (items[j] < items[j-1]){
swap(items, j, j-1);
}
}
}
return items;
};
console.log(bubbleSort(arr));
The output in the console −
[
2, 4, 4, 4, 7,
8, 8, 8, 23, 23,
45, 56
]
|
[
{
"code": null,
"e": 1176,
"s": 1062,
"text": "We are required to write a JavaScript function that takes in an array of literals and sorts it using bubble sort."
},
{
"code": null,
"e": 1204,
"s": 1176,
"text": "The code for this will be −"
},
{
"code": null,
"e": 1693,
"s": 1204,
"text": "const arr = [4, 56, 4, 23, 8, 4, 23, 2, 7, 8, 8, 45];\nconst swap = (items, firstIndex, secondIndex) => {\n var temp = items[firstIndex];\n items[firstIndex] = items[secondIndex];\n items[secondIndex] = temp;\n};\nconst bubbleSort = items => {\n var len = items.length,\n i, j;\n for (i=len-1; i >= 0; i--){\n for (j=len-i; j >= 0; j--){\n if (items[j] < items[j-1]){\n swap(items, j, j-1);\n }\n }\n }\n return items;\n};\nconsole.log(bubbleSort(arr));"
},
{
"code": null,
"e": 1721,
"s": 1693,
"text": "The output in the console −"
},
{
"code": null,
"e": 1773,
"s": 1721,
"text": "[\n 2, 4, 4, 4, 7,\n 8, 8, 8, 23, 23,\n 45, 56\n]"
}
] |
Python Fire Module - GeeksforGeeks
|
28 Nov, 2021
Python Fire is a library to create CLI applications. It can automatically generate command line Interfaces from any object in python. It is not limited to this, it is a good tool for debugging and development purposes. With the help of Fire, you can turn existing code into CLI. In this article, we will see the use of fire.
Firstly, there are different installing methods that you can perform according to your choice.
Install using pip:
pip install fire
The Fire works on any Python object including components, dictionaries, lists, tuples, etc.
Here’s an example of calling fire on a function for this we will make a function and call the function in CLI.
Python3
import fire def greeting(name): return "Hello " + name fire.Fire(greeting("World!"))
Output:
Hello World!
Then, from the terminal, you can run using the following commands:
python main.py
There is another way to run this program by setting a function in the Fire function at invoking time. By doing so, we only need to pass arguments at runtime without telling which method to call.
Python3
import fire def hello(name): return "Hello " + name if __name__ == '__main__': fire.Fire(hello)
Output:
Hello world
If you run this in the terminal using the below command, it will give the same result as the above function. Calling Fire consumed name = “World”. Using this method of calling fire, saves from writing the function name with arguments.
python main.py world
Both the ways of calling will give “Hello World” as an output.
Here is an example class created named Square and a method “square” is defined inside it. Once, we call fire on any class, we can access it as a method on the command line directly. We will see how to call this method using the below example,
Python3
import fire class Square(object): def square(self, number): return number*number fire.Fire(Square)
Output:
4
There are two ways to execute this class, the first method is:
python main.py square 2
The second way which will give the same desired output is:
python main.py square --number=2
Both the methods will give the same result = 4.
Fire is convenient as it allows to pass arguments from a command line. In the above example, we invoked the method from the command line and assigned arguments at the same time.
Fire can be used to instantiate classes inside the class, creating a hierarchical view. let’s take an example,
Python3
import fire class Calculator(object): def __init__(self): self.SQUARE = Square() class Square(object): def square(self, number): return number*number def triplet(self,number): return number*number*number fire.Fire(Calculator)
In this way, the Calculator class instantiates the square class and its object is created. The member functions of the instantiated class can be accessed at run time like:
To know more about fire commands associated with a particular object or class use –help flag with the object or class. For Example, shown below, we are querying about the “SQUARE” object, and it shows two commands associated with it – “square” and “triplet”. This means you can only pass these two commands with SQUARE with their parameters.
Fire makes code more readable.
Easy to create command-line Interfaces.
fire.Fire() executes the full content of the program when invoked at the end of a program.
python-modules
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?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 25862,
"s": 25537,
"text": "Python Fire is a library to create CLI applications. It can automatically generate command line Interfaces from any object in python. It is not limited to this, it is a good tool for debugging and development purposes. With the help of Fire, you can turn existing code into CLI. In this article, we will see the use of fire."
},
{
"code": null,
"e": 25958,
"s": 25862,
"text": "Firstly, there are different installing methods that you can perform according to your choice. "
},
{
"code": null,
"e": 25977,
"s": 25958,
"text": "Install using pip:"
},
{
"code": null,
"e": 25994,
"s": 25977,
"text": "pip install fire"
},
{
"code": null,
"e": 26087,
"s": 25994,
"text": "The Fire works on any Python object including components, dictionaries, lists, tuples, etc. "
},
{
"code": null,
"e": 26198,
"s": 26087,
"text": "Here’s an example of calling fire on a function for this we will make a function and call the function in CLI."
},
{
"code": null,
"e": 26206,
"s": 26198,
"text": "Python3"
},
{
"code": "import fire def greeting(name): return \"Hello \" + name fire.Fire(greeting(\"World!\"))",
"e": 26296,
"s": 26206,
"text": null
},
{
"code": null,
"e": 26304,
"s": 26296,
"text": "Output:"
},
{
"code": null,
"e": 26317,
"s": 26304,
"text": "Hello World!"
},
{
"code": null,
"e": 26384,
"s": 26317,
"text": "Then, from the terminal, you can run using the following commands:"
},
{
"code": null,
"e": 26400,
"s": 26384,
"text": " python main.py"
},
{
"code": null,
"e": 26595,
"s": 26400,
"text": "There is another way to run this program by setting a function in the Fire function at invoking time. By doing so, we only need to pass arguments at runtime without telling which method to call."
},
{
"code": null,
"e": 26603,
"s": 26595,
"text": "Python3"
},
{
"code": "import fire def hello(name): return \"Hello \" + name if __name__ == '__main__': fire.Fire(hello)",
"e": 26707,
"s": 26603,
"text": null
},
{
"code": null,
"e": 26715,
"s": 26707,
"text": "Output:"
},
{
"code": null,
"e": 26727,
"s": 26715,
"text": "Hello world"
},
{
"code": null,
"e": 26962,
"s": 26727,
"text": "If you run this in the terminal using the below command, it will give the same result as the above function. Calling Fire consumed name = “World”. Using this method of calling fire, saves from writing the function name with arguments."
},
{
"code": null,
"e": 26983,
"s": 26962,
"text": "python main.py world"
},
{
"code": null,
"e": 27046,
"s": 26983,
"text": "Both the ways of calling will give “Hello World” as an output."
},
{
"code": null,
"e": 27289,
"s": 27046,
"text": "Here is an example class created named Square and a method “square” is defined inside it. Once, we call fire on any class, we can access it as a method on the command line directly. We will see how to call this method using the below example,"
},
{
"code": null,
"e": 27297,
"s": 27289,
"text": "Python3"
},
{
"code": "import fire class Square(object): def square(self, number): return number*number fire.Fire(Square)",
"e": 27410,
"s": 27297,
"text": null
},
{
"code": null,
"e": 27418,
"s": 27410,
"text": "Output:"
},
{
"code": null,
"e": 27420,
"s": 27418,
"text": "4"
},
{
"code": null,
"e": 27483,
"s": 27420,
"text": "There are two ways to execute this class, the first method is:"
},
{
"code": null,
"e": 27507,
"s": 27483,
"text": "python main.py square 2"
},
{
"code": null,
"e": 27566,
"s": 27507,
"text": "The second way which will give the same desired output is:"
},
{
"code": null,
"e": 27599,
"s": 27566,
"text": "python main.py square --number=2"
},
{
"code": null,
"e": 27648,
"s": 27599,
"text": "Both the methods will give the same result = 4. "
},
{
"code": null,
"e": 27828,
"s": 27648,
"text": "Fire is convenient as it allows to pass arguments from a command line. In the above example, we invoked the method from the command line and assigned arguments at the same time. "
},
{
"code": null,
"e": 27939,
"s": 27828,
"text": "Fire can be used to instantiate classes inside the class, creating a hierarchical view. let’s take an example,"
},
{
"code": null,
"e": 27947,
"s": 27939,
"text": "Python3"
},
{
"code": "import fire class Calculator(object): def __init__(self): self.SQUARE = Square() class Square(object): def square(self, number): return number*number def triplet(self,number): return number*number*number fire.Fire(Calculator)",
"e": 28216,
"s": 27947,
"text": null
},
{
"code": null,
"e": 28389,
"s": 28216,
"text": "In this way, the Calculator class instantiates the square class and its object is created. The member functions of the instantiated class can be accessed at run time like: "
},
{
"code": null,
"e": 28731,
"s": 28389,
"text": "To know more about fire commands associated with a particular object or class use –help flag with the object or class. For Example, shown below, we are querying about the “SQUARE” object, and it shows two commands associated with it – “square” and “triplet”. This means you can only pass these two commands with SQUARE with their parameters."
},
{
"code": null,
"e": 28762,
"s": 28731,
"text": "Fire makes code more readable."
},
{
"code": null,
"e": 28802,
"s": 28762,
"text": "Easy to create command-line Interfaces."
},
{
"code": null,
"e": 28893,
"s": 28802,
"text": "fire.Fire() executes the full content of the program when invoked at the end of a program."
},
{
"code": null,
"e": 28908,
"s": 28893,
"text": "python-modules"
},
{
"code": null,
"e": 28915,
"s": 28908,
"text": "Python"
},
{
"code": null,
"e": 29013,
"s": 28915,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29045,
"s": 29013,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29087,
"s": 29045,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29129,
"s": 29087,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29156,
"s": 29129,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 29212,
"s": 29156,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29234,
"s": 29212,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29273,
"s": 29234,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29304,
"s": 29273,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29333,
"s": 29304,
"text": "Create a directory in Python"
}
] |
How to put string in array, split by new line in PHP ? - GeeksforGeeks
|
24 Jan, 2022
Given a string concatenated with several new line character. The task is to split that string and store them into array such that strings are splitted by the newline.Example:
Input : string is 'Ankit \n Ram \n Shyam'
Output : Array
(
[0] => Ankit
[1] => Ram
[2] => Shyam
)
Using explode() Function: The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs. This functions returns an array containing the strings formed by splitting the original string. This function accepts separator and string to be separated and optional argument length of string to be separated.Example:
php
<?php // PHP program to separate string// using explode function // String which to be converted$str = "Ankit Mishra\nRam Singh\nShyam Pandey"; // Function to convert string to array$arr = explode("\n", $str); // Print the information of arrayprint_r($arr);?>
Array
(
[0] => Ankit Mishra
[1] => Ram Singh
[2] => Shyam Pandey
)
Using preg_split() Function: The function splits the string into smaller strings or sub-strings of length which is specified by the user. If the limit is specified then small string or sub-strings up to limit return through an array. The preg_split() function is similar to explode() function but the difference is used to the regular expression to specify the delimiter but explode is not used it. This function takes first argument as regular expression which is used for splitting second argument is as string which is to be splitted.Example:
php
<?php // A php program to separate string// using preg_split() function // String which to be converted$str = "Ankit Mishra\nRam Singh\nShyam Pandey"; // This function converts the string$arr= preg_split ('/\n/', $str); // print the information of arrayprint_r($arr);?>
Array
(
[0] => Ankit Mishra
[1] => Ram Singh
[2] => Shyam Pandey
)
saurabh1990aror
Picked
Web-Programs
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
|
[
{
"code": null,
"e": 26253,
"s": 26225,
"text": "\n24 Jan, 2022"
},
{
"code": null,
"e": 26430,
"s": 26253,
"text": "Given a string concatenated with several new line character. The task is to split that string and store them into array such that strings are splitted by the newline.Example: "
},
{
"code": null,
"e": 26542,
"s": 26430,
"text": " Input : string is 'Ankit \\n Ram \\n Shyam'\n Output : Array\n(\n [0] => Ankit\n [1] => Ram\n [2] => Shyam\n)"
},
{
"code": null,
"e": 26924,
"s": 26542,
"text": "Using explode() Function: The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs. This functions returns an array containing the strings formed by splitting the original string. This function accepts separator and string to be separated and optional argument length of string to be separated.Example: "
},
{
"code": null,
"e": 26928,
"s": 26924,
"text": "php"
},
{
"code": "<?php // PHP program to separate string// using explode function // String which to be converted$str = \"Ankit Mishra\\nRam Singh\\nShyam Pandey\"; // Function to convert string to array$arr = explode(\"\\n\", $str); // Print the information of arrayprint_r($arr);?>",
"e": 27188,
"s": 26928,
"text": null
},
{
"code": null,
"e": 27267,
"s": 27188,
"text": "Array\n(\n [0] => Ankit Mishra\n [1] => Ram Singh\n [2] => Shyam Pandey\n)"
},
{
"code": null,
"e": 27817,
"s": 27269,
"text": "Using preg_split() Function: The function splits the string into smaller strings or sub-strings of length which is specified by the user. If the limit is specified then small string or sub-strings up to limit return through an array. The preg_split() function is similar to explode() function but the difference is used to the regular expression to specify the delimiter but explode is not used it. This function takes first argument as regular expression which is used for splitting second argument is as string which is to be splitted.Example: "
},
{
"code": null,
"e": 27821,
"s": 27817,
"text": "php"
},
{
"code": "<?php // A php program to separate string// using preg_split() function // String which to be converted$str = \"Ankit Mishra\\nRam Singh\\nShyam Pandey\"; // This function converts the string$arr= preg_split ('/\\n/', $str); // print the information of arrayprint_r($arr);?>",
"e": 28091,
"s": 27821,
"text": null
},
{
"code": null,
"e": 28170,
"s": 28091,
"text": "Array\n(\n [0] => Ankit Mishra\n [1] => Ram Singh\n [2] => Shyam Pandey\n)"
},
{
"code": null,
"e": 28188,
"s": 28172,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 28195,
"s": 28188,
"text": "Picked"
},
{
"code": null,
"e": 28208,
"s": 28195,
"text": "Web-Programs"
},
{
"code": null,
"e": 28212,
"s": 28208,
"text": "PHP"
},
{
"code": null,
"e": 28225,
"s": 28212,
"text": "PHP Programs"
},
{
"code": null,
"e": 28242,
"s": 28225,
"text": "Web Technologies"
},
{
"code": null,
"e": 28246,
"s": 28242,
"text": "PHP"
},
{
"code": null,
"e": 28344,
"s": 28246,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28394,
"s": 28344,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 28434,
"s": 28394,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 28495,
"s": 28434,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 28545,
"s": 28495,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 28590,
"s": 28545,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 28640,
"s": 28590,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 28680,
"s": 28640,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 28732,
"s": 28680,
"text": "How to call PHP function on the click of a Button ?"
},
{
"code": null,
"e": 28793,
"s": 28732,
"text": "How to Upload Image into Database and Display it using PHP ?"
}
] |
C# | How to get First Element of the Tuple? - GeeksforGeeks
|
30 Apr, 2019
Tuple is a data structure which gives you the easiest way to represent a data set which has multiple values that may/may not be related to each other. Item1 Property is used to get the first element of the given tuple. It is applicable on every tuple like 1-Tuple, 2-Tuple, and so on.
Syntax:
public T1 Item1 { get; }
Here, T1 is the value of the current Tuple<> object’s first component. This Tuple<> can be 1-tuple, or 2-tuple, or 3-tuple, or 4-tuple, or 5-tuple, or 6-tuple, or 7-tuple, or 8-tuple.
Example: In the below code, you can see that we are accessing the first element of each tuple.
// C# program to illustrate how to get // the first element of the tupleusing System; class GFG { // Main method static public void Main() { // Taking 1-tuple var st1 = Tuple.Create("Mohan"); Console.WriteLine("Student-1 Name: " + st1.Item1); // Taking 2-tuple var st2 = Tuple.Create("Sohan", 20); Console.WriteLine("Student-2 Name: " + st2.Item1); // Taking 3-tuple var st3 = Tuple.Create("Soniya", 30, "CSE"); Console.WriteLine("Student-3 Name: " + st3.Item1); // Taking 4-tuple var st4 = Tuple.Create("Rohan", 29, "CSE", 2015); Console.WriteLine("Student-4 Name: " + st4.Item1); // Taking 5-tuple var st5 = Tuple.Create("Siya", 22, "CSE", 2017, "20-Mar-1993"); Console.WriteLine("Student-5 Name: " + st5.Item1); // Taking 6-tuple var st6 = Tuple.Create("Riya", 24, "CSE", 2015, "30-May-2015", 230134832); Console.WriteLine("Student-6 Name: " + st6.Item1); // Taking 7-tuple var st7 = Tuple.Create("Rohit", 21, "CSE", 2017, "21-Apr-1998", 384749829, 20000); Console.WriteLine("Student-7 Name: " + st7.Item1); // Taking 8-tuple var st8 = Tuple.Create("Manita", 24, "CSE", 2016, "03-Aug-1991", 235678909, 34000, "C#"); Console.WriteLine("Student-8 Name: " + st8.Item1); }}
Student-1 Name: Mohan
Student-2 Name: Sohan
Student-3 Name: Soniya
Student-4 Name: Rohan
Student-5 Name: Siya
Student-6 Name: Riya
Student-7 Name: Rohit
Student-8 Name: Manita
CSharp-Tuple
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Delegates
C# | Method Overriding
C# | Abstract Classes
Difference between Ref and Out keywords in C#
Extension Method in C#
C# | Class and Object
C# | Constructors
C# | String.IndexOf( ) Method | Set - 1
C# | Replace() Method
Introduction to .NET Framework
|
[
{
"code": null,
"e": 25935,
"s": 25907,
"text": "\n30 Apr, 2019"
},
{
"code": null,
"e": 26220,
"s": 25935,
"text": "Tuple is a data structure which gives you the easiest way to represent a data set which has multiple values that may/may not be related to each other. Item1 Property is used to get the first element of the given tuple. It is applicable on every tuple like 1-Tuple, 2-Tuple, and so on."
},
{
"code": null,
"e": 26228,
"s": 26220,
"text": "Syntax:"
},
{
"code": null,
"e": 26253,
"s": 26228,
"text": "public T1 Item1 { get; }"
},
{
"code": null,
"e": 26437,
"s": 26253,
"text": "Here, T1 is the value of the current Tuple<> object’s first component. This Tuple<> can be 1-tuple, or 2-tuple, or 3-tuple, or 4-tuple, or 5-tuple, or 6-tuple, or 7-tuple, or 8-tuple."
},
{
"code": null,
"e": 26532,
"s": 26437,
"text": "Example: In the below code, you can see that we are accessing the first element of each tuple."
},
{
"code": "// C# program to illustrate how to get // the first element of the tupleusing System; class GFG { // Main method static public void Main() { // Taking 1-tuple var st1 = Tuple.Create(\"Mohan\"); Console.WriteLine(\"Student-1 Name: \" + st1.Item1); // Taking 2-tuple var st2 = Tuple.Create(\"Sohan\", 20); Console.WriteLine(\"Student-2 Name: \" + st2.Item1); // Taking 3-tuple var st3 = Tuple.Create(\"Soniya\", 30, \"CSE\"); Console.WriteLine(\"Student-3 Name: \" + st3.Item1); // Taking 4-tuple var st4 = Tuple.Create(\"Rohan\", 29, \"CSE\", 2015); Console.WriteLine(\"Student-4 Name: \" + st4.Item1); // Taking 5-tuple var st5 = Tuple.Create(\"Siya\", 22, \"CSE\", 2017, \"20-Mar-1993\"); Console.WriteLine(\"Student-5 Name: \" + st5.Item1); // Taking 6-tuple var st6 = Tuple.Create(\"Riya\", 24, \"CSE\", 2015, \"30-May-2015\", 230134832); Console.WriteLine(\"Student-6 Name: \" + st6.Item1); // Taking 7-tuple var st7 = Tuple.Create(\"Rohit\", 21, \"CSE\", 2017, \"21-Apr-1998\", 384749829, 20000); Console.WriteLine(\"Student-7 Name: \" + st7.Item1); // Taking 8-tuple var st8 = Tuple.Create(\"Manita\", 24, \"CSE\", 2016, \"03-Aug-1991\", 235678909, 34000, \"C#\"); Console.WriteLine(\"Student-8 Name: \" + st8.Item1); }}",
"e": 28027,
"s": 26532,
"text": null
},
{
"code": null,
"e": 28204,
"s": 28027,
"text": "Student-1 Name: Mohan\nStudent-2 Name: Sohan\nStudent-3 Name: Soniya\nStudent-4 Name: Rohan\nStudent-5 Name: Siya\nStudent-6 Name: Riya\nStudent-7 Name: Rohit\nStudent-8 Name: Manita\n"
},
{
"code": null,
"e": 28217,
"s": 28204,
"text": "CSharp-Tuple"
},
{
"code": null,
"e": 28220,
"s": 28217,
"text": "C#"
},
{
"code": null,
"e": 28318,
"s": 28220,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28333,
"s": 28318,
"text": "C# | Delegates"
},
{
"code": null,
"e": 28356,
"s": 28333,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 28378,
"s": 28356,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 28424,
"s": 28378,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 28447,
"s": 28424,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28469,
"s": 28447,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 28487,
"s": 28469,
"text": "C# | Constructors"
},
{
"code": null,
"e": 28527,
"s": 28487,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 28549,
"s": 28527,
"text": "C# | Replace() Method"
}
] |
LocalTime toEpochSecond() method in Java with Examples - GeeksforGeeks
|
04 Dec, 2018
The toEpochSecond() method of LocalTime class is used to convert this LocalTime to the number of seconds since the epoch of 1970-01-01T00:00:00Z. The method combines this local time with the specified date and offset passed as parameters to calculate the epoch-second value, which is the number of elapsed seconds from 1970-01-01T00:00:00Z. Instants on the timeline after the epoch are positive, earlier are negative.
Syntax:
public long
toEpochSecond(LocalDate date,
ZoneOffset offset)
Parameters: This method accepts two parameters:
date: It is the date which is to be used for epoch second calculation as the target date.
offset: It is the zone offset.
Return value: This method returns number of seconds since the epoch of 1970-01-01T00:00:00Z. It may be negative.
Below programs illustrate the toEpochSecond() method:
Program 1:
// Java program to demonstrate// LocalTime.toEpochSecond() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalDate object LocalDate date = LocalDate.parse("2018-12-29"); // create a LocalTime object LocalTime time = LocalTime.parse("20:12:32"); // print Instant System.out.println("LocalDate: " + date); // create ZoneId ZoneOffset zone = ZoneOffset.of("Z"); // print ZoneId System.out.println("ZoneOffset: " + zone); // apply ofInstant() long value = time.toEpochSecond(date, zone); // print result System.out.println("Epoch Second: " + value); }}
LocalDate: 2018-12-29
ZoneOffset: Z
Epoch Second: 1546114352
Program 2:
// Java program to demonstrate// LocalTime.toEpochSecond() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalDate object LocalDate date = LocalDate.parse("1909-04-18"); // create a LocalTime object LocalTime time = LocalTime.parse("00:10:09"); // print Instant System.out.println("LocalDate: " + date); // create ZoneId ZoneOffset zone = ZoneOffset.of("Z"); // print ZoneId System.out.println("ZoneOffset: " + zone); // apply ofInstant() long value = time.toEpochSecond(date, zone); // print result System.out.println("Epoch Second: " + value); }}
LocalDate: 1909-04-18
ZoneOffset: Z
Epoch Second: -1915746591
References: https://docs.oracle.com/javase/10/docs/api/java/time/LocalTime.html#toEpochSecond(java.time.LocalDate, java.time.ZoneOffset)
Java-Functions
Java-LocalTime
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
|
[
{
"code": null,
"e": 25573,
"s": 25545,
"text": "\n04 Dec, 2018"
},
{
"code": null,
"e": 25991,
"s": 25573,
"text": "The toEpochSecond() method of LocalTime class is used to convert this LocalTime to the number of seconds since the epoch of 1970-01-01T00:00:00Z. The method combines this local time with the specified date and offset passed as parameters to calculate the epoch-second value, which is the number of elapsed seconds from 1970-01-01T00:00:00Z. Instants on the timeline after the epoch are positive, earlier are negative."
},
{
"code": null,
"e": 25999,
"s": 25991,
"text": "Syntax:"
},
{
"code": null,
"e": 26097,
"s": 25999,
"text": "public long \n toEpochSecond(LocalDate date,\n ZoneOffset offset)\n"
},
{
"code": null,
"e": 26145,
"s": 26097,
"text": "Parameters: This method accepts two parameters:"
},
{
"code": null,
"e": 26235,
"s": 26145,
"text": "date: It is the date which is to be used for epoch second calculation as the target date."
},
{
"code": null,
"e": 26266,
"s": 26235,
"text": "offset: It is the zone offset."
},
{
"code": null,
"e": 26379,
"s": 26266,
"text": "Return value: This method returns number of seconds since the epoch of 1970-01-01T00:00:00Z. It may be negative."
},
{
"code": null,
"e": 26433,
"s": 26379,
"text": "Below programs illustrate the toEpochSecond() method:"
},
{
"code": null,
"e": 26444,
"s": 26433,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate// LocalTime.toEpochSecond() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalDate object LocalDate date = LocalDate.parse(\"2018-12-29\"); // create a LocalTime object LocalTime time = LocalTime.parse(\"20:12:32\"); // print Instant System.out.println(\"LocalDate: \" + date); // create ZoneId ZoneOffset zone = ZoneOffset.of(\"Z\"); // print ZoneId System.out.println(\"ZoneOffset: \" + zone); // apply ofInstant() long value = time.toEpochSecond(date, zone); // print result System.out.println(\"Epoch Second: \" + value); }}",
"e": 27217,
"s": 26444,
"text": null
},
{
"code": null,
"e": 27279,
"s": 27217,
"text": "LocalDate: 2018-12-29\nZoneOffset: Z\nEpoch Second: 1546114352\n"
},
{
"code": null,
"e": 27290,
"s": 27279,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// LocalTime.toEpochSecond() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalDate object LocalDate date = LocalDate.parse(\"1909-04-18\"); // create a LocalTime object LocalTime time = LocalTime.parse(\"00:10:09\"); // print Instant System.out.println(\"LocalDate: \" + date); // create ZoneId ZoneOffset zone = ZoneOffset.of(\"Z\"); // print ZoneId System.out.println(\"ZoneOffset: \" + zone); // apply ofInstant() long value = time.toEpochSecond(date, zone); // print result System.out.println(\"Epoch Second: \" + value); }}",
"e": 28063,
"s": 27290,
"text": null
},
{
"code": null,
"e": 28126,
"s": 28063,
"text": "LocalDate: 1909-04-18\nZoneOffset: Z\nEpoch Second: -1915746591\n"
},
{
"code": null,
"e": 28263,
"s": 28126,
"text": "References: https://docs.oracle.com/javase/10/docs/api/java/time/LocalTime.html#toEpochSecond(java.time.LocalDate, java.time.ZoneOffset)"
},
{
"code": null,
"e": 28278,
"s": 28263,
"text": "Java-Functions"
},
{
"code": null,
"e": 28293,
"s": 28278,
"text": "Java-LocalTime"
},
{
"code": null,
"e": 28311,
"s": 28293,
"text": "Java-time package"
},
{
"code": null,
"e": 28316,
"s": 28311,
"text": "Java"
},
{
"code": null,
"e": 28321,
"s": 28316,
"text": "Java"
},
{
"code": null,
"e": 28419,
"s": 28321,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28470,
"s": 28419,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 28500,
"s": 28470,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 28515,
"s": 28500,
"text": "Stream In Java"
},
{
"code": null,
"e": 28546,
"s": 28515,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 28564,
"s": 28546,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 28596,
"s": 28564,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 28616,
"s": 28596,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 28648,
"s": 28616,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 28672,
"s": 28648,
"text": "Singleton Class in Java"
}
] |
JavaScript Map get( ) Method - GeeksforGeeks
|
24 Nov, 2021
The Map.get() method in JavaScript is used for returning a specific element among all the elements which are present in a map. The Map.get() method takes the key of the element to be returned as an argument and returns the element which is associated with the specified key passed as an argument. If the key passed as an argument is not present in the map, then Map.get() method returns undefined. The Map.get() method is used to get a specific element among all the elements which are present in a map.
Syntax:
mapObj.get(key)
Parameter Value:
key: It is the key of the element of the map which has to be returned.
Return Value: The Map.get() method returns the element which is associated with the specified key passed as an argument or undefined if the key passed as an argument is not present in the map.
The examples below illustrate the get() method:
Example 1: This example describes the Map() method to create the map object that contains the [key, value] pair to the map & displays the element that is associated with the specific key using the Map.get() method.
javascript
<script> // Creating a map object var myMap = new Map(); // Adding [key, value] pair to the map myMap.set(0, 'GeeksforGeeks'); // Displaying the element which is associated with // the key '0' using Map.get() method document.write(myMap.get(0));</script>
Output:
"GeeksforGeeks"
Example 2: This example describes the Map() method to create the map object that contains the multiple [key, value] pair to the map & displays the element that is associated with the specific key using the Map.get() method.
Javascript
<script> // Creating a map object var myMap = new Map(); // Adding [key, value] pair to the map myMap.set(0, 'GeeksforGeeks'); myMap.set(1, 'is an online portal'); myMap.set(2, 'for geeks'); // Displaying the elements which are associated with the keys '0', '2' // and '4' using Map.get() method document.write(myMap.get(0),"</br>"); document.write(myMap.get(2),"</br>"); document.write(myMap.get(4),"</br>");</script>
Output:
"GeeksforGeeks"
"for geeks"
undefined
Exceptions:
If the variable is not of the Map type then the Map.get() operation throws a TypeError.
If the index specified in the Map.get() function doesn’t belong to the [key, value] pairs of a map, the Map.get() function returns undefined.
Differences between Objects and Maps in JavaScript: Both of these data structures are similar in many ways such as both are used to store values using keys, allowing retrieval of those values using keys, deletion of keys, and verifying whether a key holds any value or not. However, there are quite significant differences between Objects and Maps in JavaScript which make the usage of maps a better and more preferable option in many cases.
The keys used in maps can be any type of values such as functions, objects, etc whereas the keys in objects are limited to symbols and strings.
The size of a map can be known easily by using the size property but while dealing with objects, the size has to be determined manually.
A Map should be preferred in cases where the requirement involves frequent addition and removal of [key, value] pairs because a map is an iterative data type and can be directly iterated whereas iterating an Object requires obtaining its keys in a specific manner.
Supported Browsers:
Google Chrome 38.0
Microsoft Edge 12.0
Firefox 13.0
Internet Explorer 11.0
Opera 25.0
Safari 8.0
bhaskargeeksforgeeks
javascript-functions
javascript-map
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
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 ?
Difference Between PUT and PATCH Request
JavaScript | console.log() with Examples
How to read a local text file using JavaScript?
Node.js | fs.writeFileSync() Method
|
[
{
"code": null,
"e": 25637,
"s": 25609,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 26141,
"s": 25637,
"text": "The Map.get() method in JavaScript is used for returning a specific element among all the elements which are present in a map. The Map.get() method takes the key of the element to be returned as an argument and returns the element which is associated with the specified key passed as an argument. If the key passed as an argument is not present in the map, then Map.get() method returns undefined. The Map.get() method is used to get a specific element among all the elements which are present in a map."
},
{
"code": null,
"e": 26149,
"s": 26141,
"text": "Syntax:"
},
{
"code": null,
"e": 26165,
"s": 26149,
"text": "mapObj.get(key)"
},
{
"code": null,
"e": 26182,
"s": 26165,
"text": "Parameter Value:"
},
{
"code": null,
"e": 26253,
"s": 26182,
"text": "key: It is the key of the element of the map which has to be returned."
},
{
"code": null,
"e": 26446,
"s": 26253,
"text": "Return Value: The Map.get() method returns the element which is associated with the specified key passed as an argument or undefined if the key passed as an argument is not present in the map."
},
{
"code": null,
"e": 26494,
"s": 26446,
"text": "The examples below illustrate the get() method:"
},
{
"code": null,
"e": 26709,
"s": 26494,
"text": "Example 1: This example describes the Map() method to create the map object that contains the [key, value] pair to the map & displays the element that is associated with the specific key using the Map.get() method."
},
{
"code": null,
"e": 26720,
"s": 26709,
"text": "javascript"
},
{
"code": "<script> // Creating a map object var myMap = new Map(); // Adding [key, value] pair to the map myMap.set(0, 'GeeksforGeeks'); // Displaying the element which is associated with // the key '0' using Map.get() method document.write(myMap.get(0));</script>",
"e": 26984,
"s": 26720,
"text": null
},
{
"code": null,
"e": 26992,
"s": 26984,
"text": "Output:"
},
{
"code": null,
"e": 27008,
"s": 26992,
"text": "\"GeeksforGeeks\""
},
{
"code": null,
"e": 27232,
"s": 27008,
"text": "Example 2: This example describes the Map() method to create the map object that contains the multiple [key, value] pair to the map & displays the element that is associated with the specific key using the Map.get() method."
},
{
"code": null,
"e": 27243,
"s": 27232,
"text": "Javascript"
},
{
"code": "<script> // Creating a map object var myMap = new Map(); // Adding [key, value] pair to the map myMap.set(0, 'GeeksforGeeks'); myMap.set(1, 'is an online portal'); myMap.set(2, 'for geeks'); // Displaying the elements which are associated with the keys '0', '2' // and '4' using Map.get() method document.write(myMap.get(0),\"</br>\"); document.write(myMap.get(2),\"</br>\"); document.write(myMap.get(4),\"</br>\");</script>",
"e": 27675,
"s": 27243,
"text": null
},
{
"code": null,
"e": 27683,
"s": 27675,
"text": "Output:"
},
{
"code": null,
"e": 27721,
"s": 27683,
"text": "\"GeeksforGeeks\"\n\"for geeks\"\nundefined"
},
{
"code": null,
"e": 27733,
"s": 27721,
"text": "Exceptions:"
},
{
"code": null,
"e": 27821,
"s": 27733,
"text": "If the variable is not of the Map type then the Map.get() operation throws a TypeError."
},
{
"code": null,
"e": 27963,
"s": 27821,
"text": "If the index specified in the Map.get() function doesn’t belong to the [key, value] pairs of a map, the Map.get() function returns undefined."
},
{
"code": null,
"e": 28405,
"s": 27963,
"text": "Differences between Objects and Maps in JavaScript: Both of these data structures are similar in many ways such as both are used to store values using keys, allowing retrieval of those values using keys, deletion of keys, and verifying whether a key holds any value or not. However, there are quite significant differences between Objects and Maps in JavaScript which make the usage of maps a better and more preferable option in many cases."
},
{
"code": null,
"e": 28549,
"s": 28405,
"text": "The keys used in maps can be any type of values such as functions, objects, etc whereas the keys in objects are limited to symbols and strings."
},
{
"code": null,
"e": 28686,
"s": 28549,
"text": "The size of a map can be known easily by using the size property but while dealing with objects, the size has to be determined manually."
},
{
"code": null,
"e": 28951,
"s": 28686,
"text": "A Map should be preferred in cases where the requirement involves frequent addition and removal of [key, value] pairs because a map is an iterative data type and can be directly iterated whereas iterating an Object requires obtaining its keys in a specific manner."
},
{
"code": null,
"e": 28971,
"s": 28951,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 28990,
"s": 28971,
"text": "Google Chrome 38.0"
},
{
"code": null,
"e": 29010,
"s": 28990,
"text": "Microsoft Edge 12.0"
},
{
"code": null,
"e": 29023,
"s": 29010,
"text": "Firefox 13.0"
},
{
"code": null,
"e": 29046,
"s": 29023,
"text": "Internet Explorer 11.0"
},
{
"code": null,
"e": 29057,
"s": 29046,
"text": "Opera 25.0"
},
{
"code": null,
"e": 29068,
"s": 29057,
"text": "Safari 8.0"
},
{
"code": null,
"e": 29089,
"s": 29068,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 29110,
"s": 29089,
"text": "javascript-functions"
},
{
"code": null,
"e": 29125,
"s": 29110,
"text": "javascript-map"
},
{
"code": null,
"e": 29136,
"s": 29125,
"text": "JavaScript"
},
{
"code": null,
"e": 29234,
"s": 29136,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29274,
"s": 29234,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29319,
"s": 29274,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29380,
"s": 29319,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29452,
"s": 29380,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 29504,
"s": 29452,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 29550,
"s": 29504,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 29591,
"s": 29550,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 29632,
"s": 29591,
"text": "JavaScript | console.log() with Examples"
},
{
"code": null,
"e": 29680,
"s": 29632,
"text": "How to read a local text file using JavaScript?"
}
] |
Get the Last parts of a Data Set in R Programming - tail() Function - GeeksforGeeks
|
30 Jun, 2020
tail() function in R Language is used to get the last parts of a vector, matrix, table, data frame or function.
Syntax: tail(x, n)
Parameters:x: specified data typesn: number of row need to be printed
Example 1:
# R program to illustrate# tail function # Calling the tail() function to # get the last iris demo datasettail(iris)
Output:
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
145 6.7 3.3 5.7 2.5 virginica
146 6.7 3.0 5.2 2.3 virginica
147 6.3 2.5 5.0 1.9 virginica
148 6.5 3.0 5.2 2.0 virginica
149 6.2 3.4 5.4 2.3 virginica
150 5.9 3.0 5.1 1.8 virginica
Example 2:
# R program to illustrate# tail function # Calling the tail() function to # get the last iris demo dataset# in 4 rowstail(iris, 4)
Output:
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
147 6.3 2.5 5.0 1.9 virginica
148 6.5 3.0 5.2 2.0 virginica
149 6.2 3.4 5.4 2.3 virginica
150 5.9 3.0 5.1 1.8 virginica
R DataFrame-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
How to change Row Names of DataFrame in R ?
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
K-Means Clustering in R Programming
Replace Specific Characters in String in R
Remove rows with NA in one column of R DataFrame
|
[
{
"code": null,
"e": 26141,
"s": 26113,
"text": "\n30 Jun, 2020"
},
{
"code": null,
"e": 26253,
"s": 26141,
"text": "tail() function in R Language is used to get the last parts of a vector, matrix, table, data frame or function."
},
{
"code": null,
"e": 26272,
"s": 26253,
"text": "Syntax: tail(x, n)"
},
{
"code": null,
"e": 26342,
"s": 26272,
"text": "Parameters:x: specified data typesn: number of row need to be printed"
},
{
"code": null,
"e": 26353,
"s": 26342,
"text": "Example 1:"
},
{
"code": "# R program to illustrate# tail function # Calling the tail() function to # get the last iris demo datasettail(iris)",
"e": 26471,
"s": 26353,
"text": null
},
{
"code": null,
"e": 26479,
"s": 26471,
"text": "Output:"
},
{
"code": null,
"e": 26928,
"s": 26479,
"text": " Sepal.Length Sepal.Width Petal.Length Petal.Width Species\n145 6.7 3.3 5.7 2.5 virginica\n146 6.7 3.0 5.2 2.3 virginica\n147 6.3 2.5 5.0 1.9 virginica\n148 6.5 3.0 5.2 2.0 virginica\n149 6.2 3.4 5.4 2.3 virginica\n150 5.9 3.0 5.1 1.8 virginica\n"
},
{
"code": null,
"e": 26939,
"s": 26928,
"text": "Example 2:"
},
{
"code": "# R program to illustrate# tail function # Calling the tail() function to # get the last iris demo dataset# in 4 rowstail(iris, 4)",
"e": 27071,
"s": 26939,
"text": null
},
{
"code": null,
"e": 27079,
"s": 27071,
"text": "Output:"
},
{
"code": null,
"e": 27400,
"s": 27079,
"text": " Sepal.Length Sepal.Width Petal.Length Petal.Width Species\n147 6.3 2.5 5.0 1.9 virginica\n148 6.5 3.0 5.2 2.0 virginica\n149 6.2 3.4 5.4 2.3 virginica\n150 5.9 3.0 5.1 1.8 virginica\n"
},
{
"code": null,
"e": 27421,
"s": 27400,
"text": "R DataFrame-Function"
},
{
"code": null,
"e": 27432,
"s": 27421,
"text": "R Language"
},
{
"code": null,
"e": 27530,
"s": 27432,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27582,
"s": 27530,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 27614,
"s": 27582,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 27658,
"s": 27614,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 27710,
"s": 27658,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 27745,
"s": 27710,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 27783,
"s": 27745,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 27841,
"s": 27783,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 27877,
"s": 27841,
"text": "K-Means Clustering in R Programming"
},
{
"code": null,
"e": 27920,
"s": 27877,
"text": "Replace Specific Characters in String in R"
}
] |
Infosys Interview Experience for Specialist Programmer(Lateral) - GeeksforGeeks
|
31 Aug, 2021
Round 1: It started with a problem-solving round. I got 30 min to solve.
Question: An evil scientist has developed an injection that induces insatiable hunger in a fish. On giving this injection, a fish of size x can eat another fish of smaller size y (y < x) and become a fish of size x + y retaining this hunger. An aquarium has a number of fishes of various sizes. The scientist introduces an injected fish into this aquarium with an objective that eventually only 1 fish remains. In order to achieve this, the scientist is allowed only two types of moves: either add a normal fish of any size or remove an existing normal fish from the aquarium. Given the sizes of other fishes in the aquarium and the size of injected fish, write a program to determine the minimum number of moves needed by the scientist to achieve his objective. For example, suppose there are 5 fishes in the aquarium, the injected fish is of size 10 and the other fishes are of sizes 9, 20, 25, and 100. To ensure that only 1 fish remains in the aquarium the scientist needs to remove the fish of size 100 and add a fish of size 3. So the output is 2. The sequence of steps is shown below. The sizes of fishes in the aquarium at each step are shown in curly braces. The highlighted number is the size of the injected fish.Solution:JavascriptJavascriptfunction fish(x, A) { A.sort((a,b) => a-b); let sum = x; let required_removals=A.length; let moves = 0; let best_moves=required_removals; let i =0; while(i<A.length) { if(sum > A[i]) { sum +=A[i]; required_removals -=1; i=i+1; } else { sum = sum +(sum -1); moves=moves+1; } best_moves = Math.min(best_moves, moves+required_removals); } return best_moves; } var arr= [ [10, [9,20,25,100]], [3, [25,20,100,400,500]], [50, [25,20,9,100]] ] for(let [x,A] of arr) { console.log(`${x}#${A}`); console.log(""); console.log(fish(x,A)); }
Question: An evil scientist has developed an injection that induces insatiable hunger in a fish. On giving this injection, a fish of size x can eat another fish of smaller size y (y < x) and become a fish of size x + y retaining this hunger. An aquarium has a number of fishes of various sizes. The scientist introduces an injected fish into this aquarium with an objective that eventually only 1 fish remains. In order to achieve this, the scientist is allowed only two types of moves: either add a normal fish of any size or remove an existing normal fish from the aquarium. Given the sizes of other fishes in the aquarium and the size of injected fish, write a program to determine the minimum number of moves needed by the scientist to achieve his objective. For example, suppose there are 5 fishes in the aquarium, the injected fish is of size 10 and the other fishes are of sizes 9, 20, 25, and 100. To ensure that only 1 fish remains in the aquarium the scientist needs to remove the fish of size 100 and add a fish of size 3. So the output is 2. The sequence of steps is shown below. The sizes of fishes in the aquarium at each step are shown in curly braces. The highlighted number is the size of the injected fish.Solution:JavascriptJavascriptfunction fish(x, A) { A.sort((a,b) => a-b); let sum = x; let required_removals=A.length; let moves = 0; let best_moves=required_removals; let i =0; while(i<A.length) { if(sum > A[i]) { sum +=A[i]; required_removals -=1; i=i+1; } else { sum = sum +(sum -1); moves=moves+1; } best_moves = Math.min(best_moves, moves+required_removals); } return best_moves; } var arr= [ [10, [9,20,25,100]], [3, [25,20,100,400,500]], [50, [25,20,9,100]] ] for(let [x,A] of arr) { console.log(`${x}#${A}`); console.log(""); console.log(fish(x,A)); }
Solution:
Javascript
function fish(x, A) { A.sort((a,b) => a-b); let sum = x; let required_removals=A.length; let moves = 0; let best_moves=required_removals; let i =0; while(i<A.length) { if(sum > A[i]) { sum +=A[i]; required_removals -=1; i=i+1; } else { sum = sum +(sum -1); moves=moves+1; } best_moves = Math.min(best_moves, moves+required_removals); } return best_moves; } var arr= [ [10, [9,20,25,100]], [3, [25,20,100,400,500]], [50, [25,20,9,100]] ] for(let [x,A] of arr) { console.log(`${x}#${A}`); console.log(""); console.log(fish(x,A)); }
After that, I am from MERN stack technology. So, I was been asked a couple of React.js and Node.js Questions
Redux Flow, Redux Saga, Thunk, Refs, Lazy Loading in React.js, FormikWrapper Class in Node.js, ejs, Coa Framework, Express QuestionsMongo DB data aggregation
Redux Flow, Redux Saga, Thunk, Refs, Lazy Loading in React.js, Formik
Wrapper Class in Node.js, ejs, Coa Framework, Express Questions
Mongo DB data aggregation
Round 2: Questions mainly from my project and React.js
Round 3: HR Round (Salary and Other Personal Details Discussion)
Infosys
Marketing
Interview Experiences
Infosys
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience for SDE-1 (Off-Campus)
Amazon AWS Interview Experience for SDE-1
Amazon Interview Experience for SDE-1 (Off-Campus) 2022
Amazon Interview Experience
Amazon Interview Experience for SDE-1
EPAM Interview Experience (Off-Campus)
Amazon Interview Experience (Off-Campus) 2022
JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021
Amazon Interview Experience for SDE-1 (On-Campus)
Freshworks/Freshdesk Interview Experience for Software Developer (On-Campus)
|
[
{
"code": null,
"e": 26261,
"s": 26233,
"text": "\n31 Aug, 2021"
},
{
"code": null,
"e": 26335,
"s": 26261,
"text": "Round 1: It started with a problem-solving round. I got 30 min to solve. "
},
{
"code": null,
"e": 28224,
"s": 26335,
"text": "Question: An evil scientist has developed an injection that induces insatiable hunger in a fish. On giving this injection, a fish of size x can eat another fish of smaller size y (y < x) and become a fish of size x + y retaining this hunger. An aquarium has a number of fishes of various sizes. The scientist introduces an injected fish into this aquarium with an objective that eventually only 1 fish remains. In order to achieve this, the scientist is allowed only two types of moves: either add a normal fish of any size or remove an existing normal fish from the aquarium. Given the sizes of other fishes in the aquarium and the size of injected fish, write a program to determine the minimum number of moves needed by the scientist to achieve his objective. For example, suppose there are 5 fishes in the aquarium, the injected fish is of size 10 and the other fishes are of sizes 9, 20, 25, and 100. To ensure that only 1 fish remains in the aquarium the scientist needs to remove the fish of size 100 and add a fish of size 3. So the output is 2. The sequence of steps is shown below. The sizes of fishes in the aquarium at each step are shown in curly braces. The highlighted number is the size of the injected fish.Solution:JavascriptJavascriptfunction fish(x, A) { A.sort((a,b) => a-b); let sum = x; let required_removals=A.length; let moves = 0; let best_moves=required_removals; let i =0; while(i<A.length) { if(sum > A[i]) { sum +=A[i]; required_removals -=1; i=i+1; } else { sum = sum +(sum -1); moves=moves+1; } best_moves = Math.min(best_moves, moves+required_removals); } return best_moves; } var arr= [ [10, [9,20,25,100]], [3, [25,20,100,400,500]], [50, [25,20,9,100]] ] for(let [x,A] of arr) { console.log(`${x}#${A}`); console.log(\"\"); console.log(fish(x,A)); }"
},
{
"code": null,
"e": 30113,
"s": 28224,
"text": "Question: An evil scientist has developed an injection that induces insatiable hunger in a fish. On giving this injection, a fish of size x can eat another fish of smaller size y (y < x) and become a fish of size x + y retaining this hunger. An aquarium has a number of fishes of various sizes. The scientist introduces an injected fish into this aquarium with an objective that eventually only 1 fish remains. In order to achieve this, the scientist is allowed only two types of moves: either add a normal fish of any size or remove an existing normal fish from the aquarium. Given the sizes of other fishes in the aquarium and the size of injected fish, write a program to determine the minimum number of moves needed by the scientist to achieve his objective. For example, suppose there are 5 fishes in the aquarium, the injected fish is of size 10 and the other fishes are of sizes 9, 20, 25, and 100. To ensure that only 1 fish remains in the aquarium the scientist needs to remove the fish of size 100 and add a fish of size 3. So the output is 2. The sequence of steps is shown below. The sizes of fishes in the aquarium at each step are shown in curly braces. The highlighted number is the size of the injected fish.Solution:JavascriptJavascriptfunction fish(x, A) { A.sort((a,b) => a-b); let sum = x; let required_removals=A.length; let moves = 0; let best_moves=required_removals; let i =0; while(i<A.length) { if(sum > A[i]) { sum +=A[i]; required_removals -=1; i=i+1; } else { sum = sum +(sum -1); moves=moves+1; } best_moves = Math.min(best_moves, moves+required_removals); } return best_moves; } var arr= [ [10, [9,20,25,100]], [3, [25,20,100,400,500]], [50, [25,20,9,100]] ] for(let [x,A] of arr) { console.log(`${x}#${A}`); console.log(\"\"); console.log(fish(x,A)); }"
},
{
"code": null,
"e": 30123,
"s": 30113,
"text": "Solution:"
},
{
"code": null,
"e": 30134,
"s": 30123,
"text": "Javascript"
},
{
"code": "function fish(x, A) { A.sort((a,b) => a-b); let sum = x; let required_removals=A.length; let moves = 0; let best_moves=required_removals; let i =0; while(i<A.length) { if(sum > A[i]) { sum +=A[i]; required_removals -=1; i=i+1; } else { sum = sum +(sum -1); moves=moves+1; } best_moves = Math.min(best_moves, moves+required_removals); } return best_moves; } var arr= [ [10, [9,20,25,100]], [3, [25,20,100,400,500]], [50, [25,20,9,100]] ] for(let [x,A] of arr) { console.log(`${x}#${A}`); console.log(\"\"); console.log(fish(x,A)); }",
"e": 30769,
"s": 30134,
"text": null
},
{
"code": null,
"e": 30878,
"s": 30769,
"text": "After that, I am from MERN stack technology. So, I was been asked a couple of React.js and Node.js Questions"
},
{
"code": null,
"e": 31036,
"s": 30878,
"text": "Redux Flow, Redux Saga, Thunk, Refs, Lazy Loading in React.js, FormikWrapper Class in Node.js, ejs, Coa Framework, Express QuestionsMongo DB data aggregation"
},
{
"code": null,
"e": 31106,
"s": 31036,
"text": "Redux Flow, Redux Saga, Thunk, Refs, Lazy Loading in React.js, Formik"
},
{
"code": null,
"e": 31170,
"s": 31106,
"text": "Wrapper Class in Node.js, ejs, Coa Framework, Express Questions"
},
{
"code": null,
"e": 31196,
"s": 31170,
"text": "Mongo DB data aggregation"
},
{
"code": null,
"e": 31251,
"s": 31196,
"text": "Round 2: Questions mainly from my project and React.js"
},
{
"code": null,
"e": 31316,
"s": 31251,
"text": "Round 3: HR Round (Salary and Other Personal Details Discussion)"
},
{
"code": null,
"e": 31324,
"s": 31316,
"text": "Infosys"
},
{
"code": null,
"e": 31334,
"s": 31324,
"text": "Marketing"
},
{
"code": null,
"e": 31356,
"s": 31334,
"text": "Interview Experiences"
},
{
"code": null,
"e": 31364,
"s": 31356,
"text": "Infosys"
},
{
"code": null,
"e": 31462,
"s": 31364,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31513,
"s": 31462,
"text": "Amazon Interview Experience for SDE-1 (Off-Campus)"
},
{
"code": null,
"e": 31555,
"s": 31513,
"text": "Amazon AWS Interview Experience for SDE-1"
},
{
"code": null,
"e": 31611,
"s": 31555,
"text": "Amazon Interview Experience for SDE-1 (Off-Campus) 2022"
},
{
"code": null,
"e": 31639,
"s": 31611,
"text": "Amazon Interview Experience"
},
{
"code": null,
"e": 31677,
"s": 31639,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 31716,
"s": 31677,
"text": "EPAM Interview Experience (Off-Campus)"
},
{
"code": null,
"e": 31762,
"s": 31716,
"text": "Amazon Interview Experience (Off-Campus) 2022"
},
{
"code": null,
"e": 31834,
"s": 31762,
"text": "JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021"
},
{
"code": null,
"e": 31884,
"s": 31834,
"text": "Amazon Interview Experience for SDE-1 (On-Campus)"
}
] |
Check if all duplicate elements in the Array are adjacent or not - GeeksforGeeks
|
09 Feb, 2022
Given an array arr[]. The task is to check whether duplicate elements in arr[] are contiguous or not.
Examples
Input: arr[] = {1, 2, 3, 4, 5, 6}Output: YesExplanation: There is no duplicate element in arr[] so there is no need to check anything and answer is Yes.
Input: arr[] = {1, 2, 2, 4}Output: YesExplanation: 2 is occurring 2 times and it is contiguous. Hence, answer is Yes.
Input: arr[] = {1, 2, 3, 2, 4}Output: NoExplanation: There is a gap between 2’s and 3 is between two 2’s. Therefore, the answer is No.
Approach: This problem can be solved by using HashMaps. Follow the steps below to solve the given problem.
Use maps to store the visited elements.
First, mark the first element on the map.
Traverse the array arr[] from 1 to N-1. where N is the size of arr[].
If the current element matches the previous element means there is a cycle of one element repeating so simply continue the loop.
If the current element is already marked in the map return “No”.
Mark the current element in the map.
If the function reaches here means there are all contiguous elements so return “Yes”.
Below is the implementation of the above approach.
C++14
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check whether duplicate// elements in array arr[] are contiguous or notstring checkContiguous(int* arr, int& n){ int i; // Map to keep track of elements unordered_map<int, bool> visited; visited.clear(); visited.insert({ arr[0], 1 }); for (i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) continue; else if (visited[arr[i]]) return "No"; visited[arr[i]] = 1; } return "Yes";} // Driver Codeint main(){ int arr[] = { 2, 4, 5, 5, 3, 5 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call cout << checkContiguous(arr, N); return 0;}
// Java code for the above approachimport java.io.*; class GFG { // Function to check whether duplicate // elements in array arr[] are contiguous or not static String checkContiguous(int[] arr, int n) { int i; // Map to keep track of elements int[] visited = new int[n]; for (i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) continue; else if (visited[arr[i]] == 0) return "No"; visited[arr[i]] = 1; } return "Yes"; } // Driver Code public static void main(String[] args) { int arr[] = { 2, 4, 5, 5, 3, 5 }; int N = arr.length; // Function Call System.out.println(checkContiguous(arr, N)); }} // This code is contributed by Potta Lokesh
# Python program for the above approach # Function to check whether duplicate# elements in array arr[] are contiguous or notdef checkContiguous (arr, n): i = None # Map to keep track of elements visited = [0] * n; for i in range(1, n): if (arr[i] == arr[i - 1]): continue; elif (visited[arr[i]] == 0): return "No"; visited[arr[i]] = 1; return "Yes"; # Driver Code arr = [2, 4, 5, 5, 3, 5];N = len(arr) # Function Callprint(checkContiguous(arr, N)); # This code is contributed by Saurabh Jaiswal
// C# code for the above approachusing System;class GFG { // Function to check whether duplicate // elements in array arr[] are contiguous or not static String checkContiguous(int[] arr, int n) { int i; // Map to keep track of elements int[] visited = new int[n]; for (i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) continue; else if (visited[arr[i]] == 0) return "No"; visited[arr[i]] = 1; } return "Yes"; } // Driver Code public static void Main() { int[] arr = { 2, 4, 5, 5, 3, 5 }; int N = arr.Length; // Function Call Console.WriteLine(checkContiguous(arr, N)); }} // This code is contributed by ukasp.
<script> // JavaScript program for the above approach // Function to check whether duplicate // elements in array arr[] are contiguous or not const checkContiguous = (arr, n) => { let i; // Map to keep track of elements let visited = {}; visited[arr[0]] = 1; for (i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) continue; else if (visited[arr[i]]) return "No"; visited[arr[i]] = 1; } return "Yes"; } // Driver Code let arr = [2, 4, 5, 5, 3, 5]; let N = arr.length; // Function Call document.write(checkContiguous(arr, N)); // This code is contributed by rakeshsahni </script>
No
Time Complexity: O(N) Auxiliary Space: O(N)
rakeshsahni
lokeshpotta20
_saurabh_jaiswal
ukasp
simranarora5sos
surinderdawra388
simmytarika5
Algo-Geek 2021
Algo Geek
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check if the given string is valid English word or not
Sort strings on the basis of their numeric part
Divide given number into two even parts
Smallest set of vertices to visit all nodes of the given Graph
Count of Palindrome Strings in given Array of strings
Arrays in Java
Arrays in C/C++
Maximum and minimum of an array using minimum number of comparisons
Write a program to reverse an array or string
Program for array rotation
|
[
{
"code": null,
"e": 27509,
"s": 27481,
"text": "\n09 Feb, 2022"
},
{
"code": null,
"e": 27612,
"s": 27509,
"text": "Given an array arr[]. The task is to check whether duplicate elements in arr[] are contiguous or not. "
},
{
"code": null,
"e": 27621,
"s": 27612,
"text": "Examples"
},
{
"code": null,
"e": 27775,
"s": 27621,
"text": "Input: arr[] = {1, 2, 3, 4, 5, 6}Output: YesExplanation: There is no duplicate element in arr[] so there is no need to check anything and answer is Yes. "
},
{
"code": null,
"e": 27894,
"s": 27775,
"text": "Input: arr[] = {1, 2, 2, 4}Output: YesExplanation: 2 is occurring 2 times and it is contiguous. Hence, answer is Yes. "
},
{
"code": null,
"e": 28030,
"s": 27894,
"text": "Input: arr[] = {1, 2, 3, 2, 4}Output: NoExplanation: There is a gap between 2’s and 3 is between two 2’s. Therefore, the answer is No. "
},
{
"code": null,
"e": 28138,
"s": 28030,
"text": "Approach: This problem can be solved by using HashMaps. Follow the steps below to solve the given problem. "
},
{
"code": null,
"e": 28178,
"s": 28138,
"text": "Use maps to store the visited elements."
},
{
"code": null,
"e": 28220,
"s": 28178,
"text": "First, mark the first element on the map."
},
{
"code": null,
"e": 28290,
"s": 28220,
"text": "Traverse the array arr[] from 1 to N-1. where N is the size of arr[]."
},
{
"code": null,
"e": 28419,
"s": 28290,
"text": "If the current element matches the previous element means there is a cycle of one element repeating so simply continue the loop."
},
{
"code": null,
"e": 28484,
"s": 28419,
"text": "If the current element is already marked in the map return “No”."
},
{
"code": null,
"e": 28521,
"s": 28484,
"text": "Mark the current element in the map."
},
{
"code": null,
"e": 28607,
"s": 28521,
"text": "If the function reaches here means there are all contiguous elements so return “Yes”."
},
{
"code": null,
"e": 28659,
"s": 28607,
"text": "Below is the implementation of the above approach. "
},
{
"code": null,
"e": 28665,
"s": 28659,
"text": "C++14"
},
{
"code": null,
"e": 28670,
"s": 28665,
"text": "Java"
},
{
"code": null,
"e": 28678,
"s": 28670,
"text": "Python3"
},
{
"code": null,
"e": 28681,
"s": 28678,
"text": "C#"
},
{
"code": null,
"e": 28692,
"s": 28681,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check whether duplicate// elements in array arr[] are contiguous or notstring checkContiguous(int* arr, int& n){ int i; // Map to keep track of elements unordered_map<int, bool> visited; visited.clear(); visited.insert({ arr[0], 1 }); for (i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) continue; else if (visited[arr[i]]) return \"No\"; visited[arr[i]] = 1; } return \"Yes\";} // Driver Codeint main(){ int arr[] = { 2, 4, 5, 5, 3, 5 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call cout << checkContiguous(arr, N); return 0;}",
"e": 29410,
"s": 28692,
"text": null
},
{
"code": "// Java code for the above approachimport java.io.*; class GFG { // Function to check whether duplicate // elements in array arr[] are contiguous or not static String checkContiguous(int[] arr, int n) { int i; // Map to keep track of elements int[] visited = new int[n]; for (i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) continue; else if (visited[arr[i]] == 0) return \"No\"; visited[arr[i]] = 1; } return \"Yes\"; } // Driver Code public static void main(String[] args) { int arr[] = { 2, 4, 5, 5, 3, 5 }; int N = arr.length; // Function Call System.out.println(checkContiguous(arr, N)); }} // This code is contributed by Potta Lokesh",
"e": 30120,
"s": 29410,
"text": null
},
{
"code": "# Python program for the above approach # Function to check whether duplicate# elements in array arr[] are contiguous or notdef checkContiguous (arr, n): i = None # Map to keep track of elements visited = [0] * n; for i in range(1, n): if (arr[i] == arr[i - 1]): continue; elif (visited[arr[i]] == 0): return \"No\"; visited[arr[i]] = 1; return \"Yes\"; # Driver Code arr = [2, 4, 5, 5, 3, 5];N = len(arr) # Function Callprint(checkContiguous(arr, N)); # This code is contributed by Saurabh Jaiswal",
"e": 30684,
"s": 30120,
"text": null
},
{
"code": "// C# code for the above approachusing System;class GFG { // Function to check whether duplicate // elements in array arr[] are contiguous or not static String checkContiguous(int[] arr, int n) { int i; // Map to keep track of elements int[] visited = new int[n]; for (i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) continue; else if (visited[arr[i]] == 0) return \"No\"; visited[arr[i]] = 1; } return \"Yes\"; } // Driver Code public static void Main() { int[] arr = { 2, 4, 5, 5, 3, 5 }; int N = arr.Length; // Function Call Console.WriteLine(checkContiguous(arr, N)); }} // This code is contributed by ukasp.",
"e": 31367,
"s": 30684,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to check whether duplicate // elements in array arr[] are contiguous or not const checkContiguous = (arr, n) => { let i; // Map to keep track of elements let visited = {}; visited[arr[0]] = 1; for (i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) continue; else if (visited[arr[i]]) return \"No\"; visited[arr[i]] = 1; } return \"Yes\"; } // Driver Code let arr = [2, 4, 5, 5, 3, 5]; let N = arr.length; // Function Call document.write(checkContiguous(arr, N)); // This code is contributed by rakeshsahni </script>",
"e": 32092,
"s": 31367,
"text": null
},
{
"code": null,
"e": 32095,
"s": 32092,
"text": "No"
},
{
"code": null,
"e": 32139,
"s": 32095,
"text": "Time Complexity: O(N) Auxiliary Space: O(N)"
},
{
"code": null,
"e": 32151,
"s": 32139,
"text": "rakeshsahni"
},
{
"code": null,
"e": 32165,
"s": 32151,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 32182,
"s": 32165,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 32188,
"s": 32182,
"text": "ukasp"
},
{
"code": null,
"e": 32204,
"s": 32188,
"text": "simranarora5sos"
},
{
"code": null,
"e": 32221,
"s": 32204,
"text": "surinderdawra388"
},
{
"code": null,
"e": 32234,
"s": 32221,
"text": "simmytarika5"
},
{
"code": null,
"e": 32249,
"s": 32234,
"text": "Algo-Geek 2021"
},
{
"code": null,
"e": 32259,
"s": 32249,
"text": "Algo Geek"
},
{
"code": null,
"e": 32266,
"s": 32259,
"text": "Arrays"
},
{
"code": null,
"e": 32273,
"s": 32266,
"text": "Arrays"
},
{
"code": null,
"e": 32371,
"s": 32273,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32426,
"s": 32371,
"text": "Check if the given string is valid English word or not"
},
{
"code": null,
"e": 32474,
"s": 32426,
"text": "Sort strings on the basis of their numeric part"
},
{
"code": null,
"e": 32514,
"s": 32474,
"text": "Divide given number into two even parts"
},
{
"code": null,
"e": 32577,
"s": 32514,
"text": "Smallest set of vertices to visit all nodes of the given Graph"
},
{
"code": null,
"e": 32631,
"s": 32577,
"text": "Count of Palindrome Strings in given Array of strings"
},
{
"code": null,
"e": 32646,
"s": 32631,
"text": "Arrays in Java"
},
{
"code": null,
"e": 32662,
"s": 32646,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 32730,
"s": 32662,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 32776,
"s": 32730,
"text": "Write a program to reverse an array or string"
}
] |
Set remove() method in Java with Examples - GeeksforGeeks
|
31 Dec, 2018
The java.util.Set.remove(Object O) method is used to remove a particular element from a Set.
Syntax:
boolean remove(Object O)
Parameters: The parameter O is of the type of element maintained by this Set and specifies the element to be removed from the Set.
Return Value: This method returns True if the specified element is present in the Set otherwise it returns False.
Below program illustrate the java.util.Set.remove(Object O) method:
// Java code to illustrate Set.remove() method import java.util.*; public class SetDemo { public static void main(String args[]) { // Creating an empty Set Set<String> set = new HashSet<String>(); // Use add() method to add elements into the Set set.add("Welcome"); set.add("To"); set.add("Geeks"); set.add("4"); set.add("Geeks"); // Displaying the Set System.out.println("Set: " + set); // Removing elements using remove() method set.remove("Geeks"); set.remove("4"); set.remove("Welcome"); // Displaying the Set after removal System.out.println("Set after removing elements: " + set); }}
Set: [4, Geeks, Welcome, To]
Set after removing elements: [To]
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#remove(java.lang.Object)
Java-Collections
Java-Functions
java-set
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
|
[
{
"code": null,
"e": 26319,
"s": 26291,
"text": "\n31 Dec, 2018"
},
{
"code": null,
"e": 26412,
"s": 26319,
"text": "The java.util.Set.remove(Object O) method is used to remove a particular element from a Set."
},
{
"code": null,
"e": 26420,
"s": 26412,
"text": "Syntax:"
},
{
"code": null,
"e": 26445,
"s": 26420,
"text": "boolean remove(Object O)"
},
{
"code": null,
"e": 26576,
"s": 26445,
"text": "Parameters: The parameter O is of the type of element maintained by this Set and specifies the element to be removed from the Set."
},
{
"code": null,
"e": 26690,
"s": 26576,
"text": "Return Value: This method returns True if the specified element is present in the Set otherwise it returns False."
},
{
"code": null,
"e": 26758,
"s": 26690,
"text": "Below program illustrate the java.util.Set.remove(Object O) method:"
},
{
"code": "// Java code to illustrate Set.remove() method import java.util.*; public class SetDemo { public static void main(String args[]) { // Creating an empty Set Set<String> set = new HashSet<String>(); // Use add() method to add elements into the Set set.add(\"Welcome\"); set.add(\"To\"); set.add(\"Geeks\"); set.add(\"4\"); set.add(\"Geeks\"); // Displaying the Set System.out.println(\"Set: \" + set); // Removing elements using remove() method set.remove(\"Geeks\"); set.remove(\"4\"); set.remove(\"Welcome\"); // Displaying the Set after removal System.out.println(\"Set after removing elements: \" + set); }}",
"e": 27505,
"s": 26758,
"text": null
},
{
"code": null,
"e": 27569,
"s": 27505,
"text": "Set: [4, Geeks, Welcome, To]\nSet after removing elements: [To]\n"
},
{
"code": null,
"e": 27666,
"s": 27569,
"text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#remove(java.lang.Object)"
},
{
"code": null,
"e": 27683,
"s": 27666,
"text": "Java-Collections"
},
{
"code": null,
"e": 27698,
"s": 27683,
"text": "Java-Functions"
},
{
"code": null,
"e": 27707,
"s": 27698,
"text": "java-set"
},
{
"code": null,
"e": 27712,
"s": 27707,
"text": "Java"
},
{
"code": null,
"e": 27717,
"s": 27712,
"text": "Java"
},
{
"code": null,
"e": 27734,
"s": 27717,
"text": "Java-Collections"
},
{
"code": null,
"e": 27832,
"s": 27734,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27883,
"s": 27832,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 27913,
"s": 27883,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 27928,
"s": 27913,
"text": "Stream In Java"
},
{
"code": null,
"e": 27947,
"s": 27928,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 27978,
"s": 27947,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 27996,
"s": 27978,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 28028,
"s": 27996,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 28048,
"s": 28028,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 28072,
"s": 28048,
"text": "Singleton Class in Java"
}
] |
Docker - Using Image Tags - GeeksforGeeks
|
31 Oct, 2020
You can use Image tags to describe an image using simple labels and aliases. Tags can simply be the version of the project, features of the Image or simply your name, pretty much anything that can describe the Image. It helps you in managing the version of the project and allows you to keep track of the overall development process.
In this article, we will discuss almost everything related to tags that would help you get started with Image Tagging.
Before diving into this article, let’s discuss something called the latest tag. If you don’t specify a tag to an image, it automatically gets tagged with the latest tag meaning that this Image is of the latest version.
The three most common scenarios where tagging is mostly used that are described below:
You can specify a tag to the image right at the time when you are building it using the -t flag. If you don’t specify a tag, it is automatically tagged with the latest tag.
sudo docker build -t <image-name>:<tag-name>
You can also specify the tag of the Image which you want to pull in the Dockerfile. Let’s say you have a Dockerfile to pull an Ubuntu Image with the latest version.
FROM ubuntu:latest
Now, if you want to build the Image with a custom tag called my-ubuntu, you can use the following command.
sudo docker build -t tag-demo:my-ubuntu .
You can also tag an Image directly using the tag sub-command.
sudo docker tag <imageId> <imageName>/<tagName>
You can see that the new tag has been assigned to the Image.
You can pull a Docker Image using the pull sub-command. You can specify the tag of the Image that you want to pull. Note that if you don’t specify a tag, it will automatically pull the latest version of the Image by appending the “latest” tag to the Image.
sudo docker pull alpine:3.6
Docker Container
linux
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Copying Files to and from Docker Containers
Markov Decision Process
Fuzzy Logic | Introduction
Q-Learning in Python
Principal Component Analysis with Python
Basics of API Testing Using Postman
ML | What is Machine Learning ?
OpenCV - Overview
Deep Learning | Introduction to Long Short Term Memory
Getting Started with System Design
|
[
{
"code": null,
"e": 25493,
"s": 25465,
"text": "\n31 Oct, 2020"
},
{
"code": null,
"e": 25828,
"s": 25493,
"text": "You can use Image tags to describe an image using simple labels and aliases. Tags can simply be the version of the project, features of the Image or simply your name, pretty much anything that can describe the Image. It helps you in managing the version of the project and allows you to keep track of the overall development process. "
},
{
"code": null,
"e": 25947,
"s": 25828,
"text": "In this article, we will discuss almost everything related to tags that would help you get started with Image Tagging."
},
{
"code": null,
"e": 26166,
"s": 25947,
"text": "Before diving into this article, let’s discuss something called the latest tag. If you don’t specify a tag to an image, it automatically gets tagged with the latest tag meaning that this Image is of the latest version."
},
{
"code": null,
"e": 26253,
"s": 26166,
"text": "The three most common scenarios where tagging is mostly used that are described below:"
},
{
"code": null,
"e": 26426,
"s": 26253,
"text": "You can specify a tag to the image right at the time when you are building it using the -t flag. If you don’t specify a tag, it is automatically tagged with the latest tag."
},
{
"code": null,
"e": 26472,
"s": 26426,
"text": "sudo docker build -t <image-name>:<tag-name>\n"
},
{
"code": null,
"e": 26637,
"s": 26472,
"text": "You can also specify the tag of the Image which you want to pull in the Dockerfile. Let’s say you have a Dockerfile to pull an Ubuntu Image with the latest version."
},
{
"code": null,
"e": 26657,
"s": 26637,
"text": "FROM ubuntu:latest\n"
},
{
"code": null,
"e": 26764,
"s": 26657,
"text": "Now, if you want to build the Image with a custom tag called my-ubuntu, you can use the following command."
},
{
"code": null,
"e": 26807,
"s": 26764,
"text": "sudo docker build -t tag-demo:my-ubuntu .\n"
},
{
"code": null,
"e": 26869,
"s": 26807,
"text": "You can also tag an Image directly using the tag sub-command."
},
{
"code": null,
"e": 26918,
"s": 26869,
"text": "sudo docker tag <imageId> <imageName>/<tagName>\n"
},
{
"code": null,
"e": 26979,
"s": 26918,
"text": "You can see that the new tag has been assigned to the Image."
},
{
"code": null,
"e": 27236,
"s": 26979,
"text": "You can pull a Docker Image using the pull sub-command. You can specify the tag of the Image that you want to pull. Note that if you don’t specify a tag, it will automatically pull the latest version of the Image by appending the “latest” tag to the Image."
},
{
"code": null,
"e": 27265,
"s": 27236,
"text": "sudo docker pull alpine:3.6\n"
},
{
"code": null,
"e": 27282,
"s": 27265,
"text": "Docker Container"
},
{
"code": null,
"e": 27288,
"s": 27282,
"text": "linux"
},
{
"code": null,
"e": 27314,
"s": 27288,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 27412,
"s": 27314,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27456,
"s": 27412,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 27480,
"s": 27456,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 27507,
"s": 27480,
"text": "Fuzzy Logic | Introduction"
},
{
"code": null,
"e": 27528,
"s": 27507,
"text": "Q-Learning in Python"
},
{
"code": null,
"e": 27569,
"s": 27528,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 27605,
"s": 27569,
"text": "Basics of API Testing Using Postman"
},
{
"code": null,
"e": 27637,
"s": 27605,
"text": "ML | What is Machine Learning ?"
},
{
"code": null,
"e": 27655,
"s": 27637,
"text": "OpenCV - Overview"
},
{
"code": null,
"e": 27710,
"s": 27655,
"text": "Deep Learning | Introduction to Long Short Term Memory"
}
] |
unordered_map clear in C++ STL - GeeksforGeeks
|
18 Dec, 2018
unordered_map::clear() function is used to remove all elements from the container. When this function is applied to unordered_map its size becomes zero.Syntax:
unordered_map_name.clear()
Parameters: This function does not accepts any parameterReturn type: This function return nothing.
Examples:
Input: ump = { {1, 2}, {3, 4}, {5, 6}, {7, 8}}ump.clear();Output: ump = { };
// CPP program to illustrate// Implementation of unordered_map clear() function#include <bits/stdc++.h>using namespace std; int main(){ // Take any two unordered_map unordered_map<int, int> ump1, ump2; // Inserting values ump1[1] = 2; ump1[3] = 4; ump1[5] = 6; ump1[7] = 8; // Print the size of container cout << "Unordered_map size before calling clear function: \n"; cout << "ump1 size = " << ump1.size() << endl; cout << "ump2 size = " << ump2.size() << endl; // Deleting the elements ump1.clear(); ump2.clear(); // Print the size of container cout << "Unordered_map size after calling clear function: \n"; cout << "ump1 size = " << ump1.size() << endl; cout << "ump2 size = " << ump2.size() << endl; return 0;}
Unordered_map size before calling clear function:
ump1 size = 4
ump2 size = 0
Unordered_map size after calling clear function:
ump1 size = 0
ump2 size = 0
What is the application?clear is used when we wish to delete old elements and start from fresh, especially in loops. We can achieve same functionality by creating a new map, but clearing same map is better performance wise as we do not have to create new object.
cpp-unordered_map
cpp-unordered_map-functions
Picked
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Queue in C++ Standard Template Library (STL)
Inline Functions in C++
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
|
[
{
"code": null,
"e": 25368,
"s": 25340,
"text": "\n18 Dec, 2018"
},
{
"code": null,
"e": 25528,
"s": 25368,
"text": "unordered_map::clear() function is used to remove all elements from the container. When this function is applied to unordered_map its size becomes zero.Syntax:"
},
{
"code": null,
"e": 25557,
"s": 25528,
"text": " unordered_map_name.clear()\n"
},
{
"code": null,
"e": 25656,
"s": 25557,
"text": "Parameters: This function does not accepts any parameterReturn type: This function return nothing."
},
{
"code": null,
"e": 25666,
"s": 25656,
"text": "Examples:"
},
{
"code": null,
"e": 25743,
"s": 25666,
"text": "Input: ump = { {1, 2}, {3, 4}, {5, 6}, {7, 8}}ump.clear();Output: ump = { };"
},
{
"code": "// CPP program to illustrate// Implementation of unordered_map clear() function#include <bits/stdc++.h>using namespace std; int main(){ // Take any two unordered_map unordered_map<int, int> ump1, ump2; // Inserting values ump1[1] = 2; ump1[3] = 4; ump1[5] = 6; ump1[7] = 8; // Print the size of container cout << \"Unordered_map size before calling clear function: \\n\"; cout << \"ump1 size = \" << ump1.size() << endl; cout << \"ump2 size = \" << ump2.size() << endl; // Deleting the elements ump1.clear(); ump2.clear(); // Print the size of container cout << \"Unordered_map size after calling clear function: \\n\"; cout << \"ump1 size = \" << ump1.size() << endl; cout << \"ump2 size = \" << ump2.size() << endl; return 0;}",
"e": 26527,
"s": 25743,
"text": null
},
{
"code": null,
"e": 26685,
"s": 26527,
"text": "Unordered_map size before calling clear function: \nump1 size = 4\nump2 size = 0\nUnordered_map size after calling clear function: \nump1 size = 0\nump2 size = 0\n"
},
{
"code": null,
"e": 26948,
"s": 26685,
"text": "What is the application?clear is used when we wish to delete old elements and start from fresh, especially in loops. We can achieve same functionality by creating a new map, but clearing same map is better performance wise as we do not have to create new object."
},
{
"code": null,
"e": 26966,
"s": 26948,
"text": "cpp-unordered_map"
},
{
"code": null,
"e": 26994,
"s": 26966,
"text": "cpp-unordered_map-functions"
},
{
"code": null,
"e": 27001,
"s": 26994,
"text": "Picked"
},
{
"code": null,
"e": 27005,
"s": 27001,
"text": "C++"
},
{
"code": null,
"e": 27009,
"s": 27005,
"text": "CPP"
},
{
"code": null,
"e": 27107,
"s": 27009,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27135,
"s": 27107,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 27155,
"s": 27135,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 27179,
"s": 27155,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 27212,
"s": 27179,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 27237,
"s": 27212,
"text": "std::string class in C++"
},
{
"code": null,
"e": 27281,
"s": 27237,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 27326,
"s": 27281,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 27350,
"s": 27326,
"text": "Inline Functions in C++"
},
{
"code": null,
"e": 27403,
"s": 27350,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
}
] |
Python | Pandas dataframe.rsub() - GeeksforGeeks
|
24 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.
Pandas dataframe.rsub() function is used for finding the subtraction of dataframe and other, element-wise (binary operator rfloordiv). This function is essentially same as doing other – dataframe but with a support to substitute for missing data in one of the inputs.
Syntax:DataFrame.rsub(other, axis=’columns’, level=None, fill_value=None)Parameters :other : Series, DataFrame, or constantaxis : For Series input, axis to match Series index onlevel : Broadcast across a level, matching Index values on the passed MultiIndex levelfill_value : Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing.
Returns : result : DataFrame
Example #1: Use rsub() function to subtract each element of a series to a corresponding value in a dataframe over the column axis.
# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({"A":[1, 5, 3, 4, 2], "B":[3, 2, 4, 3, 4], "C":[2, 2, 7, 3, 4], "D":[4, 3, 6, 12, 7]}, index =["A1", "A2", "A3", "A4", "A5"]) # Print the dataframedf
Let’s create the series
# importing pandas as pdimport pandas as pd # Create the seriessr = pd.Series([12, 25, 64, 18], index =["A", "B", "C", "D"]) # Print the seriessr
Lets use the dataframe.rsub() function to subtract each element in a series with the corresponding element in the dataframe.
# equivalent to sr - dfdf.rsub(sr, axis = 1)
Output : Example #2: Use rsub() function to subtract each element in a dataframe with the corresponding element in other dataframe
# importing pandas as pdimport pandas as pd # Creating the first dataframe df1 = pd.DataFrame({"A":[1, 5, 3, 4, 2], "B":[3, 2, 4, 3, 4], "C":[2, 2, 7, 3, 4], "D":[4, 3, 6, 12, 7]}, index =["A1", "A2", "A3", "A4", "A5"]) # Creating the second dataframedf2 = pd.DataFrame({"A":[10, 11, 7, 8, 5], "B":[21, 5, 32, 4, 6], "C":[11, 21, 23, 7, 9], "D":[1, 5, 3, 8, 6]}, index =["A1", "A2", "A3", "A4", "A5"]) # Print the first dataframeprint(df1) # Print the second dataframeprint(df2)
Lets perform df2 - df1
# subtract df1 from df2df1.rsub(df2)
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.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n24 Nov, 2018"
},
{
"code": null,
"e": 25751,
"s": 25537,
"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": 26019,
"s": 25751,
"text": "Pandas dataframe.rsub() function is used for finding the subtraction of dataframe and other, element-wise (binary operator rfloordiv). This function is essentially same as doing other – dataframe but with a support to substitute for missing data in one of the inputs."
},
{
"code": null,
"e": 26519,
"s": 26019,
"text": "Syntax:DataFrame.rsub(other, axis=’columns’, level=None, fill_value=None)Parameters :other : Series, DataFrame, or constantaxis : For Series input, axis to match Series index onlevel : Broadcast across a level, matching Index values on the passed MultiIndex levelfill_value : Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing."
},
{
"code": null,
"e": 26548,
"s": 26519,
"text": "Returns : result : DataFrame"
},
{
"code": null,
"e": 26679,
"s": 26548,
"text": "Example #1: Use rsub() function to subtract each element of a series to a corresponding value in a dataframe over the column axis."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({\"A\":[1, 5, 3, 4, 2], \"B\":[3, 2, 4, 3, 4], \"C\":[2, 2, 7, 3, 4], \"D\":[4, 3, 6, 12, 7]}, index =[\"A1\", \"A2\", \"A3\", \"A4\", \"A5\"]) # Print the dataframedf",
"e": 26993,
"s": 26679,
"text": null
},
{
"code": null,
"e": 27017,
"s": 26993,
"text": "Let’s create the series"
},
{
"code": "# importing pandas as pdimport pandas as pd # Create the seriessr = pd.Series([12, 25, 64, 18], index =[\"A\", \"B\", \"C\", \"D\"]) # Print the seriessr",
"e": 27165,
"s": 27017,
"text": null
},
{
"code": null,
"e": 27290,
"s": 27165,
"text": "Lets use the dataframe.rsub() function to subtract each element in a series with the corresponding element in the dataframe."
},
{
"code": "# equivalent to sr - dfdf.rsub(sr, axis = 1)",
"e": 27335,
"s": 27290,
"text": null
},
{
"code": null,
"e": 27466,
"s": 27335,
"text": "Output : Example #2: Use rsub() function to subtract each element in a dataframe with the corresponding element in other dataframe"
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the first dataframe df1 = pd.DataFrame({\"A\":[1, 5, 3, 4, 2], \"B\":[3, 2, 4, 3, 4], \"C\":[2, 2, 7, 3, 4], \"D\":[4, 3, 6, 12, 7]}, index =[\"A1\", \"A2\", \"A3\", \"A4\", \"A5\"]) # Creating the second dataframedf2 = pd.DataFrame({\"A\":[10, 11, 7, 8, 5], \"B\":[21, 5, 32, 4, 6], \"C\":[11, 21, 23, 7, 9], \"D\":[1, 5, 3, 8, 6]}, index =[\"A1\", \"A2\", \"A3\", \"A4\", \"A5\"]) # Print the first dataframeprint(df1) # Print the second dataframeprint(df2)",
"e": 28107,
"s": 27466,
"text": null
},
{
"code": null,
"e": 28130,
"s": 28107,
"text": "Lets perform df2 - df1"
},
{
"code": "# subtract df1 from df2df1.rsub(df2)",
"e": 28167,
"s": 28130,
"text": null
},
{
"code": null,
"e": 28176,
"s": 28167,
"text": "Output :"
},
{
"code": null,
"e": 28200,
"s": 28176,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 28232,
"s": 28200,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 28246,
"s": 28232,
"text": "Python-pandas"
},
{
"code": null,
"e": 28253,
"s": 28246,
"text": "Python"
},
{
"code": null,
"e": 28351,
"s": 28253,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28383,
"s": 28351,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28425,
"s": 28383,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28467,
"s": 28425,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28494,
"s": 28467,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28550,
"s": 28494,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28572,
"s": 28550,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28611,
"s": 28572,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28642,
"s": 28611,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28671,
"s": 28642,
"text": "Create a directory in Python"
}
] |
What is Indentation, Documentation and Program Maintenance? - GeeksforGeeks
|
02 Jul, 2020
Indentation improves the readability of the code. It is mainly used for code inside looping statements, control structures, functions etc. as good intended code is easy to maintain and is good looking. It makes the code more readable and easy to understand. Some programming languages like Python made indentation mandatory instead of using brackets, It makes code easy to read and understand.
Some Rules for indentation are:
Each nested block should be properly indented and spaced with a tab space.
All braces should start from a new line then the code comes following the end braces from a new line.
Example of Some Good Indentation Practices
1. Using Indentation in conditional statements.
C++
#include <iostream>using namespace std; int main(){ int a = 10, b = 20; if (a > b) { cout << "a is greater than b"; } else { cout << "b is greater than a"; } return 0;}
Output:
b is greater than a
2. Using indentation in looping statements.
C++
#include <iostream>using namespace std; int main(){ for (int i = 0; i < 10; i++) { cout << "GeeksforGeeks" << "\n"; } return 0;}
Output:
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
Documentation is a very important aspect of programming. Good documentation in programs make it easy for user to read and understand the code. This is done by inserting comments in the necessary places to make the code readable and more understandable for user. Documentation is basically for users of the code to understand it even without the help of programmer. Add Comments in code and explain the code line and the code will be well Documented.
Example:
C++
#include <iostream>using namespace std; // Main functionint main(){ // Initializing variable a by 10 and b by 20 int a = 10, b = 20; // If a is greater than b go inside if block if (a > b) { // Print a is greater than b cout << "a is greater than b"; } // If a is not greater than b go in else block else { // Print b is greater than a cout << "b is greater than a"; } // End of main function return 0;}
Once the Program is made, it is saved and stored as a software package. After some time if the program needs improvement or modification, the saved program is modified and saves effort and time as programs need not to made from the very beginning. Hence Modifications will meet the purpose only. Program maintenance is done as:
Keep the last program.
Modify the program for required improvements.
Do not make new program from scratch, just use the last saved program.
Save time and effort.
Picked
GBlog
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
How to Start Learning DSA?
Introduction to Recurrent Neural Network
12 pip Commands For Python Developers
7 Things You Didn’t Know About Java
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
C++ Classes and Objects
|
[
{
"code": null,
"e": 26273,
"s": 26245,
"text": "\n02 Jul, 2020"
},
{
"code": null,
"e": 26667,
"s": 26273,
"text": "Indentation improves the readability of the code. It is mainly used for code inside looping statements, control structures, functions etc. as good intended code is easy to maintain and is good looking. It makes the code more readable and easy to understand. Some programming languages like Python made indentation mandatory instead of using brackets, It makes code easy to read and understand."
},
{
"code": null,
"e": 26699,
"s": 26667,
"text": "Some Rules for indentation are:"
},
{
"code": null,
"e": 26774,
"s": 26699,
"text": "Each nested block should be properly indented and spaced with a tab space."
},
{
"code": null,
"e": 26876,
"s": 26774,
"text": "All braces should start from a new line then the code comes following the end braces from a new line."
},
{
"code": null,
"e": 26919,
"s": 26876,
"text": "Example of Some Good Indentation Practices"
},
{
"code": null,
"e": 26967,
"s": 26919,
"text": "1. Using Indentation in conditional statements."
},
{
"code": null,
"e": 26971,
"s": 26967,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; int main(){ int a = 10, b = 20; if (a > b) { cout << \"a is greater than b\"; } else { cout << \"b is greater than a\"; } return 0;}",
"e": 27173,
"s": 26971,
"text": null
},
{
"code": null,
"e": 27181,
"s": 27173,
"text": "Output:"
},
{
"code": null,
"e": 27202,
"s": 27181,
"text": "b is greater than a\n"
},
{
"code": null,
"e": 27246,
"s": 27202,
"text": "2. Using indentation in looping statements."
},
{
"code": null,
"e": 27250,
"s": 27246,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; int main(){ for (int i = 0; i < 10; i++) { cout << \"GeeksforGeeks\" << \"\\n\"; } return 0;}",
"e": 27408,
"s": 27250,
"text": null
},
{
"code": null,
"e": 27416,
"s": 27408,
"text": "Output:"
},
{
"code": null,
"e": 27557,
"s": 27416,
"text": "GeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks\n"
},
{
"code": null,
"e": 28007,
"s": 27557,
"text": "Documentation is a very important aspect of programming. Good documentation in programs make it easy for user to read and understand the code. This is done by inserting comments in the necessary places to make the code readable and more understandable for user. Documentation is basically for users of the code to understand it even without the help of programmer. Add Comments in code and explain the code line and the code will be well Documented."
},
{
"code": null,
"e": 28017,
"s": 28007,
"text": "Example: "
},
{
"code": null,
"e": 28021,
"s": 28017,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; // Main functionint main(){ // Initializing variable a by 10 and b by 20 int a = 10, b = 20; // If a is greater than b go inside if block if (a > b) { // Print a is greater than b cout << \"a is greater than b\"; } // If a is not greater than b go in else block else { // Print b is greater than a cout << \"b is greater than a\"; } // End of main function return 0;}",
"e": 28512,
"s": 28021,
"text": null
},
{
"code": null,
"e": 28840,
"s": 28512,
"text": "Once the Program is made, it is saved and stored as a software package. After some time if the program needs improvement or modification, the saved program is modified and saves effort and time as programs need not to made from the very beginning. Hence Modifications will meet the purpose only. Program maintenance is done as:"
},
{
"code": null,
"e": 28863,
"s": 28840,
"text": "Keep the last program."
},
{
"code": null,
"e": 28909,
"s": 28863,
"text": "Modify the program for required improvements."
},
{
"code": null,
"e": 28980,
"s": 28909,
"text": "Do not make new program from scratch, just use the last saved program."
},
{
"code": null,
"e": 29002,
"s": 28980,
"text": "Save time and effort."
},
{
"code": null,
"e": 29009,
"s": 29002,
"text": "Picked"
},
{
"code": null,
"e": 29015,
"s": 29009,
"text": "GBlog"
},
{
"code": null,
"e": 29034,
"s": 29015,
"text": "School Programming"
},
{
"code": null,
"e": 29132,
"s": 29034,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29157,
"s": 29132,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 29184,
"s": 29157,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 29225,
"s": 29184,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 29263,
"s": 29225,
"text": "12 pip Commands For Python Developers"
},
{
"code": null,
"e": 29299,
"s": 29263,
"text": "7 Things You Didn’t Know About Java"
},
{
"code": null,
"e": 29317,
"s": 29299,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29333,
"s": 29317,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 29352,
"s": 29333,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 29377,
"s": 29352,
"text": "Reverse a string in Java"
}
] |
destroy() method in Tkinter | Python
|
24 Nov, 2021
Tkinter supports a variety of methods to perform various tasks. It also offers some universal method.
destroy() is a universal widget method i.e we can use this method with any of the available widgets as well as with the main tkinter window.
Syntax:
widget_object = Widget(parent, command = widget_class_object.destroy)
This method can be used with after() method.
Code #1: destroy() method passed as command
# importing only those functions# which are neededfrom tkinter import * from tkinter.ttk import * # creating tkinter windowroot = Tk() # Creating button. In this destroy method is passed# as command, so as soon as button 1 is pressed root# window will be destroyedbtn1 = Button(root, text ="Button 1", command = root.destroy)btn1.pack(pady = 10) # Creating button. In this destroy method is passed# as command, so as soon as button 2 is pressed# button 1 will be destroyedbtn2 = Button(root, text ="Button 2", command = btn1.destroy)btn2.pack(pady = 10) # infinite loopmainloop()
Output:
As you may observe, in above code that the command that is passed in button-2 is to destroy button-1 so as soon as you press button-2, button-2 will get destroyed.
Code #2:destroy() method with after() method
# importing only those functions# which are neededfrom tkinter import * from tkinter.ttk import * # creating tkinter windowroot = Tk() # Creating button. In this destroy method is passed# as command, so as soon as button 1 is pressed root# window will be destroyedbtn1 = Button(root, text ="Button 1")btn1.pack(pady = 10) # Creating button. In this destroy method is passed# as command, so as soon as button 2 is pressed# button 1 will be destroyedbtn2 = Button(root, text ="Button 2")btn2.pack(pady = 10) # after method destroying button-1# and button-2 after certain timebtn1.after(3000, btn1.destroy)btn2.after(6000, btn2.destroy) # infinite loopmainloop()
Output:From output you may see that both the widgets are destroyed after a certain time limit and only root window will be left empty.
Note: There is another method available quit() which do not destroy widgets but it exits the tcl/tk interpreter i.e it stops the mainloop().
Python-gui
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 130,
"s": 28,
"text": "Tkinter supports a variety of methods to perform various tasks. It also offers some universal method."
},
{
"code": null,
"e": 271,
"s": 130,
"text": "destroy() is a universal widget method i.e we can use this method with any of the available widgets as well as with the main tkinter window."
},
{
"code": null,
"e": 279,
"s": 271,
"text": "Syntax:"
},
{
"code": null,
"e": 350,
"s": 279,
"text": "widget_object = Widget(parent, command = widget_class_object.destroy)\n"
},
{
"code": null,
"e": 395,
"s": 350,
"text": "This method can be used with after() method."
},
{
"code": null,
"e": 439,
"s": 395,
"text": "Code #1: destroy() method passed as command"
},
{
"code": "# importing only those functions# which are neededfrom tkinter import * from tkinter.ttk import * # creating tkinter windowroot = Tk() # Creating button. In this destroy method is passed# as command, so as soon as button 1 is pressed root# window will be destroyedbtn1 = Button(root, text =\"Button 1\", command = root.destroy)btn1.pack(pady = 10) # Creating button. In this destroy method is passed# as command, so as soon as button 2 is pressed# button 1 will be destroyedbtn2 = Button(root, text =\"Button 2\", command = btn1.destroy)btn2.pack(pady = 10) # infinite loopmainloop()",
"e": 1023,
"s": 439,
"text": null
},
{
"code": null,
"e": 1031,
"s": 1023,
"text": "Output:"
},
{
"code": null,
"e": 1195,
"s": 1031,
"text": "As you may observe, in above code that the command that is passed in button-2 is to destroy button-1 so as soon as you press button-2, button-2 will get destroyed."
},
{
"code": null,
"e": 1240,
"s": 1195,
"text": "Code #2:destroy() method with after() method"
},
{
"code": "# importing only those functions# which are neededfrom tkinter import * from tkinter.ttk import * # creating tkinter windowroot = Tk() # Creating button. In this destroy method is passed# as command, so as soon as button 1 is pressed root# window will be destroyedbtn1 = Button(root, text =\"Button 1\")btn1.pack(pady = 10) # Creating button. In this destroy method is passed# as command, so as soon as button 2 is pressed# button 1 will be destroyedbtn2 = Button(root, text =\"Button 2\")btn2.pack(pady = 10) # after method destroying button-1# and button-2 after certain timebtn1.after(3000, btn1.destroy)btn2.after(6000, btn2.destroy) # infinite loopmainloop()",
"e": 1905,
"s": 1240,
"text": null
},
{
"code": null,
"e": 2040,
"s": 1905,
"text": "Output:From output you may see that both the widgets are destroyed after a certain time limit and only root window will be left empty."
},
{
"code": null,
"e": 2181,
"s": 2040,
"text": "Note: There is another method available quit() which do not destroy widgets but it exits the tcl/tk interpreter i.e it stops the mainloop()."
},
{
"code": null,
"e": 2192,
"s": 2181,
"text": "Python-gui"
},
{
"code": null,
"e": 2207,
"s": 2192,
"text": "Python-tkinter"
},
{
"code": null,
"e": 2214,
"s": 2207,
"text": "Python"
}
] |
C# | Type.GetMethods() Method
|
16 Dec, 2019
Type.GetMethods() Method is used to get the methods of the current Type. There are 2 methods in the overload list of this method as follows:
GetMethods(BindingFlags) Method
GetMethods() Method
This method is used to search for the methods defined for the current Type, using the specified binding constraints when overridden in a derived class.
Syntax: public abstract System.Reflection.MethodInfo[] GetMethods (System.Reflection.BindingFlags bindingAttr);Here, it takes a bitmask comprised of one or more BindingFlags which specify how the search is conducted or,Zero (Default), to return an empty array.
Return Value: This method returns an array of MethodInfo objects representing all methods defined for the current Type which match the specified binding constraints Or an empty array of type MethodInfo, if no methods are defined for the current Type, or if none of the defined methods match the binding constraints.
Below programs illustrate the use of Type.GetMethods(BindingFlags) Method:
Example 1:
// C# program to demonstrate the// Type.GetMethods() Methodusing System;using System.Globalization;using System.Reflection; // Defining class Emptypublic class Empty { } class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(Empty); // try-catch block for handling Exception try { // Getting array of Method by // using GetMethods() Method MethodInfo[] info = objType.GetMethods(BindingFlags.Public | BindingFlags.Instance); // Display the Result Console.WriteLine("Methods of current type is as Follow: "); for (int i = 0; i < info.Length; i++) Console.WriteLine(" {0}", info[i]); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.Write("name is null."); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
Methods of current type is as Follow:
Boolean Equals(System.Object)
Int32 GetHashCode()
System.Type GetType()
System.String ToString()
Example 2:
// C# program to demonstrate the// Type.GetMethods() Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(int); // try-catch block for handling Exception try { // Getting array of Method by // using GetMethods() Method MethodInfo[] info = objType.GetMethods(BindingFlags.Public | BindingFlags.Static); // Display the Result Console.WriteLine("Methods of current type is as Follow: "); for (int i = 0; i < info.Length; i++) Console.WriteLine(" {0}", info[i]); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.Write("name is null."); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
Methods of current type is as Follow:
Int32 Parse(System.String)
Int32 Parse(System.String, System.Globalization.NumberStyles)
Int32 Parse(System.String, System.IFormatProvider)
Int32 Parse(System.String, System.Globalization.NumberStyles, System.IFormatProvider)
Boolean TryParse(System.String, Int32 ByRef)
Boolean TryParse(System.String, System.Globalization.NumberStyles, System.IFormatProvider, Int32 ByRef)
This method is used to return all the public methods of the current Type.
Syntax: public System.Reflection.MethodInfo[] GetMethods ();
Return Value: This method returns an array of MethodInfo objects representing all the public methods defined for the current Type or an empty array of type MethodInfo if no public methods are defined for the current Type.
Below programs illustrate the use of the above-discussed method:
Example 1:
// C# program to demonstrate the// Type.GetMethods() Methodusing System;using System.Globalization;using System.Reflection; // Defining class Emptyclass Empty { } class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(Empty); // try-catch block for handling Exception try { // Getting array of Method by // using GetMethods() Method MethodInfo[] info = objType.GetMethods(); // Display the Result Console.WriteLine("Methods of current type is as Follow: "); for (int i = 0; i < info.Length; i++) Console.WriteLine(" {0}", info[i]); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.Write("name is null."); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
Methods of current type is as Follow:
Boolean Equals(System.Object)
Int32 GetHashCode()
System.Type GetType()
System.String ToString()
Example 2:
// C# program to demonstrate the// Type.GetMethods() Methodusing System;using System.Globalization;using System.Reflection; // Defining class Studentpublic class Student { private string name, dept; private int roll; // Constructor public Student(string name, int roll, string dept) { this.name = name; this.roll = roll; this.dept = dept; } // getter for name public string getName() { return name; } // getter for roll public int getRoll() { return roll; } // getter for dept public string getDept() { return dept; }} class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(Student); // try-catch block for handling Exception try { // Getting array of Method by // using GetMethods() Method MethodInfo[] info = objType.GetMethods(BindingFlags.Public | BindingFlags.Instance); // Display the Result Console.WriteLine("Methods of current type is as Follow: "); for (int i = 0; i < info.Length; i++) Console.WriteLine(" {0}", info[i]); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.Write("name is null."); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
Methods of current type is as Follow:
System.String getName()
Int32 getRoll()
System.String getDept()
Boolean Equals(System.Object)
Int32 GetHashCode()
System.Type GetType()
System.String ToString()
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.type.getmethods?view=netframework-4.8
shubham_singh
CSharp-method
CSharp-Type-Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
Extension Method in C#
C# | List Class
C# | .NET Framework (Basic Architecture and Component Stack)
HashSet in C# with Examples
Lambda Expressions in C#
Switch Statement in C#
Partial Classes in C#
Hello World in C#
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Dec, 2019"
},
{
"code": null,
"e": 169,
"s": 28,
"text": "Type.GetMethods() Method is used to get the methods of the current Type. There are 2 methods in the overload list of this method as follows:"
},
{
"code": null,
"e": 201,
"s": 169,
"text": "GetMethods(BindingFlags) Method"
},
{
"code": null,
"e": 221,
"s": 201,
"text": "GetMethods() Method"
},
{
"code": null,
"e": 373,
"s": 221,
"text": "This method is used to search for the methods defined for the current Type, using the specified binding constraints when overridden in a derived class."
},
{
"code": null,
"e": 634,
"s": 373,
"text": "Syntax: public abstract System.Reflection.MethodInfo[] GetMethods (System.Reflection.BindingFlags bindingAttr);Here, it takes a bitmask comprised of one or more BindingFlags which specify how the search is conducted or,Zero (Default), to return an empty array."
},
{
"code": null,
"e": 950,
"s": 634,
"text": "Return Value: This method returns an array of MethodInfo objects representing all methods defined for the current Type which match the specified binding constraints Or an empty array of type MethodInfo, if no methods are defined for the current Type, or if none of the defined methods match the binding constraints."
},
{
"code": null,
"e": 1025,
"s": 950,
"text": "Below programs illustrate the use of Type.GetMethods(BindingFlags) Method:"
},
{
"code": null,
"e": 1036,
"s": 1025,
"text": "Example 1:"
},
{
"code": "// C# program to demonstrate the// Type.GetMethods() Methodusing System;using System.Globalization;using System.Reflection; // Defining class Emptypublic class Empty { } class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(Empty); // try-catch block for handling Exception try { // Getting array of Method by // using GetMethods() Method MethodInfo[] info = objType.GetMethods(BindingFlags.Public | BindingFlags.Instance); // Display the Result Console.WriteLine(\"Methods of current type is as Follow: \"); for (int i = 0; i < info.Length; i++) Console.WriteLine(\" {0}\", info[i]); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.Write(\"name is null.\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 2078,
"s": 1036,
"text": null
},
{
"code": null,
"e": 2219,
"s": 2078,
"text": "Methods of current type is as Follow: \n Boolean Equals(System.Object)\n Int32 GetHashCode()\n System.Type GetType()\n System.String ToString()\n"
},
{
"code": null,
"e": 2230,
"s": 2219,
"text": "Example 2:"
},
{
"code": "// C# program to demonstrate the// Type.GetMethods() Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(int); // try-catch block for handling Exception try { // Getting array of Method by // using GetMethods() Method MethodInfo[] info = objType.GetMethods(BindingFlags.Public | BindingFlags.Static); // Display the Result Console.WriteLine(\"Methods of current type is as Follow: \"); for (int i = 0; i < info.Length; i++) Console.WriteLine(\" {0}\", info[i]); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.Write(\"name is null.\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 3222,
"s": 2230,
"text": null
},
{
"code": null,
"e": 3643,
"s": 3222,
"text": "Methods of current type is as Follow: \n Int32 Parse(System.String)\n Int32 Parse(System.String, System.Globalization.NumberStyles)\n Int32 Parse(System.String, System.IFormatProvider)\n Int32 Parse(System.String, System.Globalization.NumberStyles, System.IFormatProvider)\n Boolean TryParse(System.String, Int32 ByRef)\n Boolean TryParse(System.String, System.Globalization.NumberStyles, System.IFormatProvider, Int32 ByRef)\n"
},
{
"code": null,
"e": 3717,
"s": 3643,
"text": "This method is used to return all the public methods of the current Type."
},
{
"code": null,
"e": 3778,
"s": 3717,
"text": "Syntax: public System.Reflection.MethodInfo[] GetMethods ();"
},
{
"code": null,
"e": 4000,
"s": 3778,
"text": "Return Value: This method returns an array of MethodInfo objects representing all the public methods defined for the current Type or an empty array of type MethodInfo if no public methods are defined for the current Type."
},
{
"code": null,
"e": 4065,
"s": 4000,
"text": "Below programs illustrate the use of the above-discussed method:"
},
{
"code": null,
"e": 4076,
"s": 4065,
"text": "Example 1:"
},
{
"code": "// C# program to demonstrate the// Type.GetMethods() Methodusing System;using System.Globalization;using System.Reflection; // Defining class Emptyclass Empty { } class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(Empty); // try-catch block for handling Exception try { // Getting array of Method by // using GetMethods() Method MethodInfo[] info = objType.GetMethods(); // Display the Result Console.WriteLine(\"Methods of current type is as Follow: \"); for (int i = 0; i < info.Length; i++) Console.WriteLine(\" {0}\", info[i]); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.Write(\"name is null.\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 5069,
"s": 4076,
"text": null
},
{
"code": null,
"e": 5210,
"s": 5069,
"text": "Methods of current type is as Follow: \n Boolean Equals(System.Object)\n Int32 GetHashCode()\n System.Type GetType()\n System.String ToString()\n"
},
{
"code": null,
"e": 5221,
"s": 5210,
"text": "Example 2:"
},
{
"code": "// C# program to demonstrate the// Type.GetMethods() Methodusing System;using System.Globalization;using System.Reflection; // Defining class Studentpublic class Student { private string name, dept; private int roll; // Constructor public Student(string name, int roll, string dept) { this.name = name; this.roll = roll; this.dept = dept; } // getter for name public string getName() { return name; } // getter for roll public int getRoll() { return roll; } // getter for dept public string getDept() { return dept; }} class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(Student); // try-catch block for handling Exception try { // Getting array of Method by // using GetMethods() Method MethodInfo[] info = objType.GetMethods(BindingFlags.Public | BindingFlags.Instance); // Display the Result Console.WriteLine(\"Methods of current type is as Follow: \"); for (int i = 0; i < info.Length; i++) Console.WriteLine(\" {0}\", info[i]); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.Write(\"name is null.\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 6720,
"s": 5221,
"text": null
},
{
"code": null,
"e": 6928,
"s": 6720,
"text": "Methods of current type is as Follow: \n System.String getName()\n Int32 getRoll()\n System.String getDept()\n Boolean Equals(System.Object)\n Int32 GetHashCode()\n System.Type GetType()\n System.String ToString()\n"
},
{
"code": null,
"e": 6939,
"s": 6928,
"text": "Reference:"
},
{
"code": null,
"e": 7028,
"s": 6939,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.type.getmethods?view=netframework-4.8"
},
{
"code": null,
"e": 7042,
"s": 7028,
"text": "shubham_singh"
},
{
"code": null,
"e": 7056,
"s": 7042,
"text": "CSharp-method"
},
{
"code": null,
"e": 7074,
"s": 7056,
"text": "CSharp-Type-Class"
},
{
"code": null,
"e": 7077,
"s": 7074,
"text": "C#"
},
{
"code": null,
"e": 7175,
"s": 7077,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7218,
"s": 7175,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 7267,
"s": 7218,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 7290,
"s": 7267,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 7306,
"s": 7290,
"text": "C# | List Class"
},
{
"code": null,
"e": 7367,
"s": 7306,
"text": "C# | .NET Framework (Basic Architecture and Component Stack)"
},
{
"code": null,
"e": 7395,
"s": 7367,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 7420,
"s": 7395,
"text": "Lambda Expressions in C#"
},
{
"code": null,
"e": 7443,
"s": 7420,
"text": "Switch Statement in C#"
},
{
"code": null,
"e": 7465,
"s": 7443,
"text": "Partial Classes in C#"
}
] |
Python Arcade – Handling Mouse Inputs
|
23 Sep, 2021
In this article, we will learn how we can handle mouse inputs in the arcade module in Python.
In Arcade, you can easily handle the mouse inputs using these functions:
on_mouse_motion():
Syntax: on_mouse_motion(x, y, dx, dy)
Parameters:
x : x coordinate
y : y coordinate
dx : change in x coordinate
dy : change in y coordinate
on_mouse_press():
Syntax : on_mouse_press( x, y, button, modifiers)
Parameters:
x : x coordinate
y : y coordinate
button : button that is pressed
modifiers : Bitwise ‘and’ of all modifiers (shift, ctrl, num lock) pressed during this event.
on_mouse_motion() function will be called whenever the user moves the mouse. Similarly, on_mouse_press() will be called whenever a user presses a mouse button.
Here we will create a simple program using the arcade module to move our character using mouse inputs.
In the below example, we are going to create a MainGame() class. Inside this class first, we will initialize the starting x and y coordinate of the player. Then we will create three functions inside this class.
on_draw():- Inside this function, we will start the rendering using arcade.start_render() and then we will draw our player.
on_mouse_motion():- This function will be called whenever the user moves the mouse. Inside this function, we will change the x and y coordinate of the player.
Below is the implementation:
Python3
# Importing arcade moduleimport arcade # Creating MainGame classclass MainGame(arcade.Window): def __init__(self): super().__init__(600, 600, title="Keyboard Inputs") # Starting location of player self.x = 100 self.y = 100 # Creating on_draw() function to draw on the screen def on_draw(self): arcade.start_render() # Drawing our player arcade.draw_circle_filled(self.x, self.y, 25, arcade.color.GREEN) # Creating function to check the position # of the mouse def on_mouse_motion(self, x, y, dx, dy): """ Called whenever the mouse moves. """ self.x = x self.y = y # Calling MainGame classMainGame()arcade.run()
Output:
Now to handle mouse clicks we are going to create a new function called “on_mouse_press”. This function will be called every time user clicks a mouse button.
Python3
# Importing arcade moduleimport arcade # Creating MainGame class class MainGame(arcade.Window): def __init__(self): super().__init__(600, 600, title="Keyboard Inputs") # Starting location of player self.x = 100 self.y = 100 # Creating on_draw() function to draw on the screen def on_draw(self): arcade.start_render() # Drawing our player arcade.draw_circle_filled(self.x, self.y,25, arcade.color.GREEN ) # Creating function to check the position # of the mouse def on_mouse_motion(self, x, y, dx, dy): """ Called whenever the mouse moves. """ self.x = x self.y = y # Creating function to check the mouse clicks def on_mouse_press(self, x, y, button, modifiers): print("Mouse button is pressed") # Calling MainGame class MainGame()arcade.run()
Output:
Python-Arcade
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Sep, 2021"
},
{
"code": null,
"e": 146,
"s": 52,
"text": "In this article, we will learn how we can handle mouse inputs in the arcade module in Python."
},
{
"code": null,
"e": 219,
"s": 146,
"text": "In Arcade, you can easily handle the mouse inputs using these functions:"
},
{
"code": null,
"e": 238,
"s": 219,
"text": "on_mouse_motion():"
},
{
"code": null,
"e": 276,
"s": 238,
"text": "Syntax: on_mouse_motion(x, y, dx, dy)"
},
{
"code": null,
"e": 288,
"s": 276,
"text": "Parameters:"
},
{
"code": null,
"e": 305,
"s": 288,
"text": "x : x coordinate"
},
{
"code": null,
"e": 322,
"s": 305,
"text": "y : y coordinate"
},
{
"code": null,
"e": 350,
"s": 322,
"text": "dx : change in x coordinate"
},
{
"code": null,
"e": 378,
"s": 350,
"text": "dy : change in y coordinate"
},
{
"code": null,
"e": 396,
"s": 378,
"text": "on_mouse_press():"
},
{
"code": null,
"e": 446,
"s": 396,
"text": "Syntax : on_mouse_press( x, y, button, modifiers)"
},
{
"code": null,
"e": 458,
"s": 446,
"text": "Parameters:"
},
{
"code": null,
"e": 475,
"s": 458,
"text": "x : x coordinate"
},
{
"code": null,
"e": 492,
"s": 475,
"text": "y : y coordinate"
},
{
"code": null,
"e": 524,
"s": 492,
"text": "button : button that is pressed"
},
{
"code": null,
"e": 618,
"s": 524,
"text": "modifiers : Bitwise ‘and’ of all modifiers (shift, ctrl, num lock) pressed during this event."
},
{
"code": null,
"e": 778,
"s": 618,
"text": "on_mouse_motion() function will be called whenever the user moves the mouse. Similarly, on_mouse_press() will be called whenever a user presses a mouse button."
},
{
"code": null,
"e": 881,
"s": 778,
"text": "Here we will create a simple program using the arcade module to move our character using mouse inputs."
},
{
"code": null,
"e": 1092,
"s": 881,
"text": "In the below example, we are going to create a MainGame() class. Inside this class first, we will initialize the starting x and y coordinate of the player. Then we will create three functions inside this class."
},
{
"code": null,
"e": 1216,
"s": 1092,
"text": "on_draw():- Inside this function, we will start the rendering using arcade.start_render() and then we will draw our player."
},
{
"code": null,
"e": 1375,
"s": 1216,
"text": "on_mouse_motion():- This function will be called whenever the user moves the mouse. Inside this function, we will change the x and y coordinate of the player."
},
{
"code": null,
"e": 1404,
"s": 1375,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 1412,
"s": 1404,
"text": "Python3"
},
{
"code": "# Importing arcade moduleimport arcade # Creating MainGame classclass MainGame(arcade.Window): def __init__(self): super().__init__(600, 600, title=\"Keyboard Inputs\") # Starting location of player self.x = 100 self.y = 100 # Creating on_draw() function to draw on the screen def on_draw(self): arcade.start_render() # Drawing our player arcade.draw_circle_filled(self.x, self.y, 25, arcade.color.GREEN) # Creating function to check the position # of the mouse def on_mouse_motion(self, x, y, dx, dy): \"\"\" Called whenever the mouse moves. \"\"\" self.x = x self.y = y # Calling MainGame classMainGame()arcade.run()",
"e": 2168,
"s": 1412,
"text": null
},
{
"code": null,
"e": 2176,
"s": 2168,
"text": "Output:"
},
{
"code": null,
"e": 2334,
"s": 2176,
"text": "Now to handle mouse clicks we are going to create a new function called “on_mouse_press”. This function will be called every time user clicks a mouse button."
},
{
"code": null,
"e": 2342,
"s": 2334,
"text": "Python3"
},
{
"code": "# Importing arcade moduleimport arcade # Creating MainGame class class MainGame(arcade.Window): def __init__(self): super().__init__(600, 600, title=\"Keyboard Inputs\") # Starting location of player self.x = 100 self.y = 100 # Creating on_draw() function to draw on the screen def on_draw(self): arcade.start_render() # Drawing our player arcade.draw_circle_filled(self.x, self.y,25, arcade.color.GREEN ) # Creating function to check the position # of the mouse def on_mouse_motion(self, x, y, dx, dy): \"\"\" Called whenever the mouse moves. \"\"\" self.x = x self.y = y # Creating function to check the mouse clicks def on_mouse_press(self, x, y, button, modifiers): print(\"Mouse button is pressed\") # Calling MainGame class MainGame()arcade.run()",
"e": 3286,
"s": 2342,
"text": null
},
{
"code": null,
"e": 3294,
"s": 3286,
"text": "Output:"
},
{
"code": null,
"e": 3308,
"s": 3294,
"text": "Python-Arcade"
},
{
"code": null,
"e": 3315,
"s": 3308,
"text": "Python"
}
] |
Julia Tutorial for 3D Data Science. Florent Poux | Towards Data Science
|
If you are always on the lookout for great ideas and new “tools” that make them easier to achieve, then you may have heard of Julia before. A very young language that is less than ten years old 👶, and that is a super cool way to get into fast scripting/coding for quickly achieving working ideas 🌼.
Supposing you are into scientific computing, machine learning, data mining, 3D data science, large-scale linear algebra, distributed and parallel computing, I think it is worth following up on this hands-on tutorial to get started with Julia and start doing fun 3D stuff!
In this newcomer tutorial, I will cut straight through the matter and provide you with a laser-focused 6-step workflow to get up and running with 3D data within the next ten minutes! Ready?
Ha, but before, I want to highlight the ambitions of the creators of Julia. The creators of Julia, namely Jeff Bezanson, Stefan Karpinski, Viral B. Shah, and Alan Edelman. They blogged in 2012 about their aspirations and essentially why they initiated the Julia movement:
We want a language that’s open source, with a liberal license. We want the speed of C with the dynamism of Ruby. We want a language that’s homoiconic, with true macros like Lisp, but with obvious, familiar mathematical notation like Matlab. We want something as usable for general programming as Python, as easy for statistics as R, as natural for string processing as Perl, as powerful for linear algebra as Matlab, as good at gluing programs together as the shell. Something that is dirt simple to learn, yet keeps the most serious hackers happy. We want it interactive and we want it compiled. It should be as fast as C.
But do these claims hold 🤔? Is this an “I want it all” language? Well, I first discovered Julia in early 2019, when I was making a research visit to the Visual Computing Institute (Computer Graphics) in RWTH Aachen University (Deutschland).
www.vci.rwth-aachen.de
Since then, I swear almost essentially through Julia! And that comes from a Pythonista/C “programmer” mindset. It is super clear, effortless to pick up, super-fast, and you can loop python scripts within, call your favorite libraries directly, and pure Julia will execute crazy fast! Indeed, Julia is compiled, not interpreted. For faster runtime performance, Julia is just-in-time (JIT) compiled using the LLVM compiler framework. At its best, Julia can approach or match the speed of C, and that is awesome 🚀! In three words, I would say that Julia is Fast, Dynamic with Reproducible environments.
⚠️ A warning, though, at the time of the writing, the documentation and tutorials are still very sparse, and the community is also pretty small compared to what you would be used to if using Python. But hey, I intend to change that a bit. Shall we dive in?
Okay, now that you have your coffee ☕ or teacup 🍵 next to you, ready to find our way into the fog, let us dive in! First, we need to download Julia from the official website: https://julialang.org/downloads/
Note: This tutorial is made with Julia version 1.6.2, 64bits using windows, but you can use any stable release, which should work (in principle 😉).
Install the pretty stuff once the executable is downloaded until you have shiny “software” ready for your beautiful hands!
Julia supports various editors like VSCode, Atom, Emacs, Sublime, Vim, Notepad++, and IDEs like IntelliJ. If you like Jupyter notebooks, you can also use them directly with Julia. For this tutorial, I will show you my favorite three choices to choose from.
It would be the first choice to demo your project in a powerpoint-style fashion or if what you intend to do is more linked to an exploratory data analysis. For this, nothing simpler, launch your freshly installed Julia executable, then a window like below should pop up.
From there, all you have to do is to type the command using Pkg and then press Enter followed by the command Pkg.add("IJulia") and Enter. The process of installing the IJulia package necessary to use Julia within Jupyter Notebooks takes around 1 minute.
Then, you can launch Anaconda Navigator (with GUI) from which Jupyter Notebook on the environment of your choosing.
Note: If you do not have Anaconda installed, you can follow the tutorial below:
towardsdatascience.com
Once opened, you can create a new notebook with Julia acting as the programming language (see below for starting a new notebook)
I tend to favor the Atom+Juno combination, which allows you to benefit from an interactive REPL mode, much like what you would be used to with Spyder. If you choose to follow these footsteps, you first need to install Atom in your system following the instructions given at https://atom.io/.
Then, you can launch Atom and head over to the package installation settings through Packages>Settings view>Open or the shortcut Ctrl+,. There search for juno and then click the install button for uber-juno and if not installed juno-client. Once Juno is installed, you can try opening the REPL with Juno > Open REPL or Ctrl+J Ctrl+O (Cmd+J Cmd+O on macOS), and then pressing Enter in the REPL to start a Julia session. And that is it! We are ready to code!
Note: If the REPL does not seem to launch correctly and does not display the Julia logo, head over to the Juno Client Settings from the Package menu and verify the path to tour Julia executable.
You can also use a google Colab environment, but that needs a specif block of code to use Julia instead of Python. For this, you will find at this link a template that makes it possible to work directly within Colab. It also contains the main code of this tutorial.
Note: Every time you want to use Julia on the Google Cloud, you need to run the first block, refresh the page, and continue directly to the second block without re-running the first until every element is ready for you.
Great, so now we are ready to Julia code. First, let us discover where we are working, so our current working directory, using the command pwd(). Hmm, it looks like we are in the base directory, so let us change it to a project directory that you would create where you want to store most of your project (data, results, ...) with cd(“C://DEV/JULIA/TUTORIALS/3D_PROJECT_1”), followed by pwd() to check out the new path.
Okay, we are all set. Let us download a dataset, for starters, a small noisy point cloud. For this, very handy, you can use the following command:
download("https://raw.githubusercontent.com/florentPoux/3D-small-datasets/main/tree_sample.csv","point_cloud_sample.csv")
Note: The download() command first takes the link to the data you want to download, which I dropped on my GitHub account, and then specifies its name locally after download.
Great, we now have a local version of the data in our working directory that we specified with the cd() command. Now, how do we load it in the script? well, we will make use of a Package called DelimitedFiles.
Note: A Package is a handy set of functions, methods, classes, and more that allow you to build on existing code without writing everything from scratch. The DelimitedFiles package allows manipulating (e.g., read and write) delimited files like our current point cloud at hand.
For using a package, we first have to load the package manager utility by just typing using Pkg. To add a new package, it is pretty simple; we just write Pkg.add(“DelimitedFiles”), and wait until the download + requirement checks are finished.
What is great about this is that you do not have to worry about dependencies (other packages needed by the current) as all is handled for you! Cool, huh? And on top, we can create excellent packages easily to ensure reproducibility of the results, for example, and independent environments, but that is for another tutorial 😉.
Note: Managing packages is then pretty straightforward, and we have a bunch of functions to update the packages, to know their current status, if we have any conflicts between them (rare), or to load unregistered packages by other like-minded coders, even one of your future local package 😉. I usually manage them by using the REPL and entering the package manager with the command ] in the right environment. To exit the package manager, one needs just to do Ctrl+C .
Ok, now that the package is installed (you only need to run this once per environment). You can use it in your current project by typing using DelimitedFiles, and also, if there are no conflicts of function names, you do not need to write from which package a function comes. to read a delimited file DelimitedFiles.readdlm() is equivalent to readdlm().
From there, let us read the point cloud at hand and store the data in the variable pointlist:
pointlist=readdlm(“point_cloud_sample.csv”,’;’)
The first lines should look like below.
Okay, pretty cool up until now, hun? And now, let us see the first real surprise if you are used to other programming languages: indexing. You can try doing pointlist[0] to retrieve the first element. What are we getting? a BoundsError.
Haha, in Julia, indexes start at 1, so if you want to retrieve the first element (the X coordinate of the first point), you just input pointlist[1] that returns 41.61793137. A bit confusing at first, it is pretty handy and logical, at least from a scientific point of view 😅. So now, if you want to retrieve the first point, then you need to know that indexes work on the first axis (rows) first, followed by the second axis (column(s)), and so on. Thus, to retrieve the first point (first row and every column):
pointlist[1,:]
Very cool, and now, to get further, if we want to store the coordinates in the points variables and the normals in the normals variable, we just do:
points = pointlist[:,1:3]normals = pointlist[:,4:6]
Note: If you want to know the type of a variable, typeof() is what you are looking for. typeof(points)will display that we deal with Matrices, which are an alias of 2-dimensional arrays. Also Float64 is a computer number format, usually occupying 64 bits in computer memory; it represents a wide dynamic range of numeric values by using a floating radix point. Double precision may be chosen when the range or precision of single-precision (Float32) would be insufficient.
One last straightforward pre-processing step would be to know how to quickly sample the variable extracting, let say, 1 line every tenth. For this, we can do the following (a bit like Python, but we need to put the word end to treat the total variable):
points_sampled=points[1:10:end,:]
We first work on rows, taking one every tenth, and for each line, we keep all columns with : following ,.
Hint: There are many ways to sample a dataset, but it is always important to balance the gain performance/results. This way is pretty quick and straightforward to execute; thus, it usually acts to get first visual results to know what we are dealing with without using too much memory. If you want to dive deeper, I recommend you follow through with the following tutorial. The adaptation to Julia should not be too problematic 😉.
towardsdatascience.com
We now are ready to address 3D data visualization, a critical step to grasp what we are dealing with! Here, one library is the go-to solution: Makie. Because we didn’t use it yet, we first need to import the package, along with two other “backends” depending on your paradigm (webGL visualization or OpenGL visualization), namely WGLMakie and GLMakie. Nothing more straightforward, we just run the following three lines only once:
Pkg.add(“Makie”)Pkg.add(“WGLMakie”)Pkg.add(“GLMakie”)
Note: Once executed, if anytime you want to explore the packages you have installed in your current environment, you can use the command Pkg.installed().
Once the needed packages are installed, to make them usable in your working session, you can add the line using Makie, GLMakie (or using Makie, WGLMakie if you want interactivity on the web with Colab or Jupyter), much like import matplotlib in Python.
Nice, now, before visualizing, let us prepare a bit of color for our colorless points, depending on their z-value. We will create a color vector the size of the sampled point cloud that will range from 0 to 1, depending on how close to the maximum value it is, by dividing each point:
zcoloring_scale=points_sampled[:,3]/maximum(points_sampled[:,3])
Hint: Julia automatically understands that you want to divide each element from points_sampled[:,3] by the maximum value with maximum() . Handy, huh? But it is a particular case of broadcasting, which in Julia, you just write by inputting a . before your function or mathematic symbol. If you do ./ here, you will get the same result.
Okay, now, all we have to do is plot our results as a scattered point cloud in 3D. For this, we use the scatter function from Makie, and we pass as arguments the coordinates of the points (points_sampled), the color vector zcoloring_scale, and also some parameters like the size of each point with markersize, and if we want to display the axis.
scatter(points_sampled, color=zcoloring_scale, markersize=100, show_axis=true)
You also can do a meshscatter plot that will generate a small sphere for each point (like the image above on the right)
scene_1 = meshscatter(points_sampled, color=zcoloring_scale, markersize=0.2, show_axis=true)
How very cool! If you want some interactivity on the web, you should make sure to use WGLMakie instead of GLMakie, which will just give you a fixed backend to generate a view.
Hint: If you want to print your figure to a file, an effortless way is to first install the FileIO package using Pkg.add(“FileIO”) and using FileIO that holds the necessary methods and function to deal with a lot of file formats incl. meshes, images, vectors ... Once available in your running session, a simple save(“scatter.png”, scene_1) will save the plot to an image in your working directory.
An effortless way to display a mesh is to use FileIO, like hinted above. In two simple lines, you can display your mesh. Take the one available on my GitHub like the point cloud before with:
download("https://raw.githubusercontent.com/florentPoux/3D-small-datasets/main/hippo_1k.obj","hippo_1k.obj")
and then, you can just store it in the obj variable with:
obj = load(“hippo_1k.obj”)
that you pass to the Makie.mesh() function shortened to mesh() to display your 3D model.
mesh(obj, color=”honeydew2”, show_axis=false)
If this is not optimized code clarity, I do not know what it is 😆!
Hint: If you want to access the single-shot color names, check out this link that gives all the available possibilities, and there are a lot 🙃.
Now we can explore a bit the data and play around with some functions. The first thing would be to know how to access a specific portion of the 3D point cloud dataset. In our case, we would like to find and separate (more or less) the ground from the rest. First, we would find through visualization the higher z of the ground and then use that as a threshold. Let us plot the 2D projection of the dataset:
scatter(points_sampled[:,2:3], color=zcoloring_scale, markersize=100, show_axis=true)
We can identify that we get a threshold at more or less 3 meters (red line). Let us use it directly for our experiments.
Hint: If you want to display other elements on the same figure, a simple way to do is to add ! to the following plots, like if you want to display the y=3 line in red like above, you would do lines!(range(38, 60, length=30),(x*0).+3, color=”red”) and admire the results with the commandcurrent_figure() 😀.
Now we want to find all points below and above the visually defined threshold and store them in a separate variable. We will use the findall function that returns the indexes of the points satisfying the condition in brackets. Let us work solely on points[:,3] as we just need to study this and retrieve indexes that we can later use to filter our full point cloud. How cool 😆?
indexes_ground=findall(x->x < 3, points[:,3])indexes_tree=findall(x->x>=3, points[:,3])
Very nice! Now, if we would like to get the points corresponding to these indexes list, we just have to pass indexes_ground or indexes_tree as a row selector in the points variable, for example, for getting all the points that belong to the ground and all the rest. And if we want to plot this, then we can do:
meshscatter(points[indexes_ground,:], color=”navajowhite4”, markersize=0.3, show_axis=false)meshscatter!(points[indexes_tree,:], color=”honeydew3”, markersize=0.3, show_axis=false)current_figure()
Awesome! We just did a manual instance segmentation step, where we have one ground element and one tree element, and that with a new language; well done!
In Julia, you just learned how to import, sub-sample, export, and visualize a point cloud composed of hundreds of thousands of points! Well done! But the path does not end here, and future posts will dive deeper into point cloud spatial analysis, file formats, data structures, visualization, animation, and meshing. We will especially look into how to manage big point cloud data as defined in the articles below.
towardsdatascience.com
towardsdatascience.com
My contributions aim to condense actionable information so you can start from scratch to build 3D automation systems for your projects. You can get started today by taking an online course at the Geodata Academy.
learngeodata.eu
If you are new to Medium, you can support my work by following the below link:
|
[
{
"code": null,
"e": 471,
"s": 172,
"text": "If you are always on the lookout for great ideas and new “tools” that make them easier to achieve, then you may have heard of Julia before. A very young language that is less than ten years old 👶, and that is a super cool way to get into fast scripting/coding for quickly achieving working ideas 🌼."
},
{
"code": null,
"e": 743,
"s": 471,
"text": "Supposing you are into scientific computing, machine learning, data mining, 3D data science, large-scale linear algebra, distributed and parallel computing, I think it is worth following up on this hands-on tutorial to get started with Julia and start doing fun 3D stuff!"
},
{
"code": null,
"e": 933,
"s": 743,
"text": "In this newcomer tutorial, I will cut straight through the matter and provide you with a laser-focused 6-step workflow to get up and running with 3D data within the next ten minutes! Ready?"
},
{
"code": null,
"e": 1205,
"s": 933,
"text": "Ha, but before, I want to highlight the ambitions of the creators of Julia. The creators of Julia, namely Jeff Bezanson, Stefan Karpinski, Viral B. Shah, and Alan Edelman. They blogged in 2012 about their aspirations and essentially why they initiated the Julia movement:"
},
{
"code": null,
"e": 1829,
"s": 1205,
"text": "We want a language that’s open source, with a liberal license. We want the speed of C with the dynamism of Ruby. We want a language that’s homoiconic, with true macros like Lisp, but with obvious, familiar mathematical notation like Matlab. We want something as usable for general programming as Python, as easy for statistics as R, as natural for string processing as Perl, as powerful for linear algebra as Matlab, as good at gluing programs together as the shell. Something that is dirt simple to learn, yet keeps the most serious hackers happy. We want it interactive and we want it compiled. It should be as fast as C."
},
{
"code": null,
"e": 2070,
"s": 1829,
"text": "But do these claims hold 🤔? Is this an “I want it all” language? Well, I first discovered Julia in early 2019, when I was making a research visit to the Visual Computing Institute (Computer Graphics) in RWTH Aachen University (Deutschland)."
},
{
"code": null,
"e": 2093,
"s": 2070,
"text": "www.vci.rwth-aachen.de"
},
{
"code": null,
"e": 2693,
"s": 2093,
"text": "Since then, I swear almost essentially through Julia! And that comes from a Pythonista/C “programmer” mindset. It is super clear, effortless to pick up, super-fast, and you can loop python scripts within, call your favorite libraries directly, and pure Julia will execute crazy fast! Indeed, Julia is compiled, not interpreted. For faster runtime performance, Julia is just-in-time (JIT) compiled using the LLVM compiler framework. At its best, Julia can approach or match the speed of C, and that is awesome 🚀! In three words, I would say that Julia is Fast, Dynamic with Reproducible environments."
},
{
"code": null,
"e": 2950,
"s": 2693,
"text": "⚠️ A warning, though, at the time of the writing, the documentation and tutorials are still very sparse, and the community is also pretty small compared to what you would be used to if using Python. But hey, I intend to change that a bit. Shall we dive in?"
},
{
"code": null,
"e": 3158,
"s": 2950,
"text": "Okay, now that you have your coffee ☕ or teacup 🍵 next to you, ready to find our way into the fog, let us dive in! First, we need to download Julia from the official website: https://julialang.org/downloads/"
},
{
"code": null,
"e": 3306,
"s": 3158,
"text": "Note: This tutorial is made with Julia version 1.6.2, 64bits using windows, but you can use any stable release, which should work (in principle 😉)."
},
{
"code": null,
"e": 3429,
"s": 3306,
"text": "Install the pretty stuff once the executable is downloaded until you have shiny “software” ready for your beautiful hands!"
},
{
"code": null,
"e": 3686,
"s": 3429,
"text": "Julia supports various editors like VSCode, Atom, Emacs, Sublime, Vim, Notepad++, and IDEs like IntelliJ. If you like Jupyter notebooks, you can also use them directly with Julia. For this tutorial, I will show you my favorite three choices to choose from."
},
{
"code": null,
"e": 3957,
"s": 3686,
"text": "It would be the first choice to demo your project in a powerpoint-style fashion or if what you intend to do is more linked to an exploratory data analysis. For this, nothing simpler, launch your freshly installed Julia executable, then a window like below should pop up."
},
{
"code": null,
"e": 4211,
"s": 3957,
"text": "From there, all you have to do is to type the command using Pkg and then press Enter followed by the command Pkg.add(\"IJulia\") and Enter. The process of installing the IJulia package necessary to use Julia within Jupyter Notebooks takes around 1 minute."
},
{
"code": null,
"e": 4327,
"s": 4211,
"text": "Then, you can launch Anaconda Navigator (with GUI) from which Jupyter Notebook on the environment of your choosing."
},
{
"code": null,
"e": 4407,
"s": 4327,
"text": "Note: If you do not have Anaconda installed, you can follow the tutorial below:"
},
{
"code": null,
"e": 4430,
"s": 4407,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 4559,
"s": 4430,
"text": "Once opened, you can create a new notebook with Julia acting as the programming language (see below for starting a new notebook)"
},
{
"code": null,
"e": 4851,
"s": 4559,
"text": "I tend to favor the Atom+Juno combination, which allows you to benefit from an interactive REPL mode, much like what you would be used to with Spyder. If you choose to follow these footsteps, you first need to install Atom in your system following the instructions given at https://atom.io/."
},
{
"code": null,
"e": 5308,
"s": 4851,
"text": "Then, you can launch Atom and head over to the package installation settings through Packages>Settings view>Open or the shortcut Ctrl+,. There search for juno and then click the install button for uber-juno and if not installed juno-client. Once Juno is installed, you can try opening the REPL with Juno > Open REPL or Ctrl+J Ctrl+O (Cmd+J Cmd+O on macOS), and then pressing Enter in the REPL to start a Julia session. And that is it! We are ready to code!"
},
{
"code": null,
"e": 5503,
"s": 5308,
"text": "Note: If the REPL does not seem to launch correctly and does not display the Julia logo, head over to the Juno Client Settings from the Package menu and verify the path to tour Julia executable."
},
{
"code": null,
"e": 5769,
"s": 5503,
"text": "You can also use a google Colab environment, but that needs a specif block of code to use Julia instead of Python. For this, you will find at this link a template that makes it possible to work directly within Colab. It also contains the main code of this tutorial."
},
{
"code": null,
"e": 5989,
"s": 5769,
"text": "Note: Every time you want to use Julia on the Google Cloud, you need to run the first block, refresh the page, and continue directly to the second block without re-running the first until every element is ready for you."
},
{
"code": null,
"e": 6409,
"s": 5989,
"text": "Great, so now we are ready to Julia code. First, let us discover where we are working, so our current working directory, using the command pwd(). Hmm, it looks like we are in the base directory, so let us change it to a project directory that you would create where you want to store most of your project (data, results, ...) with cd(“C://DEV/JULIA/TUTORIALS/3D_PROJECT_1”), followed by pwd() to check out the new path."
},
{
"code": null,
"e": 6556,
"s": 6409,
"text": "Okay, we are all set. Let us download a dataset, for starters, a small noisy point cloud. For this, very handy, you can use the following command:"
},
{
"code": null,
"e": 6678,
"s": 6556,
"text": "download(\"https://raw.githubusercontent.com/florentPoux/3D-small-datasets/main/tree_sample.csv\",\"point_cloud_sample.csv\")"
},
{
"code": null,
"e": 6852,
"s": 6678,
"text": "Note: The download() command first takes the link to the data you want to download, which I dropped on my GitHub account, and then specifies its name locally after download."
},
{
"code": null,
"e": 7062,
"s": 6852,
"text": "Great, we now have a local version of the data in our working directory that we specified with the cd() command. Now, how do we load it in the script? well, we will make use of a Package called DelimitedFiles."
},
{
"code": null,
"e": 7340,
"s": 7062,
"text": "Note: A Package is a handy set of functions, methods, classes, and more that allow you to build on existing code without writing everything from scratch. The DelimitedFiles package allows manipulating (e.g., read and write) delimited files like our current point cloud at hand."
},
{
"code": null,
"e": 7584,
"s": 7340,
"text": "For using a package, we first have to load the package manager utility by just typing using Pkg. To add a new package, it is pretty simple; we just write Pkg.add(“DelimitedFiles”), and wait until the download + requirement checks are finished."
},
{
"code": null,
"e": 7911,
"s": 7584,
"text": "What is great about this is that you do not have to worry about dependencies (other packages needed by the current) as all is handled for you! Cool, huh? And on top, we can create excellent packages easily to ensure reproducibility of the results, for example, and independent environments, but that is for another tutorial 😉."
},
{
"code": null,
"e": 8380,
"s": 7911,
"text": "Note: Managing packages is then pretty straightforward, and we have a bunch of functions to update the packages, to know their current status, if we have any conflicts between them (rare), or to load unregistered packages by other like-minded coders, even one of your future local package 😉. I usually manage them by using the REPL and entering the package manager with the command ] in the right environment. To exit the package manager, one needs just to do Ctrl+C ."
},
{
"code": null,
"e": 8734,
"s": 8380,
"text": "Ok, now that the package is installed (you only need to run this once per environment). You can use it in your current project by typing using DelimitedFiles, and also, if there are no conflicts of function names, you do not need to write from which package a function comes. to read a delimited file DelimitedFiles.readdlm() is equivalent to readdlm()."
},
{
"code": null,
"e": 8828,
"s": 8734,
"text": "From there, let us read the point cloud at hand and store the data in the variable pointlist:"
},
{
"code": null,
"e": 8876,
"s": 8828,
"text": "pointlist=readdlm(“point_cloud_sample.csv”,’;’)"
},
{
"code": null,
"e": 8916,
"s": 8876,
"text": "The first lines should look like below."
},
{
"code": null,
"e": 9153,
"s": 8916,
"text": "Okay, pretty cool up until now, hun? And now, let us see the first real surprise if you are used to other programming languages: indexing. You can try doing pointlist[0] to retrieve the first element. What are we getting? a BoundsError."
},
{
"code": null,
"e": 9666,
"s": 9153,
"text": "Haha, in Julia, indexes start at 1, so if you want to retrieve the first element (the X coordinate of the first point), you just input pointlist[1] that returns 41.61793137. A bit confusing at first, it is pretty handy and logical, at least from a scientific point of view 😅. So now, if you want to retrieve the first point, then you need to know that indexes work on the first axis (rows) first, followed by the second axis (column(s)), and so on. Thus, to retrieve the first point (first row and every column):"
},
{
"code": null,
"e": 9681,
"s": 9666,
"text": "pointlist[1,:]"
},
{
"code": null,
"e": 9830,
"s": 9681,
"text": "Very cool, and now, to get further, if we want to store the coordinates in the points variables and the normals in the normals variable, we just do:"
},
{
"code": null,
"e": 9883,
"s": 9830,
"text": "points = pointlist[:,1:3]normals = pointlist[:,4:6]"
},
{
"code": null,
"e": 10356,
"s": 9883,
"text": "Note: If you want to know the type of a variable, typeof() is what you are looking for. typeof(points)will display that we deal with Matrices, which are an alias of 2-dimensional arrays. Also Float64 is a computer number format, usually occupying 64 bits in computer memory; it represents a wide dynamic range of numeric values by using a floating radix point. Double precision may be chosen when the range or precision of single-precision (Float32) would be insufficient."
},
{
"code": null,
"e": 10610,
"s": 10356,
"text": "One last straightforward pre-processing step would be to know how to quickly sample the variable extracting, let say, 1 line every tenth. For this, we can do the following (a bit like Python, but we need to put the word end to treat the total variable):"
},
{
"code": null,
"e": 10645,
"s": 10610,
"text": "points_sampled=points[1:10:end,:] "
},
{
"code": null,
"e": 10751,
"s": 10645,
"text": "We first work on rows, taking one every tenth, and for each line, we keep all columns with : following ,."
},
{
"code": null,
"e": 11182,
"s": 10751,
"text": "Hint: There are many ways to sample a dataset, but it is always important to balance the gain performance/results. This way is pretty quick and straightforward to execute; thus, it usually acts to get first visual results to know what we are dealing with without using too much memory. If you want to dive deeper, I recommend you follow through with the following tutorial. The adaptation to Julia should not be too problematic 😉."
},
{
"code": null,
"e": 11205,
"s": 11182,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 11636,
"s": 11205,
"text": "We now are ready to address 3D data visualization, a critical step to grasp what we are dealing with! Here, one library is the go-to solution: Makie. Because we didn’t use it yet, we first need to import the package, along with two other “backends” depending on your paradigm (webGL visualization or OpenGL visualization), namely WGLMakie and GLMakie. Nothing more straightforward, we just run the following three lines only once:"
},
{
"code": null,
"e": 11690,
"s": 11636,
"text": "Pkg.add(“Makie”)Pkg.add(“WGLMakie”)Pkg.add(“GLMakie”)"
},
{
"code": null,
"e": 11844,
"s": 11690,
"text": "Note: Once executed, if anytime you want to explore the packages you have installed in your current environment, you can use the command Pkg.installed()."
},
{
"code": null,
"e": 12097,
"s": 11844,
"text": "Once the needed packages are installed, to make them usable in your working session, you can add the line using Makie, GLMakie (or using Makie, WGLMakie if you want interactivity on the web with Colab or Jupyter), much like import matplotlib in Python."
},
{
"code": null,
"e": 12382,
"s": 12097,
"text": "Nice, now, before visualizing, let us prepare a bit of color for our colorless points, depending on their z-value. We will create a color vector the size of the sampled point cloud that will range from 0 to 1, depending on how close to the maximum value it is, by dividing each point:"
},
{
"code": null,
"e": 12447,
"s": 12382,
"text": "zcoloring_scale=points_sampled[:,3]/maximum(points_sampled[:,3])"
},
{
"code": null,
"e": 12782,
"s": 12447,
"text": "Hint: Julia automatically understands that you want to divide each element from points_sampled[:,3] by the maximum value with maximum() . Handy, huh? But it is a particular case of broadcasting, which in Julia, you just write by inputting a . before your function or mathematic symbol. If you do ./ here, you will get the same result."
},
{
"code": null,
"e": 13128,
"s": 12782,
"text": "Okay, now, all we have to do is plot our results as a scattered point cloud in 3D. For this, we use the scatter function from Makie, and we pass as arguments the coordinates of the points (points_sampled), the color vector zcoloring_scale, and also some parameters like the size of each point with markersize, and if we want to display the axis."
},
{
"code": null,
"e": 13207,
"s": 13128,
"text": "scatter(points_sampled, color=zcoloring_scale, markersize=100, show_axis=true)"
},
{
"code": null,
"e": 13327,
"s": 13207,
"text": "You also can do a meshscatter plot that will generate a small sphere for each point (like the image above on the right)"
},
{
"code": null,
"e": 13420,
"s": 13327,
"text": "scene_1 = meshscatter(points_sampled, color=zcoloring_scale, markersize=0.2, show_axis=true)"
},
{
"code": null,
"e": 13596,
"s": 13420,
"text": "How very cool! If you want some interactivity on the web, you should make sure to use WGLMakie instead of GLMakie, which will just give you a fixed backend to generate a view."
},
{
"code": null,
"e": 13995,
"s": 13596,
"text": "Hint: If you want to print your figure to a file, an effortless way is to first install the FileIO package using Pkg.add(“FileIO”) and using FileIO that holds the necessary methods and function to deal with a lot of file formats incl. meshes, images, vectors ... Once available in your running session, a simple save(“scatter.png”, scene_1) will save the plot to an image in your working directory."
},
{
"code": null,
"e": 14186,
"s": 13995,
"text": "An effortless way to display a mesh is to use FileIO, like hinted above. In two simple lines, you can display your mesh. Take the one available on my GitHub like the point cloud before with:"
},
{
"code": null,
"e": 14295,
"s": 14186,
"text": "download(\"https://raw.githubusercontent.com/florentPoux/3D-small-datasets/main/hippo_1k.obj\",\"hippo_1k.obj\")"
},
{
"code": null,
"e": 14353,
"s": 14295,
"text": "and then, you can just store it in the obj variable with:"
},
{
"code": null,
"e": 14380,
"s": 14353,
"text": "obj = load(“hippo_1k.obj”)"
},
{
"code": null,
"e": 14469,
"s": 14380,
"text": "that you pass to the Makie.mesh() function shortened to mesh() to display your 3D model."
},
{
"code": null,
"e": 14515,
"s": 14469,
"text": "mesh(obj, color=”honeydew2”, show_axis=false)"
},
{
"code": null,
"e": 14582,
"s": 14515,
"text": "If this is not optimized code clarity, I do not know what it is 😆!"
},
{
"code": null,
"e": 14726,
"s": 14582,
"text": "Hint: If you want to access the single-shot color names, check out this link that gives all the available possibilities, and there are a lot 🙃."
},
{
"code": null,
"e": 15133,
"s": 14726,
"text": "Now we can explore a bit the data and play around with some functions. The first thing would be to know how to access a specific portion of the 3D point cloud dataset. In our case, we would like to find and separate (more or less) the ground from the rest. First, we would find through visualization the higher z of the ground and then use that as a threshold. Let us plot the 2D projection of the dataset:"
},
{
"code": null,
"e": 15219,
"s": 15133,
"text": "scatter(points_sampled[:,2:3], color=zcoloring_scale, markersize=100, show_axis=true)"
},
{
"code": null,
"e": 15340,
"s": 15219,
"text": "We can identify that we get a threshold at more or less 3 meters (red line). Let us use it directly for our experiments."
},
{
"code": null,
"e": 15646,
"s": 15340,
"text": "Hint: If you want to display other elements on the same figure, a simple way to do is to add ! to the following plots, like if you want to display the y=3 line in red like above, you would do lines!(range(38, 60, length=30),(x*0).+3, color=”red”) and admire the results with the commandcurrent_figure() 😀."
},
{
"code": null,
"e": 16024,
"s": 15646,
"text": "Now we want to find all points below and above the visually defined threshold and store them in a separate variable. We will use the findall function that returns the indexes of the points satisfying the condition in brackets. Let us work solely on points[:,3] as we just need to study this and retrieve indexes that we can later use to filter our full point cloud. How cool 😆?"
},
{
"code": null,
"e": 16112,
"s": 16024,
"text": "indexes_ground=findall(x->x < 3, points[:,3])indexes_tree=findall(x->x>=3, points[:,3])"
},
{
"code": null,
"e": 16423,
"s": 16112,
"text": "Very nice! Now, if we would like to get the points corresponding to these indexes list, we just have to pass indexes_ground or indexes_tree as a row selector in the points variable, for example, for getting all the points that belong to the ground and all the rest. And if we want to plot this, then we can do:"
},
{
"code": null,
"e": 16620,
"s": 16423,
"text": "meshscatter(points[indexes_ground,:], color=”navajowhite4”, markersize=0.3, show_axis=false)meshscatter!(points[indexes_tree,:], color=”honeydew3”, markersize=0.3, show_axis=false)current_figure()"
},
{
"code": null,
"e": 16774,
"s": 16620,
"text": "Awesome! We just did a manual instance segmentation step, where we have one ground element and one tree element, and that with a new language; well done!"
},
{
"code": null,
"e": 17189,
"s": 16774,
"text": "In Julia, you just learned how to import, sub-sample, export, and visualize a point cloud composed of hundreds of thousands of points! Well done! But the path does not end here, and future posts will dive deeper into point cloud spatial analysis, file formats, data structures, visualization, animation, and meshing. We will especially look into how to manage big point cloud data as defined in the articles below."
},
{
"code": null,
"e": 17212,
"s": 17189,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 17235,
"s": 17212,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 17448,
"s": 17235,
"text": "My contributions aim to condense actionable information so you can start from scratch to build 3D automation systems for your projects. You can get started today by taking an online course at the Geodata Academy."
},
{
"code": null,
"e": 17464,
"s": 17448,
"text": "learngeodata.eu"
}
] |
Find the node with minimum value in a Binary Search Tree in C++
|
Suppose we have one binary search tree. We have to find the minimum element in binary search tree. So if the BST is like below −
The minimum element will be 1.
As we know that the left subtree always holds the smaller elements. So if we traverse through the left subtree again and again until left is null, we can find the smallest element.
Live Demo
#include<iostream>
using namespace std;
class node{
public:
node *left;
int val;
node *right;
};
node *bst = NULL;
node *getNode(){
node *newNode;
newNode = new node;
return newNode;
}
void insert(node **root, int key){
node *newNode;
newNode = getNode();
newNode->val = key; newNode->left = NULL; newNode->right = NULL;
if(*root == NULL){
*root = newNode;
return;
} else {
if(key < (*root)->val)
insert(&((*root)->left), key);
else
insert(&((*root)->right), key);
}
}
int minElement(){
node* current = bst;
while (current->left != NULL) {
current = current->left;
}
return(current->val);
}
main(){
int item[] = {3, 2, 1, 6, 5, 8};
int n = sizeof(item)/sizeof(item[0]);
int i;
for(i = 0; i<8; i++){
insert(&bst, item[i]);
}
cout << "Minimum element is: " << minElement();
}
Minimum element is: 1
|
[
{
"code": null,
"e": 1191,
"s": 1062,
"text": "Suppose we have one binary search tree. We have to find the minimum element in binary search tree. So if the BST is like below −"
},
{
"code": null,
"e": 1222,
"s": 1191,
"text": "The minimum element will be 1."
},
{
"code": null,
"e": 1403,
"s": 1222,
"text": "As we know that the left subtree always holds the smaller elements. So if we traverse through the left subtree again and again until left is null, we can find the smallest element."
},
{
"code": null,
"e": 1414,
"s": 1403,
"text": " Live Demo"
},
{
"code": null,
"e": 2311,
"s": 1414,
"text": "#include<iostream>\nusing namespace std;\nclass node{\n public:\n node *left;\n int val;\n node *right;\n};\nnode *bst = NULL;\nnode *getNode(){\n node *newNode;\n newNode = new node;\n return newNode;\n}\nvoid insert(node **root, int key){\n node *newNode;\n newNode = getNode();\n newNode->val = key; newNode->left = NULL; newNode->right = NULL;\n if(*root == NULL){\n *root = newNode;\n return;\n } else {\n if(key < (*root)->val)\n insert(&((*root)->left), key);\n else\n insert(&((*root)->right), key);\n }\n}\nint minElement(){\n node* current = bst;\n while (current->left != NULL) {\n current = current->left;\n }\n return(current->val);\n}\nmain(){\n int item[] = {3, 2, 1, 6, 5, 8};\n int n = sizeof(item)/sizeof(item[0]);\n int i;\n for(i = 0; i<8; i++){\n insert(&bst, item[i]);\n }\n cout << \"Minimum element is: \" << minElement();\n}"
},
{
"code": null,
"e": 2333,
"s": 2311,
"text": "Minimum element is: 1"
}
] |
Creating RSA Keys
|
In this chapter, we will focus on step wise implementation of RSA algorithm using Python.
The following steps are involved in generating RSA keys −
Create two large prime numbers namely p and q. The product of these numbers will be called n, where n= p*q
Create two large prime numbers namely p and q. The product of these numbers will be called n, where n= p*q
Generate a random number which is relatively prime with (p-1) and (q-1). Let the number be called as e.
Generate a random number which is relatively prime with (p-1) and (q-1). Let the number be called as e.
Calculate the modular inverse of e. The calculated inverse will be called as d.
Calculate the modular inverse of e. The calculated inverse will be called as d.
We need two primary algorithms for generating RSA keys using Python − Cryptomath module and Rabin Miller module.
The source code of cryptomath module which follows all the basic implementation of RSA algorithm is as follows −
def gcd(a, b):
while a != 0:
a, b = b % a, a
return b
def findModInverse(a, m):
if gcd(a, m) != 1:
return None
u1, u2, u3 = 1, 0, a
v1, v2, v3 = 0, 1, m
while v3 != 0:
q = u3 // v3
v1, v2, v3, u1, u2, u3 = (u1 - q * v1), (u2 - q * v2), (u3 - q * v3), v1, v2, v3
return u1 % m
The source code of RabinMiller module which follows all the basic implementation of RSA algorithm is as follows −
import random
def rabinMiller(num):
s = num - 1
t = 0
while s % 2 == 0:
s = s // 2
t += 1
for trials in range(5):
a = random.randrange(2, num - 1)
v = pow(a, s, num)
if v != 1:
i = 0
while v != (num - 1):
if i == t - 1:
return False
else:
i = i + 1
v = (v ** 2) % num
return True
def isPrime(num):
if (num 7< 2):
return False
lowPrimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61,
67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,
157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241,
251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313,317, 331, 337, 347, 349,
353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449,
457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569,
571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661,
673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787,
797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907,
911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]
if num in lowPrimes:
return True
for prime in lowPrimes:
if (num % prime == 0):
return False
return rabinMiller(num)
def generateLargePrime(keysize = 1024):
while True:
num = random.randrange(2**(keysize-1), 2**(keysize))
if isPrime(num):
return num
The complete code for generating RSA keys is as follows −
import random, sys, os, rabinMiller, cryptomath
def main():
makeKeyFiles('RSA_demo', 1024)
def generateKey(keySize):
# Step 1: Create two prime numbers, p and q. Calculate n = p * q.
print('Generating p prime...')
p = rabinMiller.generateLargePrime(keySize)
print('Generating q prime...')
q = rabinMiller.generateLargePrime(keySize)
n = p * q
# Step 2: Create a number e that is relatively prime to (p-1)*(q-1).
print('Generating e that is relatively prime to (p-1)*(q-1)...')
while True:
e = random.randrange(2 ** (keySize - 1), 2 ** (keySize))
if cryptomath.gcd(e, (p - 1) * (q - 1)) == 1:
break
# Step 3: Calculate d, the mod inverse of e.
print('Calculating d that is mod inverse of e...')
d = cryptomath.findModInverse(e, (p - 1) * (q - 1))
publicKey = (n, e)
privateKey = (n, d)
print('Public key:', publicKey)
print('Private key:', privateKey)
return (publicKey, privateKey)
def makeKeyFiles(name, keySize):
# Creates two files 'x_pubkey.txt' and 'x_privkey.txt'
(where x is the value in name) with the the n,e and d,e integers written in them,
# delimited by a comma.
if os.path.exists('%s_pubkey.txt' % (name)) or os.path.exists('%s_privkey.txt' % (name)):
sys.exit('WARNING: The file %s_pubkey.txt or %s_privkey.txt already exists! Use a different name or delete these files and re-run this program.' % (name, name))
publicKey, privateKey = generateKey(keySize)
print()
print('The public key is a %s and a %s digit number.' % (len(str(publicKey[0])), len(str(publicKey[1]))))
print('Writing public key to file %s_pubkey.txt...' % (name))
fo = open('%s_pubkey.txt' % (name), 'w')
fo.write('%s,%s,%s' % (keySize, publicKey[0], publicKey[1]))
fo.close()
print()
print('The private key is a %s and a %s digit number.' % (len(str(publicKey[0])), len(str(publicKey[1]))))
print('Writing private key to file %s_privkey.txt...' % (name))
fo = open('%s_privkey.txt' % (name), 'w')
fo.write('%s,%s,%s' % (keySize, privateKey[0], privateKey[1]))
fo.close()
# If makeRsaKeys.py is run (instead of imported as a module) call
# the main() function.
if __name__ == '__main__':
main()
The public key and private keys are generated and saved in the respective files as shown in the following output.
10 Lectures
2 hours
Total Seminars
10 Lectures
2 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2382,
"s": 2292,
"text": "In this chapter, we will focus on step wise implementation of RSA algorithm using Python."
},
{
"code": null,
"e": 2440,
"s": 2382,
"text": "The following steps are involved in generating RSA keys −"
},
{
"code": null,
"e": 2547,
"s": 2440,
"text": "Create two large prime numbers namely p and q. The product of these numbers will be called n, where n= p*q"
},
{
"code": null,
"e": 2654,
"s": 2547,
"text": "Create two large prime numbers namely p and q. The product of these numbers will be called n, where n= p*q"
},
{
"code": null,
"e": 2758,
"s": 2654,
"text": "Generate a random number which is relatively prime with (p-1) and (q-1). Let the number be called as e."
},
{
"code": null,
"e": 2862,
"s": 2758,
"text": "Generate a random number which is relatively prime with (p-1) and (q-1). Let the number be called as e."
},
{
"code": null,
"e": 2942,
"s": 2862,
"text": "Calculate the modular inverse of e. The calculated inverse will be called as d."
},
{
"code": null,
"e": 3022,
"s": 2942,
"text": "Calculate the modular inverse of e. The calculated inverse will be called as d."
},
{
"code": null,
"e": 3136,
"s": 3022,
"text": "We need two primary algorithms for generating RSA keys using Python − Cryptomath module and Rabin Miller module."
},
{
"code": null,
"e": 3249,
"s": 3136,
"text": "The source code of cryptomath module which follows all the basic implementation of RSA algorithm is as follows −"
},
{
"code": null,
"e": 3578,
"s": 3249,
"text": "def gcd(a, b):\n while a != 0:\n a, b = b % a, a\n return b\n\ndef findModInverse(a, m):\n if gcd(a, m) != 1:\n return None\n u1, u2, u3 = 1, 0, a\n v1, v2, v3 = 0, 1, m\n \n while v3 != 0:\n q = u3 // v3\n v1, v2, v3, u1, u2, u3 = (u1 - q * v1), (u2 - q * v2), (u3 - q * v3), v1, v2, v3\n return u1 % m"
},
{
"code": null,
"e": 3692,
"s": 3578,
"text": "The source code of RabinMiller module which follows all the basic implementation of RSA algorithm is as follows −"
},
{
"code": null,
"e": 5334,
"s": 3692,
"text": "import random\ndef rabinMiller(num):\n s = num - 1\n t = 0\n \n while s % 2 == 0:\n s = s // 2\n t += 1\n for trials in range(5):\n a = random.randrange(2, num - 1)\n v = pow(a, s, num)\n if v != 1:\n i = 0\n while v != (num - 1):\n if i == t - 1:\n return False\n else:\n i = i + 1\n v = (v ** 2) % num\n return True\ndef isPrime(num):\n if (num 7< 2):\n return False\n lowPrimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, \n 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, \n 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, \n 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313,317, 331, 337, 347, 349, \n 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, \n 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, \n 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, \n 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, \n 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, \n 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]\n\t\n if num in lowPrimes:\n return True\n for prime in lowPrimes:\n if (num % prime == 0):\n return False\n return rabinMiller(num)\ndef generateLargePrime(keysize = 1024):\n while True:\n num = random.randrange(2**(keysize-1), 2**(keysize))\n if isPrime(num):\n return num"
},
{
"code": null,
"e": 5392,
"s": 5334,
"text": "The complete code for generating RSA keys is as follows −"
},
{
"code": null,
"e": 7626,
"s": 5392,
"text": "import random, sys, os, rabinMiller, cryptomath\n\ndef main():\n makeKeyFiles('RSA_demo', 1024)\n\ndef generateKey(keySize):\n # Step 1: Create two prime numbers, p and q. Calculate n = p * q.\n print('Generating p prime...')\n p = rabinMiller.generateLargePrime(keySize)\n print('Generating q prime...')\n q = rabinMiller.generateLargePrime(keySize)\n n = p * q\n\t\n # Step 2: Create a number e that is relatively prime to (p-1)*(q-1).\n print('Generating e that is relatively prime to (p-1)*(q-1)...')\n while True:\n e = random.randrange(2 ** (keySize - 1), 2 ** (keySize))\n if cryptomath.gcd(e, (p - 1) * (q - 1)) == 1:\n break\n \n # Step 3: Calculate d, the mod inverse of e.\n print('Calculating d that is mod inverse of e...')\n d = cryptomath.findModInverse(e, (p - 1) * (q - 1))\n publicKey = (n, e)\n privateKey = (n, d)\n print('Public key:', publicKey)\n print('Private key:', privateKey)\n return (publicKey, privateKey)\n\ndef makeKeyFiles(name, keySize):\n # Creates two files 'x_pubkey.txt' and 'x_privkey.txt' \n (where x is the value in name) with the the n,e and d,e integers written in them,\n # delimited by a comma.\n if os.path.exists('%s_pubkey.txt' % (name)) or os.path.exists('%s_privkey.txt' % (name)):\n sys.exit('WARNING: The file %s_pubkey.txt or %s_privkey.txt already exists! Use a different name or delete these files and re-run this program.' % (name, name))\n publicKey, privateKey = generateKey(keySize)\n print()\n print('The public key is a %s and a %s digit number.' % (len(str(publicKey[0])), len(str(publicKey[1])))) \n print('Writing public key to file %s_pubkey.txt...' % (name))\n \n fo = open('%s_pubkey.txt' % (name), 'w')\n\tfo.write('%s,%s,%s' % (keySize, publicKey[0], publicKey[1]))\n fo.close()\n print()\n print('The private key is a %s and a %s digit number.' % (len(str(publicKey[0])), len(str(publicKey[1]))))\n print('Writing private key to file %s_privkey.txt...' % (name))\n \n fo = open('%s_privkey.txt' % (name), 'w')\n fo.write('%s,%s,%s' % (keySize, privateKey[0], privateKey[1]))\n fo.close()\n# If makeRsaKeys.py is run (instead of imported as a module) call\n# the main() function.\nif __name__ == '__main__':\n main()"
},
{
"code": null,
"e": 7740,
"s": 7626,
"text": "The public key and private keys are generated and saved in the respective files as shown in the following output."
},
{
"code": null,
"e": 7773,
"s": 7740,
"text": "\n 10 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7789,
"s": 7773,
"text": " Total Seminars"
},
{
"code": null,
"e": 7822,
"s": 7789,
"text": "\n 10 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7845,
"s": 7822,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 7852,
"s": 7845,
"text": " Print"
},
{
"code": null,
"e": 7863,
"s": 7852,
"text": " Add Notes"
}
] |
MongoEngine - Advanced Queries
|
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’))
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2673,
"s": 2310,
"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": 3002,
"s": 2673,
"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": 3041,
"s": 3002,
"text": "name: Himanshu\ncity: Mumbai\nPIN: None\n"
},
{
"code": null,
"e": 3149,
"s": 3041,
"text": "Note − The value of city attribute is used as default. As default is not specified for PIN, it prints None."
},
{
"code": null,
"e": 3208,
"s": 3149,
"text": "You may call reload() function if you need missing fields."
},
{
"code": null,
"e": 3550,
"s": 3208,
"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": 3781,
"s": 3550,
"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": 3840,
"s": 3781,
"text": "person.objects(Q(name__startswith=’H’) &Q(city=’Mumbai’))\n"
},
{
"code": null,
"e": 3847,
"s": 3840,
"text": " Print"
},
{
"code": null,
"e": 3858,
"s": 3847,
"text": " Add Notes"
}
] |
How to get the exponent power of a number in JavaScript?
|
To get the exponent power of a number, use the Math.pow (base, exponent ) method. This method returns the base to the exponent power, that is, base exponent.
The following are the parameters used in Math.pow() method −
base − The base number.
exponents − The exponent to which to raise base.
You can try to run the following code to get the exponent power −
<html>
<head>
<title>JavaScript Math pow() Method</title>
</head>
<body>
<script>
var value = Math.pow(7, 2);
document.write("First Test Value : " + value );
var value = Math.pow(8, 8);
document.write("<br />Second Test Value : " + value );
var value = Math.pow(-1, 2);
document.write("<br />Third Test Value : " + value );
var value = Math.pow(0, 10);
document.write("<br />Fourth Test Value : " + value );
</script>
</body>
</html>
|
[
{
"code": null,
"e": 1221,
"s": 1062,
"text": "To get the exponent power of a number, use the Math.pow (base, exponent ) method. This method returns the base to the exponent power, that is, base exponent. "
},
{
"code": null,
"e": 1282,
"s": 1221,
"text": "The following are the parameters used in Math.pow() method −"
},
{
"code": null,
"e": 1307,
"s": 1282,
"text": "base − The base number. "
},
{
"code": null,
"e": 1356,
"s": 1307,
"text": "exponents − The exponent to which to raise base."
},
{
"code": null,
"e": 1422,
"s": 1356,
"text": "You can try to run the following code to get the exponent power −"
},
{
"code": null,
"e": 1961,
"s": 1422,
"text": "<html>\n <head>\n <title>JavaScript Math pow() Method</title>\n </head>\n <body>\n <script>\n var value = Math.pow(7, 2);\n document.write(\"First Test Value : \" + value );\n\n var value = Math.pow(8, 8);\n document.write(\"<br />Second Test Value : \" + value );\n\n var value = Math.pow(-1, 2);\n document.write(\"<br />Third Test Value : \" + value );\n\n var value = Math.pow(0, 10);\n document.write(\"<br />Fourth Test Value : \" + value );\n </script>\n </body>\n</html>"
}
] |
Format date in MySQL SELECT * query uisng FORMATDATE() method?
|
Use the DATE_FORMAT(), not FORMATDATE() in MySQL to format date. The correct syntax is as follows −
SE LECT *, DATE_FORMAT(yourDateCoumnName,’yourFormat’) as anyAliasName FROM yourTableName
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table DateFormatDemo
-> (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> UserName varchar(10),
-> UserLoginDate date
-> );
Query OK, 0 rows affected (0.94 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into DateFormatDemo(UserName,UserLoginDate) values('Mike',curdate());
Query OK, 1 row affected (0.21 sec)
mysql> insert into DateFormatDemo(UserName,UserLoginDate) values('Sam','2018-05-09');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DateFormatDemo(UserName,UserLoginDate) values('Carol','2016-01-15');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DateFormatDemo(UserName,UserLoginDate) values('Bob','2015-12-31');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DateFormatDemo(UserName,UserLoginDate) values('David','2012-08-19');
Query OK, 1 row affected (0.09 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from DateFormatDemo;
The following is the output −
+----+----------+---------------+
| Id | UserName | UserLoginDate |
+----+----------+---------------+
| 1 | Mike | 2019-02-06 |
| 2 | Sam | 2018-05-09 |
| 3 | Carol | 2016-01-15 |
| 4 | Bob | 2015-12-31 |
| 5 | David | 2012-08-19 |
+----+----------+---------------+
5 rows in set (0.00 sec)
Let us format date using DATE_FORMAT() with SELECT *. The query is as follows −
mysql> select *,DATE_FORMAT(UserLoginDate,'%d-%m-%Y') as NewFormatOfDate from DateFormatDemo;
The following is the output −
+----+----------+---------------+-----------------+
| Id | UserName | UserLoginDate | NewFormatOfDate |
+----+----------+---------------+-----------------+
| 1 | Mike | 2019-02-06 | 06-02-2019 |
| 2 | Sam | 2018-05-09 | 09-05-2018 |
| 3 | Carol | 2016-01-15 | 15-01-2016 |
| 4 | Bob | 2015-12-31 | 31-12-2015 |
| 5 | David | 2012-08-19 | 19-08-2012 |
+----+----------+---------------+-----------------+
5 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1162,
"s": 1062,
"text": "Use the DATE_FORMAT(), not FORMATDATE() in MySQL to format date. The correct syntax is as follows −"
},
{
"code": null,
"e": 1252,
"s": 1162,
"text": "SE LECT *, DATE_FORMAT(yourDateCoumnName,’yourFormat’) as anyAliasName FROM yourTableName"
},
{
"code": null,
"e": 1351,
"s": 1252,
"text": "To understand the above syntax, let us create a table. The query to create a table is as follows −"
},
{
"code": null,
"e": 1543,
"s": 1351,
"text": "mysql> create table DateFormatDemo\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> UserName varchar(10),\n -> UserLoginDate date\n -> );\nQuery OK, 0 rows affected (0.94 sec)"
},
{
"code": null,
"e": 1624,
"s": 1543,
"text": "Insert some records in the table using insert command. The query is as follows −"
},
{
"code": null,
"e": 2236,
"s": 1624,
"text": "mysql> insert into DateFormatDemo(UserName,UserLoginDate) values('Mike',curdate());\nQuery OK, 1 row affected (0.21 sec)\nmysql> insert into DateFormatDemo(UserName,UserLoginDate) values('Sam','2018-05-09');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DateFormatDemo(UserName,UserLoginDate) values('Carol','2016-01-15');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DateFormatDemo(UserName,UserLoginDate) values('Bob','2015-12-31');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DateFormatDemo(UserName,UserLoginDate) values('David','2012-08-19');\nQuery OK, 1 row affected (0.09 sec)"
},
{
"code": null,
"e": 2321,
"s": 2236,
"text": "Display all records from the table using select statement. The query is as follows −"
},
{
"code": null,
"e": 2357,
"s": 2321,
"text": "mysql> select *from DateFormatDemo;"
},
{
"code": null,
"e": 2387,
"s": 2357,
"text": "The following is the output −"
},
{
"code": null,
"e": 2718,
"s": 2387,
"text": "+----+----------+---------------+\n| Id | UserName | UserLoginDate |\n+----+----------+---------------+\n| 1 | Mike | 2019-02-06 |\n| 2 | Sam | 2018-05-09 |\n| 3 | Carol | 2016-01-15 |\n| 4 | Bob | 2015-12-31 |\n| 5 | David | 2012-08-19 |\n+----+----------+---------------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2798,
"s": 2718,
"text": "Let us format date using DATE_FORMAT() with SELECT *. The query is as follows −"
},
{
"code": null,
"e": 2892,
"s": 2798,
"text": "mysql> select *,DATE_FORMAT(UserLoginDate,'%d-%m-%Y') as NewFormatOfDate from DateFormatDemo;"
},
{
"code": null,
"e": 2922,
"s": 2892,
"text": "The following is the output −"
},
{
"code": null,
"e": 3415,
"s": 2922,
"text": "+----+----------+---------------+-----------------+\n| Id | UserName | UserLoginDate | NewFormatOfDate |\n+----+----------+---------------+-----------------+\n| 1 | Mike | 2019-02-06 | 06-02-2019 |\n| 2 | Sam | 2018-05-09 | 09-05-2018 |\n| 3 | Carol | 2016-01-15 | 15-01-2016 |\n| 4 | Bob | 2015-12-31 | 31-12-2015 |\n| 5 | David | 2012-08-19 | 19-08-2012 |\n+----+----------+---------------+-----------------+\n5 rows in set (0.00 sec)"
}
] |
Bokeh - Exporting Plots
|
In addition to subcommands described above, Bokeh plots can be exported to PNG and SVG file format using export() function. For that purpose, local Python installation should have following dependency libraries.
PhantomJS is a JavaScript API that enables automated navigation, screenshots, user behavior and assertions. It is used to run browser-based unit tests. PhantomJS is based on WebKit providing a similar browsing environment for different browsers and provides fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG. In other words, PhantomJS is a web browser without a graphical user interface.
Pillow, a Python Imaging Library (earlier known as PIL) is a free library for the Python programming language that provides support for opening, manipulating, and saving many different image file formats. (including PPM, PNG, JPEG, GIF, TIFF, and BMP.) Some of its features are per-pixel manipulations, masking and transparency handling, image filtering, image enhancing, etc.
The export_png() function generates RGBA-format PNG image from layout. This function uses Webkit headless browser to render the layout in memory and then capture a screenshot. The generated image will be of the same dimensions as the source layout. Make sure that the Plot.background_fill_color and Plot.border_fill_color are properties to None.
from bokeh.io import export_png
export_png(plot, filename = "file.png")
It is possible that HTML5 Canvas plot output with a SVG element that can be edited using programs such as Adobe Illustrator. The SVG objects can also be converted to PDFs. Here, canvas2svg, a JavaScript library is used to mock the normal Canvas element and its methods with an SVG element. Like PNGs, in order to create a SVG with a transparent background,the Plot.background_fill_color and Plot.border_fill_color properties should be to None.
The SVG backend is first activated by setting the Plot.output_backend attribute to "svg".
plot.output_backend = "svg"
For headless export, Bokeh has a utility function, export_svgs(). This function will download all of SVG-enabled plots within a layout as distinct SVG files.
from bokeh.io import export_svgs
plot.output_backend = "svg"
export_svgs(plot, filename = "plot.svg")
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2482,
"s": 2270,
"text": "In addition to subcommands described above, Bokeh plots can be exported to PNG and SVG file format using export() function. For that purpose, local Python installation should have following dependency libraries."
},
{
"code": null,
"e": 2921,
"s": 2482,
"text": "PhantomJS is a JavaScript API that enables automated navigation, screenshots, user behavior and assertions. It is used to run browser-based unit tests. PhantomJS is based on WebKit providing a similar browsing environment for different browsers and provides fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG. In other words, PhantomJS is a web browser without a graphical user interface."
},
{
"code": null,
"e": 3298,
"s": 2921,
"text": "Pillow, a Python Imaging Library (earlier known as PIL) is a free library for the Python programming language that provides support for opening, manipulating, and saving many different image file formats. (including PPM, PNG, JPEG, GIF, TIFF, and BMP.) Some of its features are per-pixel manipulations, masking and transparency handling, image filtering, image enhancing, etc."
},
{
"code": null,
"e": 3644,
"s": 3298,
"text": "The export_png() function generates RGBA-format PNG image from layout. This function uses Webkit headless browser to render the layout in memory and then capture a screenshot. The generated image will be of the same dimensions as the source layout. Make sure that the Plot.background_fill_color and Plot.border_fill_color are properties to None."
},
{
"code": null,
"e": 3717,
"s": 3644,
"text": "from bokeh.io import export_png\nexport_png(plot, filename = \"file.png\")\n"
},
{
"code": null,
"e": 4161,
"s": 3717,
"text": "It is possible that HTML5 Canvas plot output with a SVG element that can be edited using programs such as Adobe Illustrator. The SVG objects can also be converted to PDFs. Here, canvas2svg, a JavaScript library is used to mock the normal Canvas element and its methods with an SVG element. Like PNGs, in order to create a SVG with a transparent background,the Plot.background_fill_color and Plot.border_fill_color properties should be to None."
},
{
"code": null,
"e": 4251,
"s": 4161,
"text": "The SVG backend is first activated by setting the Plot.output_backend attribute to \"svg\"."
},
{
"code": null,
"e": 4280,
"s": 4251,
"text": "plot.output_backend = \"svg\"\n"
},
{
"code": null,
"e": 4438,
"s": 4280,
"text": "For headless export, Bokeh has a utility function, export_svgs(). This function will download all of SVG-enabled plots within a layout as distinct SVG files."
},
{
"code": null,
"e": 4541,
"s": 4438,
"text": "from bokeh.io import export_svgs\nplot.output_backend = \"svg\"\nexport_svgs(plot, filename = \"plot.svg\")\n"
},
{
"code": null,
"e": 4548,
"s": 4541,
"text": " Print"
},
{
"code": null,
"e": 4559,
"s": 4548,
"text": " Add Notes"
}
] |
array at() function in C++ STL - GeeksforGeeks
|
29 Aug, 2018
The array::at() is a built-in function in C++ STL which returns a reference to the element present at location i in given array.
Syntax:
array_name.at(i)
Parameters: The function accepts a single mandatory parameter i which specifies the location.
Return value: The function returns an element present at index i in given array if i is valid index otherwise it throws out_of_range exception.
Time Complexity: O(1)
Below programs demonstrate the array::at() function:
Program 1:
// CPP program to illustrate// the array::at() function#include <bits/stdc++.h>using namespace std; int main(){ // array initialisation array<int, 5> arr = { 1, 5, 2, 4, 7 }; // prints the element at ith index // index starts from zero cout << "The element at index 2 is " << arr.at(2) << endl; return 0;}
The element at index 2 is 2
// CPP program to illustrate// the array::at() function#include <bits/stdc++.h>using namespace std; int main(){ // array initialisation array<int, 5> arr = { 1, 5, 2, 4, 7 }; // it is an exception cout << "The element at index 2 is " << arr.at(7) << endl; return 0;}
Abort signal from abort(3) (SIGABRT)
cpp-array
CPP-Functions
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Iterators in C++ STL
Operator Overloading in C++
Friend class and function in C++
Polymorphism in C++
Sorting a vector in C++
Inline Functions in C++
Convert string to char array in C++
List in C++ Standard Template Library (STL)
std::string class in C++
Exception Handling in C++
|
[
{
"code": null,
"e": 24043,
"s": 24015,
"text": "\n29 Aug, 2018"
},
{
"code": null,
"e": 24172,
"s": 24043,
"text": "The array::at() is a built-in function in C++ STL which returns a reference to the element present at location i in given array."
},
{
"code": null,
"e": 24180,
"s": 24172,
"text": "Syntax:"
},
{
"code": null,
"e": 24197,
"s": 24180,
"text": "array_name.at(i)"
},
{
"code": null,
"e": 24291,
"s": 24197,
"text": "Parameters: The function accepts a single mandatory parameter i which specifies the location."
},
{
"code": null,
"e": 24435,
"s": 24291,
"text": "Return value: The function returns an element present at index i in given array if i is valid index otherwise it throws out_of_range exception."
},
{
"code": null,
"e": 24457,
"s": 24435,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 24510,
"s": 24457,
"text": "Below programs demonstrate the array::at() function:"
},
{
"code": null,
"e": 24521,
"s": 24510,
"text": "Program 1:"
},
{
"code": "// CPP program to illustrate// the array::at() function#include <bits/stdc++.h>using namespace std; int main(){ // array initialisation array<int, 5> arr = { 1, 5, 2, 4, 7 }; // prints the element at ith index // index starts from zero cout << \"The element at index 2 is \" << arr.at(2) << endl; return 0;}",
"e": 24850,
"s": 24521,
"text": null
},
{
"code": null,
"e": 24879,
"s": 24850,
"text": "The element at index 2 is 2\n"
},
{
"code": "// CPP program to illustrate// the array::at() function#include <bits/stdc++.h>using namespace std; int main(){ // array initialisation array<int, 5> arr = { 1, 5, 2, 4, 7 }; // it is an exception cout << \"The element at index 2 is \" << arr.at(7) << endl; return 0;}",
"e": 25166,
"s": 24879,
"text": null
},
{
"code": null,
"e": 25204,
"s": 25166,
"text": "Abort signal from abort(3) (SIGABRT)\n"
},
{
"code": null,
"e": 25214,
"s": 25204,
"text": "cpp-array"
},
{
"code": null,
"e": 25228,
"s": 25214,
"text": "CPP-Functions"
},
{
"code": null,
"e": 25232,
"s": 25228,
"text": "STL"
},
{
"code": null,
"e": 25236,
"s": 25232,
"text": "C++"
},
{
"code": null,
"e": 25240,
"s": 25236,
"text": "STL"
},
{
"code": null,
"e": 25244,
"s": 25240,
"text": "CPP"
},
{
"code": null,
"e": 25342,
"s": 25244,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25351,
"s": 25342,
"text": "Comments"
},
{
"code": null,
"e": 25364,
"s": 25351,
"text": "Old Comments"
},
{
"code": null,
"e": 25385,
"s": 25364,
"text": "Iterators in C++ STL"
},
{
"code": null,
"e": 25413,
"s": 25385,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 25446,
"s": 25413,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 25466,
"s": 25446,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 25490,
"s": 25466,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 25514,
"s": 25490,
"text": "Inline Functions in C++"
},
{
"code": null,
"e": 25550,
"s": 25514,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 25594,
"s": 25550,
"text": "List in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 25619,
"s": 25594,
"text": "std::string class in C++"
}
] |
Kadane's Algorithm | Practice | GeeksforGeeks
|
Given an array Arr[] of N integers. Find the contiguous sub-array(containing at least one number) which has the maximum sum and return its sum.
Example 1:
Input:
N = 5
Arr[] = {1,2,3,-2,5}
Output:
9
Explanation:
Max subarray sum is 9
of elements (1, 2, 3, -2, 5) which
is a contiguous subarray.
Example 2:
Input:
N = 4
Arr[] = {-1,-2,-3,-4}
Output:
-1
Explanation:
Max subarray sum is -1
of element (-1)
Your Task:
You don't need to read input or print anything. The task is to complete the function maxSubarraySum() which takes Arr[] and N as input parameters and returns the sum of subarray with maximum sum.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 106
-107 ≤ A[i] ≤ 107
0
shreyapanwar71211 hours ago
My soltn:
long long maxSubarraySum(int arr[], int n){ long long maxS=0; long long currS=0; for(int i=0;i<n;i++){ currS+=arr[i]; if(currS>maxS){ maxS=currS; } if(currS<0){ currS=0; } } return maxS; }
error:
prog.cpp:49:1: error: expected } at end of input } ^ prog.cpp:49:1: error: expected unqualified-id at end of input
Q. How am I supposed to solve this if it shows the error in driver code? What have I done wrong?
0
shreyapanwar712
This comment was deleted.
0
sangrambachu1 day ago
To support all -ve number we need to use Math.max()
long maxSubarraySum(int arr[], int n){
// Your code here
long max = arr[0];
long current = arr[0];
for(int i=1; i<n; i++) {
current = Math.max(arr[i], current+arr[i]);
if(current > max) {
max = current;
}
}
return max;
}
0
ianupmondal2 days ago
Easy Java solution:
long maxSubarraySum(int arr[], int n){ long maxSum=Integer.MIN_VALUE; long currSum = 0; for (int i=0; i<n; i++){ currSum += arr[i]; if(currSum>maxSum) maxSum=currSum; if(currSum<0) currSum=0; } return maxSum; }
0
salamromim5 days ago
//Function to find the sum of contiguous subarray with public long maxSubarraySum(int[] arr, int n) { //code intinhere int curmax=0; int max=int.MinValue; // max=0; for(int i=0;i<n;i++) { curmax=arr[i]+curmax; if (curmax<arr[i]) { curmax=Math.Max(arr[i],curmax); if(max<curmax) { max=curmax; } } else { if(curmax>arr[i]) curmax=Math.Max(arr[i],curmax); // else // curmax=Math.Min(arr[i],curmax)
if(max<curmax) max=curmax; } } return max; }
}
0
surabhichoubey556 days ago
i was trying to solve this question without using kadanes algo ........please tell me where my logic fails explain me please it giving me output 11
long long maxSubarraySum(int arr[], int n){ // Your code here long long sum = 0; long long currentSum = 0; int current = 0; long long ans = 0; for(int i = 0;i<n;i++) { sum+= arr[i]; } while(current<n) { ans = max(sum,currentSum); currentSum = sum-arr[current]; current++; } if(ans<-1) { return -1; } return ans; }
0
prasantpoudel331 week ago
max_so_far =arr[0]
curr_max = arr[0]
for i in range(1,N):
curr_max = max(arr[i], curr_max + arr[i])
max_so_far = max(max_so_far,curr_max)
return max_so_far
+1
ligghhts1 week ago
long long maxSubarraySum(int arr[], int n){ // Your code here long long int ans = 0; long long int max = INT_MIN; for(int i = 0;i < n;i++){ ans += arr[i]; if(ans > max)max = ans; if(ans < 0)ans = 0; } return max; }
+1
illiyazzr1 week ago
C++ (Brute Force) Solution | inside main() function
#include <vector>#include <iostream>
using namespace std;
int main(){ vector<int>vec; int arr[] = {-2, -3, 4, -1, -2, 1, 5, -3}; int s = sizeof(arr)/sizeof(arr[0]); int sum=0; for(int i=0;i<s;i++){ for(int j=i;j<s;j++){ sum+=arr[j]; vec.push_back(sum); } sum=0; } int finalSum=vec[0]; for(int i=0;i<vec.size();i++){ if(vec[i]>finalSum){ finalSum=vec[i]; } } cout<<"Longest contiguous sub-array sum : "<<finalSum;}
0
prathamsinghal1 week ago
Great Technique to solve the Problem.Tutorial Link:
class Solution{
// arr: input array
// n: size of array
//Function to find the sum of contiguous subarray with maximum sum.
long maxSubarraySum(int arr[], int n){
// Your code here
long curr_sum = arr[0] ;
long overall_sum = arr[0] ;
for (int i = 1; i<n ; i++) {
if (curr_sum < 0) {
curr_sum = arr[i] ;
}else {
curr_sum += arr[i] ;
}
if(curr_sum > overall_sum){
overall_sum = curr_sum ;
}
}
return overall_sum ;
}
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 382,
"s": 238,
"text": "Given an array Arr[] of N integers. Find the contiguous sub-array(containing at least one number) which has the maximum sum and return its sum."
},
{
"code": null,
"e": 394,
"s": 382,
"text": "\nExample 1:"
},
{
"code": null,
"e": 536,
"s": 394,
"text": "Input:\nN = 5\nArr[] = {1,2,3,-2,5}\nOutput:\n9\nExplanation:\nMax subarray sum is 9\nof elements (1, 2, 3, -2, 5) which \nis a contiguous subarray.\n"
},
{
"code": null,
"e": 547,
"s": 536,
"text": "Example 2:"
},
{
"code": null,
"e": 646,
"s": 547,
"text": "Input:\nN = 4\nArr[] = {-1,-2,-3,-4}\nOutput:\n-1\nExplanation:\nMax subarray sum is -1 \nof element (-1)"
},
{
"code": null,
"e": 854,
"s": 646,
"text": "\nYour Task:\nYou don't need to read input or print anything. The task is to complete the function maxSubarraySum() which takes Arr[] and N as input parameters and returns the sum of subarray with maximum sum."
},
{
"code": null,
"e": 917,
"s": 854,
"text": "\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 961,
"s": 917,
"text": "\nConstraints:\n1 ≤ N ≤ 106\n-107 ≤ A[i] ≤ 107"
},
{
"code": null,
"e": 963,
"s": 961,
"text": "0"
},
{
"code": null,
"e": 991,
"s": 963,
"text": "shreyapanwar71211 hours ago"
},
{
"code": null,
"e": 1001,
"s": 991,
"text": "My soltn:"
},
{
"code": null,
"e": 1300,
"s": 1001,
"text": " long long maxSubarraySum(int arr[], int n){ long long maxS=0; long long currS=0; for(int i=0;i<n;i++){ currS+=arr[i]; if(currS>maxS){ maxS=currS; } if(currS<0){ currS=0; } } return maxS; }"
},
{
"code": null,
"e": 1307,
"s": 1300,
"text": "error:"
},
{
"code": null,
"e": 1422,
"s": 1307,
"text": "prog.cpp:49:1: error: expected } at end of input } ^ prog.cpp:49:1: error: expected unqualified-id at end of input"
},
{
"code": null,
"e": 1521,
"s": 1424,
"text": "Q. How am I supposed to solve this if it shows the error in driver code? What have I done wrong?"
},
{
"code": null,
"e": 1527,
"s": 1525,
"text": "0"
},
{
"code": null,
"e": 1543,
"s": 1527,
"text": "shreyapanwar712"
},
{
"code": null,
"e": 1569,
"s": 1543,
"text": "This comment was deleted."
},
{
"code": null,
"e": 1571,
"s": 1569,
"text": "0"
},
{
"code": null,
"e": 1593,
"s": 1571,
"text": "sangrambachu1 day ago"
},
{
"code": null,
"e": 1645,
"s": 1593,
"text": "To support all -ve number we need to use Math.max()"
},
{
"code": null,
"e": 2012,
"s": 1647,
"text": "long maxSubarraySum(int arr[], int n){\n \n // Your code here\n long max = arr[0];\n long current = arr[0];\n \n for(int i=1; i<n; i++) {\n current = Math.max(arr[i], current+arr[i]);\n \n if(current > max) {\n max = current;\n }\n }\n \n return max;\n }"
},
{
"code": null,
"e": 2014,
"s": 2012,
"text": "0"
},
{
"code": null,
"e": 2036,
"s": 2014,
"text": "ianupmondal2 days ago"
},
{
"code": null,
"e": 2056,
"s": 2036,
"text": "Easy Java solution:"
},
{
"code": null,
"e": 2375,
"s": 2058,
"text": "long maxSubarraySum(int arr[], int n){ long maxSum=Integer.MIN_VALUE; long currSum = 0; for (int i=0; i<n; i++){ currSum += arr[i]; if(currSum>maxSum) maxSum=currSum; if(currSum<0) currSum=0; } return maxSum; }"
},
{
"code": null,
"e": 2377,
"s": 2375,
"text": "0"
},
{
"code": null,
"e": 2398,
"s": 2377,
"text": "salamromim5 days ago"
},
{
"code": null,
"e": 2940,
"s": 2398,
"text": " //Function to find the sum of contiguous subarray with public long maxSubarraySum(int[] arr, int n) { //code intinhere int curmax=0; int max=int.MinValue; // max=0; for(int i=0;i<n;i++) { curmax=arr[i]+curmax; if (curmax<arr[i]) { curmax=Math.Max(arr[i],curmax); if(max<curmax) { max=curmax; } } else { if(curmax>arr[i]) curmax=Math.Max(arr[i],curmax); // else // curmax=Math.Min(arr[i],curmax)"
},
{
"code": null,
"e": 3017,
"s": 2940,
"text": " if(max<curmax) max=curmax; } } return max; }"
},
{
"code": null,
"e": 3019,
"s": 3017,
"text": "}"
},
{
"code": null,
"e": 3021,
"s": 3019,
"text": "0"
},
{
"code": null,
"e": 3048,
"s": 3021,
"text": "surabhichoubey556 days ago"
},
{
"code": null,
"e": 3200,
"s": 3048,
"text": "i was trying to solve this question without using kadanes algo ........please tell me where my logic fails explain me please it giving me output 11 "
},
{
"code": null,
"e": 3599,
"s": 3202,
"text": "long long maxSubarraySum(int arr[], int n){ // Your code here long long sum = 0; long long currentSum = 0; int current = 0; long long ans = 0; for(int i = 0;i<n;i++) { sum+= arr[i]; } while(current<n) { ans = max(sum,currentSum); currentSum = sum-arr[current]; current++; } if(ans<-1) { return -1; } return ans; }"
},
{
"code": null,
"e": 3601,
"s": 3599,
"text": "0"
},
{
"code": null,
"e": 3627,
"s": 3601,
"text": "prasantpoudel331 week ago"
},
{
"code": null,
"e": 3801,
"s": 3627,
"text": "max_so_far =arr[0]\ncurr_max = arr[0]\n \nfor i in range(1,N):\n curr_max = max(arr[i], curr_max + arr[i])\n max_so_far = max(max_so_far,curr_max)\nreturn max_so_far\n "
},
{
"code": null,
"e": 3804,
"s": 3801,
"text": "+1"
},
{
"code": null,
"e": 3823,
"s": 3804,
"text": "ligghhts1 week ago"
},
{
"code": null,
"e": 4117,
"s": 3823,
"text": " long long maxSubarraySum(int arr[], int n){ // Your code here long long int ans = 0; long long int max = INT_MIN; for(int i = 0;i < n;i++){ ans += arr[i]; if(ans > max)max = ans; if(ans < 0)ans = 0; } return max; }"
},
{
"code": null,
"e": 4120,
"s": 4117,
"text": "+1"
},
{
"code": null,
"e": 4140,
"s": 4120,
"text": "illiyazzr1 week ago"
},
{
"code": null,
"e": 4192,
"s": 4140,
"text": "C++ (Brute Force) Solution | inside main() function"
},
{
"code": null,
"e": 4231,
"s": 4194,
"text": "#include <vector>#include <iostream>"
},
{
"code": null,
"e": 4252,
"s": 4231,
"text": "using namespace std;"
},
{
"code": null,
"e": 4680,
"s": 4252,
"text": "int main(){ vector<int>vec; int arr[] = {-2, -3, 4, -1, -2, 1, 5, -3}; int s = sizeof(arr)/sizeof(arr[0]); int sum=0; for(int i=0;i<s;i++){ for(int j=i;j<s;j++){ sum+=arr[j]; vec.push_back(sum); } sum=0; } int finalSum=vec[0]; for(int i=0;i<vec.size();i++){ if(vec[i]>finalSum){ finalSum=vec[i]; } } cout<<\"Longest contiguous sub-array sum : \"<<finalSum;}"
},
{
"code": null,
"e": 4684,
"s": 4682,
"text": "0"
},
{
"code": null,
"e": 4709,
"s": 4684,
"text": "prathamsinghal1 week ago"
},
{
"code": null,
"e": 4762,
"s": 4709,
"text": "Great Technique to solve the Problem.Tutorial Link: "
},
{
"code": null,
"e": 5327,
"s": 4762,
"text": "class Solution{\n\n // arr: input array\n // n: size of array\n //Function to find the sum of contiguous subarray with maximum sum.\n long maxSubarraySum(int arr[], int n){\n \n // Your code here\n long curr_sum = arr[0] ; \n long overall_sum = arr[0] ; \n \n for (int i = 1; i<n ; i++) {\n if (curr_sum < 0) {\n curr_sum = arr[i] ; \n }else {\n curr_sum += arr[i] ;\n }\n if(curr_sum > overall_sum){\n overall_sum = curr_sum ;\n }\n }\n return overall_sum ; \n }\n \n}"
},
{
"code": null,
"e": 5473,
"s": 5327,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 5509,
"s": 5473,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5519,
"s": 5509,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5529,
"s": 5519,
"text": "\nContest\n"
},
{
"code": null,
"e": 5592,
"s": 5529,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5740,
"s": 5592,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 5948,
"s": 5740,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 6054,
"s": 5948,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
How to Rank Text Content by Semantic Similarity | by Rupert Thomas | Towards Data Science
|
Search is a standard tool for finding content — whether it's online or on-device — but what if you wanted to go deeper and find content based on the meaning of words? Tools developed for Natural Langage Processing can help.
In this article we will cover two methods of calculating the similarity of text:
Term Frequency-inverse document frequency (TF-idf): this looks at words that appear in both pieces of text, and scores them based on how often they appear. It is a useful tool if you expect the same words to appear in both pieces of text, but some words are more important that others.Semantic similarity: this scores words based on how similar they are, even if they are not exact matches. It borrows techniques from Natural Language Processing (NLP), such as word embeddings. This is useful if the word overlap between texts is limited, such as if you need ‘fruit and vegetables’ to relate to ‘tomatoes’.
Term Frequency-inverse document frequency (TF-idf): this looks at words that appear in both pieces of text, and scores them based on how often they appear. It is a useful tool if you expect the same words to appear in both pieces of text, but some words are more important that others.
Semantic similarity: this scores words based on how similar they are, even if they are not exact matches. It borrows techniques from Natural Language Processing (NLP), such as word embeddings. This is useful if the word overlap between texts is limited, such as if you need ‘fruit and vegetables’ to relate to ‘tomatoes’.
For the first part, we’ll use the TF-idf implementation in scikit-learn in isolation, as its really simple and only requires a couple of lines of code. For semantic similarity, we’ll use a number of functions from gensim (including its TF-idf implementation) and pre-trained word vectors from the GloVe algorithm. Also, we’ll need a few tools from nltk. These packages can be installed using pip:
pip install scikit-learn~=0.22pip install gensim~=3.8pip install nltk~=3.4
Alternatively, you can grab the example code from the GitHub repository and install from the requirements file:
git clone https://github.com/4OH4/doc-similaritycd doc-similaritypip install -r requirements.txt
github.com
Run the demo code in examples.ipynb,Use the tfidf.rank_documents(search_terms: str, documents: list) function to score documents based on overlapping content,Use the docsim.DocSim() class to score documents on similarity using doc2vec and the GloVe word embedding model.
Run the demo code in examples.ipynb,
Use the tfidf.rank_documents(search_terms: str, documents: list) function to score documents based on overlapping content,
Use the docsim.DocSim() class to score documents on similarity using doc2vec and the GloVe word embedding model.
Document: a piece of text, in the form of a string. This could be just a few words, or a whole novel.
Corpus: a collection of documents.
Term: a word in a document.
Term Frequency-inverse document frequency (or TF-idf) is an established technique for scoring document similarity based on the importance of the words that they share. Very high level summary:
if a term (word) appears frequently in a document, that term is probably important in that document.
but, if a term appears frequently in many documents, that term is probably less important generally.
A TF-idf score estimates the trade-off between those two heuristics, based on how frequently a word appears. There is a more detailed summary here.
We can create and fit a TF-idf vectorizer model from scikit-learn with only a few lines of code:
Here, we create the model and ‘fit’ using the text corpus. TfidfVectorizer handles the pre-processing using its default tokenizer — this converts strings into lists of single word ‘tokens’. It produces a sparse matrix of document vectors containing the term frequencies.
We then take the dot product (linear kernel) of the first vector (that contains the search terms) with the documents to determine the similarity. We have to ignore the first similarity result ([1:]) as that is comparing the search terms to themselves.
This works well for a simple example, but may fall down in real-world cases for a number of reasons.
Firstly, it doesn’t make much sense to involve words such as [‘and’, ‘on’, ‘the’, ‘are’] in the matching process, as these stopwords don’t contain contextual information. These words should be stripped out before determining similarity.
Secondly, we would want ‘fruit’ and ‘fruits’ to be recognised as related, although the model above only find exact matches. One approach to this problem is to reduce each word down to its simplest lemma — for that we need a lemmatizer.
In this case, ‘tomatoes’ in the second document is reduced to ‘tomato’ by the lemmatizer (tokenizer), which is then matched to the same word in the search terms.
Conceptually, each document is a point in a high-dimensional space, where the number of dimensions is equal to the number of unique words in the text corpus. This space will usually be quite empty, with large distances between points (documents) as documents contain a wide variety of words. In this scenario, the angle between points makes more sense as a metric of similarity than, for example, a distance-related metric such as Euclidean distance.
The similarity here is referred to as the cosine similarity. The output from TfidfVectorizer is (by default) L2-normalized, so then the dot product of two vectors is the cosine of the angle between the points denoted by the vectors.
It’s fast and works well when documents are large and/or have lots of overlap.
It looks for exact matches, so at the very least you should use a lemmatizer to take care of the plurals.
When comparing short documents with limited-term variety — such as search queries — there is a risk that you will miss semantic relationships where there isn’t an exact word match.
A move advanced approach is to compare documents based on how similar their words are. For example, ‘apples’ and ‘oranges’ might be regarded as more similar than ‘apples’ and ‘Jupiter’. Judging word similarity at scale is difficult — one widely used approach is to analyse a large corpus of text and rank words that appear together often as being more similar.
This is the basis of the word embedding model GloVe: it maps words into numerical vectors — points in a multi-dimensional space so that words that occur together often are near each other in space. It is an unsupervised learning algorithm, developed at Stanford University in 2014.
In the previous example, we used WordNetLemmatizer from the nltk package to stem and tokenize (convert to a list of single word strings) our data. Here we do similar preprocessing in gensim, and also remove any HTML tags that may be present, such as if we have scraped data from the web:
Then we create a similarity matrix, that contains the similarity between each pair of words, weighted using the term frequency:
Finally, we calculate the soft cosine similarity between the query and each of the documents. Unlike the regular cosine similarity (which would return zero for vectors with no overlapping terms), the soft cosine similarity considers word similarity as well.
There is a full example in the notebook in the code repository. There is also a self-contained DocSim class, that can be imported as a module and used to run semantic similarity queries without additional code:
from docsim import DocSimdocsim = DocSim(verbose=True)similarities = docsim.similarity_query(query_string, documents)
The GloVe word embedding models can be quite large — on my machine it took about 40 seconds to load from disk. Once it's loaded, however, subsequent operations are faster. The multi-threaded version of the class loads the model in the background, to avoid locking the main thread for a significant period of time. It is used in a similar way, although will raise an exception if the model is still loading so the status of the model_ready property should be checked first.
from docsim import DocSim_threadeddocsim = DocSim_threaded(verbose=True)similarities = docsim.similarity_query(query_string, documents)
It is more flexible as it doesn’t rely on finding exact matches.
There is a lot more computation involved so it can be slower, and the word embedding models can be quite large and take a while to prepare for first use. This scales well, but running a single query is slow.
Most words have some degree of similarity to other words, so almost all documents will have some non-zero similarity to other documents. Semantic similarity is good for ranking content in order, rather than making specific judgements about whether a document is or is not about a specific topic.
We’ve looked at two methods for comparing text content for similarity, such as might be used for search queries or content recommender systems. The first (TF-idf) scores document relationships based on the frequency of occurrence of shared words. It is fast and works well when documents are large and/or have lots of overlapping terms. The second technique looks for shared words that address similar concepts, but it does not require an exact match: for example, it links ‘fruit and vegetables’ with the word ‘tomato’. This is slower, and can sometimes give less clear-cut results, but is good with shorter search queries or documents with low word overlap.
I examined both of these methods for a real-world application: I needed to know if any of a <collection of documents> related to a small number of <search terms>. Initially, I thought I would need to use semantic similarity matching — the search terms came from uncontrolled user input and so there might be some pretty tenuous relationships. Document ranking was a useful feature, but the overall aim was to apply a decision threshold so that a binary yes/no result could be generated.
For that particular application, I found that using TF-idf alone was sufficient. The collections of documents were usually large enough that — in the cases when a match should indeed be found—there was sufficient overlap with the search terms. TF-idf gave a clearer separation between the positive and negative cases, although it did miss a few documents that would also be relevant.
Its worth taking a data-driven approach, and seeing what works best in your application.
What are your thoughts? Have you used these tools in your work, or do you favor a different approach? Leave your comments below!
Rupert Thomas is a technology consultant specialising in machine learning, machine vision, and data-driven products. @rupertthomas
Sci-kit Learn: TfidfVectorizer
GloVe: Global Vectors for Word Representation
Gensim: Soft Cosine Tutorial
|
[
{
"code": null,
"e": 396,
"s": 172,
"text": "Search is a standard tool for finding content — whether it's online or on-device — but what if you wanted to go deeper and find content based on the meaning of words? Tools developed for Natural Langage Processing can help."
},
{
"code": null,
"e": 477,
"s": 396,
"text": "In this article we will cover two methods of calculating the similarity of text:"
},
{
"code": null,
"e": 1084,
"s": 477,
"text": "Term Frequency-inverse document frequency (TF-idf): this looks at words that appear in both pieces of text, and scores them based on how often they appear. It is a useful tool if you expect the same words to appear in both pieces of text, but some words are more important that others.Semantic similarity: this scores words based on how similar they are, even if they are not exact matches. It borrows techniques from Natural Language Processing (NLP), such as word embeddings. This is useful if the word overlap between texts is limited, such as if you need ‘fruit and vegetables’ to relate to ‘tomatoes’."
},
{
"code": null,
"e": 1370,
"s": 1084,
"text": "Term Frequency-inverse document frequency (TF-idf): this looks at words that appear in both pieces of text, and scores them based on how often they appear. It is a useful tool if you expect the same words to appear in both pieces of text, but some words are more important that others."
},
{
"code": null,
"e": 1692,
"s": 1370,
"text": "Semantic similarity: this scores words based on how similar they are, even if they are not exact matches. It borrows techniques from Natural Language Processing (NLP), such as word embeddings. This is useful if the word overlap between texts is limited, such as if you need ‘fruit and vegetables’ to relate to ‘tomatoes’."
},
{
"code": null,
"e": 2089,
"s": 1692,
"text": "For the first part, we’ll use the TF-idf implementation in scikit-learn in isolation, as its really simple and only requires a couple of lines of code. For semantic similarity, we’ll use a number of functions from gensim (including its TF-idf implementation) and pre-trained word vectors from the GloVe algorithm. Also, we’ll need a few tools from nltk. These packages can be installed using pip:"
},
{
"code": null,
"e": 2164,
"s": 2089,
"text": "pip install scikit-learn~=0.22pip install gensim~=3.8pip install nltk~=3.4"
},
{
"code": null,
"e": 2276,
"s": 2164,
"text": "Alternatively, you can grab the example code from the GitHub repository and install from the requirements file:"
},
{
"code": null,
"e": 2373,
"s": 2276,
"text": "git clone https://github.com/4OH4/doc-similaritycd doc-similaritypip install -r requirements.txt"
},
{
"code": null,
"e": 2384,
"s": 2373,
"text": "github.com"
},
{
"code": null,
"e": 2655,
"s": 2384,
"text": "Run the demo code in examples.ipynb,Use the tfidf.rank_documents(search_terms: str, documents: list) function to score documents based on overlapping content,Use the docsim.DocSim() class to score documents on similarity using doc2vec and the GloVe word embedding model."
},
{
"code": null,
"e": 2692,
"s": 2655,
"text": "Run the demo code in examples.ipynb,"
},
{
"code": null,
"e": 2815,
"s": 2692,
"text": "Use the tfidf.rank_documents(search_terms: str, documents: list) function to score documents based on overlapping content,"
},
{
"code": null,
"e": 2928,
"s": 2815,
"text": "Use the docsim.DocSim() class to score documents on similarity using doc2vec and the GloVe word embedding model."
},
{
"code": null,
"e": 3030,
"s": 2928,
"text": "Document: a piece of text, in the form of a string. This could be just a few words, or a whole novel."
},
{
"code": null,
"e": 3065,
"s": 3030,
"text": "Corpus: a collection of documents."
},
{
"code": null,
"e": 3093,
"s": 3065,
"text": "Term: a word in a document."
},
{
"code": null,
"e": 3286,
"s": 3093,
"text": "Term Frequency-inverse document frequency (or TF-idf) is an established technique for scoring document similarity based on the importance of the words that they share. Very high level summary:"
},
{
"code": null,
"e": 3387,
"s": 3286,
"text": "if a term (word) appears frequently in a document, that term is probably important in that document."
},
{
"code": null,
"e": 3488,
"s": 3387,
"text": "but, if a term appears frequently in many documents, that term is probably less important generally."
},
{
"code": null,
"e": 3636,
"s": 3488,
"text": "A TF-idf score estimates the trade-off between those two heuristics, based on how frequently a word appears. There is a more detailed summary here."
},
{
"code": null,
"e": 3733,
"s": 3636,
"text": "We can create and fit a TF-idf vectorizer model from scikit-learn with only a few lines of code:"
},
{
"code": null,
"e": 4004,
"s": 3733,
"text": "Here, we create the model and ‘fit’ using the text corpus. TfidfVectorizer handles the pre-processing using its default tokenizer — this converts strings into lists of single word ‘tokens’. It produces a sparse matrix of document vectors containing the term frequencies."
},
{
"code": null,
"e": 4256,
"s": 4004,
"text": "We then take the dot product (linear kernel) of the first vector (that contains the search terms) with the documents to determine the similarity. We have to ignore the first similarity result ([1:]) as that is comparing the search terms to themselves."
},
{
"code": null,
"e": 4357,
"s": 4256,
"text": "This works well for a simple example, but may fall down in real-world cases for a number of reasons."
},
{
"code": null,
"e": 4594,
"s": 4357,
"text": "Firstly, it doesn’t make much sense to involve words such as [‘and’, ‘on’, ‘the’, ‘are’] in the matching process, as these stopwords don’t contain contextual information. These words should be stripped out before determining similarity."
},
{
"code": null,
"e": 4830,
"s": 4594,
"text": "Secondly, we would want ‘fruit’ and ‘fruits’ to be recognised as related, although the model above only find exact matches. One approach to this problem is to reduce each word down to its simplest lemma — for that we need a lemmatizer."
},
{
"code": null,
"e": 4992,
"s": 4830,
"text": "In this case, ‘tomatoes’ in the second document is reduced to ‘tomato’ by the lemmatizer (tokenizer), which is then matched to the same word in the search terms."
},
{
"code": null,
"e": 5443,
"s": 4992,
"text": "Conceptually, each document is a point in a high-dimensional space, where the number of dimensions is equal to the number of unique words in the text corpus. This space will usually be quite empty, with large distances between points (documents) as documents contain a wide variety of words. In this scenario, the angle between points makes more sense as a metric of similarity than, for example, a distance-related metric such as Euclidean distance."
},
{
"code": null,
"e": 5676,
"s": 5443,
"text": "The similarity here is referred to as the cosine similarity. The output from TfidfVectorizer is (by default) L2-normalized, so then the dot product of two vectors is the cosine of the angle between the points denoted by the vectors."
},
{
"code": null,
"e": 5755,
"s": 5676,
"text": "It’s fast and works well when documents are large and/or have lots of overlap."
},
{
"code": null,
"e": 5861,
"s": 5755,
"text": "It looks for exact matches, so at the very least you should use a lemmatizer to take care of the plurals."
},
{
"code": null,
"e": 6042,
"s": 5861,
"text": "When comparing short documents with limited-term variety — such as search queries — there is a risk that you will miss semantic relationships where there isn’t an exact word match."
},
{
"code": null,
"e": 6403,
"s": 6042,
"text": "A move advanced approach is to compare documents based on how similar their words are. For example, ‘apples’ and ‘oranges’ might be regarded as more similar than ‘apples’ and ‘Jupiter’. Judging word similarity at scale is difficult — one widely used approach is to analyse a large corpus of text and rank words that appear together often as being more similar."
},
{
"code": null,
"e": 6685,
"s": 6403,
"text": "This is the basis of the word embedding model GloVe: it maps words into numerical vectors — points in a multi-dimensional space so that words that occur together often are near each other in space. It is an unsupervised learning algorithm, developed at Stanford University in 2014."
},
{
"code": null,
"e": 6973,
"s": 6685,
"text": "In the previous example, we used WordNetLemmatizer from the nltk package to stem and tokenize (convert to a list of single word strings) our data. Here we do similar preprocessing in gensim, and also remove any HTML tags that may be present, such as if we have scraped data from the web:"
},
{
"code": null,
"e": 7101,
"s": 6973,
"text": "Then we create a similarity matrix, that contains the similarity between each pair of words, weighted using the term frequency:"
},
{
"code": null,
"e": 7359,
"s": 7101,
"text": "Finally, we calculate the soft cosine similarity between the query and each of the documents. Unlike the regular cosine similarity (which would return zero for vectors with no overlapping terms), the soft cosine similarity considers word similarity as well."
},
{
"code": null,
"e": 7570,
"s": 7359,
"text": "There is a full example in the notebook in the code repository. There is also a self-contained DocSim class, that can be imported as a module and used to run semantic similarity queries without additional code:"
},
{
"code": null,
"e": 7688,
"s": 7570,
"text": "from docsim import DocSimdocsim = DocSim(verbose=True)similarities = docsim.similarity_query(query_string, documents)"
},
{
"code": null,
"e": 8161,
"s": 7688,
"text": "The GloVe word embedding models can be quite large — on my machine it took about 40 seconds to load from disk. Once it's loaded, however, subsequent operations are faster. The multi-threaded version of the class loads the model in the background, to avoid locking the main thread for a significant period of time. It is used in a similar way, although will raise an exception if the model is still loading so the status of the model_ready property should be checked first."
},
{
"code": null,
"e": 8297,
"s": 8161,
"text": "from docsim import DocSim_threadeddocsim = DocSim_threaded(verbose=True)similarities = docsim.similarity_query(query_string, documents)"
},
{
"code": null,
"e": 8362,
"s": 8297,
"text": "It is more flexible as it doesn’t rely on finding exact matches."
},
{
"code": null,
"e": 8570,
"s": 8362,
"text": "There is a lot more computation involved so it can be slower, and the word embedding models can be quite large and take a while to prepare for first use. This scales well, but running a single query is slow."
},
{
"code": null,
"e": 8866,
"s": 8570,
"text": "Most words have some degree of similarity to other words, so almost all documents will have some non-zero similarity to other documents. Semantic similarity is good for ranking content in order, rather than making specific judgements about whether a document is or is not about a specific topic."
},
{
"code": null,
"e": 9526,
"s": 8866,
"text": "We’ve looked at two methods for comparing text content for similarity, such as might be used for search queries or content recommender systems. The first (TF-idf) scores document relationships based on the frequency of occurrence of shared words. It is fast and works well when documents are large and/or have lots of overlapping terms. The second technique looks for shared words that address similar concepts, but it does not require an exact match: for example, it links ‘fruit and vegetables’ with the word ‘tomato’. This is slower, and can sometimes give less clear-cut results, but is good with shorter search queries or documents with low word overlap."
},
{
"code": null,
"e": 10013,
"s": 9526,
"text": "I examined both of these methods for a real-world application: I needed to know if any of a <collection of documents> related to a small number of <search terms>. Initially, I thought I would need to use semantic similarity matching — the search terms came from uncontrolled user input and so there might be some pretty tenuous relationships. Document ranking was a useful feature, but the overall aim was to apply a decision threshold so that a binary yes/no result could be generated."
},
{
"code": null,
"e": 10397,
"s": 10013,
"text": "For that particular application, I found that using TF-idf alone was sufficient. The collections of documents were usually large enough that — in the cases when a match should indeed be found—there was sufficient overlap with the search terms. TF-idf gave a clearer separation between the positive and negative cases, although it did miss a few documents that would also be relevant."
},
{
"code": null,
"e": 10486,
"s": 10397,
"text": "Its worth taking a data-driven approach, and seeing what works best in your application."
},
{
"code": null,
"e": 10615,
"s": 10486,
"text": "What are your thoughts? Have you used these tools in your work, or do you favor a different approach? Leave your comments below!"
},
{
"code": null,
"e": 10746,
"s": 10615,
"text": "Rupert Thomas is a technology consultant specialising in machine learning, machine vision, and data-driven products. @rupertthomas"
},
{
"code": null,
"e": 10777,
"s": 10746,
"text": "Sci-kit Learn: TfidfVectorizer"
},
{
"code": null,
"e": 10823,
"s": 10777,
"text": "GloVe: Global Vectors for Word Representation"
}
] |
Machine Learning Project: Predicting Boston House Prices With Regression | by Victor Roman | Towards Data Science
|
In this project, we will develop and evaluate the performance and the predictive power of a model trained and tested on data collected from houses in Boston’s suburbs.
Once we get a good fit, we will use this model to predict the monetary value of a house located at the Boston’s area.
A model like this would be very valuable for a real state agent who could make use of the information provided in a dayly basis.
You can find the complete project, documentation and dataset on my GitHub page:
https://github.com/rromanss23/Machine_Leaning_Engineer_Udacity_NanoDegree/tree/master/projects/boston_housing
The dataset used in this project comes from the UCI Machine Learning Repository. This data was collected in 1978 and each of the 506 entries represents aggregate information about 14 features of homes from various suburbs located in Boston.
The features can be summarized as follows:
CRIM: This is the per capita crime rate by town
ZN: This is the proportion of residential land zoned for lots larger than 25,000 sq.ft.
INDUS: This is the proportion of non-retail business acres per town.
CHAS: This is the Charles River dummy variable (this is equal to 1 if tract bounds river; 0 otherwise)
NOX: This is the nitric oxides concentration (parts per 10 million)
RM: This is the average number of rooms per dwelling
AGE: This is the proportion of owner-occupied units built prior to 1940
DIS: This is the weighted distances to five Boston employment centers
RAD: This is the index of accessibility to radial highways
TAX: This is the full-value property-tax rate per $10,000
PTRATIO: This is the pupil-teacher ratio by town
B: This is calculated as 1000(Bk — 0.63)2, where Bk is the proportion of people of African American descent by town
LSTAT: This is the percentage lower status of the population
MEDV: This is the median value of owner-occupied homes in $1000s
This is an overview of the original dataset, with its original features:
For the purpose of the project the dataset has been preprocessed as follows:
The essential features for the project are: ‘RM’, ‘LSTAT’, ‘PTRATIO’ and ‘MEDV’. The remaining features have been excluded.
16 data points with a ‘MEDV’ value of 50.0 have been removed. As they likely contain censored or missing values.
1 data point with a ‘RM’ value of 8.78 it is considered an outlier and has been removed for the optimal performance of the model.
As this data is out of date, the ‘MEDV’ value has been scaled multiplicatively to account for 35 years of markt inflation.
We’ll now open a python 3 Jupyter Notebook and execute the following code snippet to load the dataset and remove the non-essential features. Recieving a success message if the actions were correclty performed.
As our goal is to develop a model that has the capacity of predicting the value of houses, we will split the dataset into features and the target variable. And store them in features and prices variables, respectively
The features ‘RM’, ‘LSTAT’ and ‘PTRATIO’, give us quantitative information abouth each datapoint. We will store them in features.
The target variable, ‘MEDV’, will be the variable we seek to predict. We will store it in prices.
# Import libraries necessary for this projectimport numpy as npimport pandas as pdfrom sklearn.model_selection import ShuffleSplit# Import supplementary visualizations code visuals.pyimport visuals as vs# Pretty display for notebooks%matplotlib inline# Load the Boston housing datasetdata = pd.read_csv('housing.csv')prices = data['MEDV']features = data.drop('MEDV', axis = 1) # Successprint("Boston housing dataset has {} data points with {} variables each.".format(*data.shape))
In the first section of the project, we will make an exploratory analysis of the dataset and provide some observations.
Calculate Statistics
# Minimum price of the dataminimum_price = np.amin(prices)# Maximum price of the datamaximum_price = np.amax(prices)# Mean price of the datamean_price = np.mean(prices)# Median price of the datamedian_price = np.median(prices)# Standard deviation of prices of the datastd_price = np.std(prices)# Show the calculated statisticsprint("Statistics for Boston housing dataset:\n")print("Minimum price: ${}".format(minimum_price)) print("Maximum price: ${}".format(maximum_price))print("Mean price: ${}".format(mean_price))print("Median price ${}".format(median_price))print("Standard deviation of prices: ${}".format(std_price))
Data Science is the process of making some assumptions and hypothesis on the data, and testing them by performing some tasks. Initially we could make the following intuitive assumptions for each feature:
Houses with more rooms (higher ‘RM’ value) will worth more. Usually houses with more rooms are bigger and can fit more people, so it is reasonable that they cost more money. They are directly proportional variables.
Neighborhoods with more lower class workers (higher ‘LSTAT’ value) will worth less. If the percentage of lower working class people is higher, it is likely that they have low purchasing power and therefore, they houses will cost less. They are inversely proportional variables.
Neighborhoods with more students to teachers ratio (higher ‘PTRATIO’ value) will be worth less. If the percentage of students to teachers ratio people is higher, it is likely that in the neighborhood there are less schools, this could be because there is less tax income which could be because in that neighborhood people earn less money. If people earn less money it is likely that their houses are worth less. They are inversely proportional variables.
We’ll find out if these assumptions are correct through the project.
Scatterplot and Histograms
We will start by creating a scatterplot matrix that will allow us to visualize the pair-wise relationships and correlations between the different features.
It is also quite useful to have a quick overview of how the data is distributed and wheter it cointains or not outliers.
import matplotlib.pyplot as pltimport seaborn as sns%matplotlib inline# Calculate and show pairplotsns.pairplot(data, size=2.5)plt.tight_layout()
We can spot a linear relationship between ‘RM’ and House prices ‘MEDV’. In addition, we can infer from the histogram that the ‘MEDV’ variable seems to be normally distributed but contain several outliers.
Correlation Matrix
We are going to create now a correlation matrix to quantify and summarize the relationships between the variables.
This correlation matrix is closely related witn covariance matrix, in fact it is a rescaled version of the covariance matrix, computed from standardize features.
It is a square matrix (with the same number of columns and rows) that contains the Person’s r correlation coefficient.
# Calculate and show correlation matrixcm = np.corrcoef(data.values.T)sns.set(font_scale=1.5)hm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f', annot_kws={'size': 15}, yticklabels=cols, xticklabels=cols)
To fit a regression model, the features of interest are the ones with a high correlation with the target variable ‘MEDV’. From the previous correlation matrix, we can see that this condition is achieved for our selected variables.
In this second section of the project, we will develop the tools and techniques necessary for a model to make a prediction. Being able to make accurate evaluations of each model’s performance through the use of these tools and techniques helps to reinforce greatly the confidence in the predictions.
Defining a Performace Metric
It is difficult to measure the quality of a given model without quantifying its performance on the training and testing. This is typically done using some type of performance metric, whether it is through calculating some type of error, the goodness of fit, or some other useful measurement.
For this project, we will calculate the coefficient of determination, R2, to quantify the model’s performance. The coefficient of determination for a model is a useful statistic in regression analysis, as it often describes how “good” that model is at making predictions.
The values for R2 range from 0 to 1, which captures the percentage of squared correlation between the predicted and actual values of the target variable.
A model with an R2 of 0 is no better than a model that always predicts the mean of the target variable.
Whereas a model with an R2 of 1 perfectly predicts the target variable.
Any value between 0 and 1 indicates what percentage of the target variable, using this model, can be explained by the features.
A model can be given a negative R2 as well, which indicates that the model is arbitrarily worse than one that always predicts the mean of the target variable.
# Import 'r2_score'from sklearn.metrics import r2_scoredef performance_metric(y_true, y_predict): """ Calculates and returns the performance score between true (y_true) and predicted (y_predict) values based on the metric chosen. """ score = r2_score(y_true, y_predict) # Return the score return score
Shuffle and Split Data
For this section we will take the Boston housing dataset and split the data into training and testing subsets. Typically, the data is also shuffled into a random order when creating the training and testing subsets to remove any bias in the ordering of the dataset.
# Import 'train_test_split'from sklearn.model_selection import train_test_split# Shuffle and split the data into training and testing subsetsX_train, X_test, y_train, y_test = train_test_split(features, prices, test_size=0.2, random_state = 42)# Successprint("Training and testing split was successful.")
Training and Testing
You may ask now:
What is the benefit to splitting a dataset into some ratio of training and testing subsets for a learning algorithm?
It is useful to evaluate our model once it is trained. We want to know if it has learned properly from a training split of the data. There can be 3 different situations:
1) The model didn ́t learn well on the data, and can’t predict even the outcomes of the training set, this is called underfitting and it is caused because a high bias.
2) The model learn too well the training data, up to the point that it memorized it and is not able to generalize on new data, this is called overfitting, it is caused because high variance.
3) The model just had the right balance between bias and variance, it learned well and is able predict correctly the outcomes on new data.
In this third section of the project, we’ll take a look at several models’ learning and testing performances on various subsets of training data.
Additionally, we’ll investigate one particular algorithm with an increasing 'max_depth' parameter on the full training set to observe how model complexity affects performance.
Graphing the model's performance based on varying criteria can be beneficial in the analysis process, such as visualizing behavior that may not have been apparent from the results alone.
Learning Curves
The following code cell produces four graphs for a decision tree model with different maximum depths. Each graph visualizes the learning curves of the model for both training and testing as the size of the training set is increased.
Note that the shaded region of a learning curve denotes the uncertainty of that curve (measured as the standard deviation). The model is scored on both the training and testing sets using R2, the coefficient of determination.
# Produce learning curves for varying training set sizes and maximum depthsvs.ModelLearning(features, prices)
Learning the Data
If we take a close look at the graph with the max depth of 3:
As the number of training points increases, the training score decreases. In contrast, the test score increases.
As both scores (training and testing) tend to converge, from the 300 points treshold, having more training points will not benefit the model.
In general, with more columns for each observation, we’ll get more information and the model will be able to learn better from the dataset and therefore, make better predictions.
Complexity Curves
The following code cell produces a graph for a decision tree model that has been trained and validated on the training data using different maximum depths. The graph produces two complexity curves — one for training and one for validation.
Similar to the learning curves, the shaded regions of both the complexity curves denote the uncertainty in those curves, and the model is scored on both the training and validation sets using the performance_metric function.
# Produce complexity curve for varying training set sizes and maximum depthsvs.ModelComplexity(X_train, y_train)
Bias-Variance Tradeoff
If we analize how the bias-variance vary with the maximun depth, we can infer that:
With the maximun depth of one, the graphic shows that the model does not return good score in neither training nor testing data, which is a symptom of underfitting and so, high bias. To improve performance, we should increase model’s complexity, in this case increasing the max_depth hyperparameter to get better results.
With the maximun depth of ten, the graphic shows that the model learn perfectly well from training data (with a score close to one) and also returns poor results on test data, which is an indicator of overfitting, not being able to generalize well on new data. This is a problem of High Variance. To improve performance, we should decrease the model’s complexity, in this case decreasing the max_depth hyperparameter to get better results.
Best-Guess Optimal Model
From the complexity curve, we can infer that the best maximum depth for the model is 4, as it is the one that yields the best validation score.
In addition, for more depth although the training score increases, validation score tends to decrease which is a sign of overfitting.
In this final section of the project, we will construct a model and make a prediction on the client’s feature set using an optimized model from fit_model.
Grid Search
The grid search technique exhaustively generates candidates from a grid of parameter values specified with the param_grid parameter, which is a dictionary with the values of the hyperparameters to evaluate. One example can be:
param_grid = [ {‘C’: [1, 10, 100, 1000], ‘kernel’: [‘linear’]}, {‘C’: [1, 10, 100, 1000], ‘gamma’: [0.001, 0.0001], ‘kernel’: [‘rbf’]}, ]
In this example, two grids should be explored: one with a linear kernel an C values of [1,10,100,1000], and the second one with an RBF kernel, and the cross product of C values ranging in [1, 10, 100, 1000] and gamma values in [0.001, 0.0001].
When fitting it on a dataset all the possible combinations of parameter values are evaluated and the best combination is retained.
K-fold cross-validation is a technique used for making sure that our model is well trained, without using the test set. It consist in splitting data into k partitions of equal size. For each partition i, we train the model on the remaining k-1 parameters and evaluate it on partition i. The final score is the average of the K scores obtained.
When evaluating different hyperparameters for estimators, there is still a risk of overfitting on the test set because the parameters can be tweaked until the estimator performs optimally. This way, knowledge about the test set can “leak” into the model and evaluation metrics no longer report on generalization performance.
To solve this problem, yet another part of the dataset can be held out as a so-called “validation set”: training proceeds on the training set, after which evaluation is done on the validation set, and when the experiment seems to be successful, final evaluation can be done on the test set.
However, by partitioning the available data into three sets (training, validating and testing sets), we drastically reduce the number of samples which can be used for learning the model, and the resulting model may not be sufficiently well trained (underfitting).
By using k-fold validation we make sure that the model uses all the training data available for tunning the model, it can be computationally expensive but allows to train models even if little data is available.
The main purpose of k-fold validation is to get an unbiased estimate of model generalization on new data.
Fitting a Model
The final implementation requires that we bring everything together and train a model using the decision tree algorithm.
To ensure that we are producing an optimized model, we will train the model using the grid search technique to optimize the 'max_depth'parameter for the decision tree. The 'max_depth' parameter can be thought of as how many questions the decision tree algorithm is allowed to ask about the data before making a prediction.
In addition, we will find your implementation is using ShuffleSplit() for an alternative form of cross-validation (see the 'cv_sets'variable). The ShuffleSplit() implementation below will create 10 ('n_splits') shuffled sets, and for each shuffle, 20% ('test_size') of the data will be used as the validation set.
# Import 'make_scorer', 'DecisionTreeRegressor', and 'GridSearchCV'from sklearn.tree import DecisionTreeRegressorfrom sklearn.metrics import make_scorerfrom sklearn.model_selection import GridSearchCVdef fit_model(X, y): """ Performs grid search over the 'max_depth' parameter for a decision tree regressor trained on the input data [X, y]. """ # Create cross-validation sets from the training data cv_sets = ShuffleSplit(n_splits = 10, test_size = 0.20, random_state = 0) # Create a decision tree regressor object regressor = DecisionTreeRegressor() # Create a dictionary for the parameter 'max_depth' with a range from 1 to 10 params = {'max_depth':[1,2,3,4,5,6,7,8,9,10]} # Transform 'performance_metric' into a scoring function using 'make_scorer' scoring_fnc = make_scorer(performance_metric) # Create the grid search cv object --> GridSearchCV() grid = GridSearchCV(estimator=regressor, param_grid=params, scoring=scoring_fnc, cv=cv_sets) # Fit the grid search object to the data to compute the optimal model grid = grid.fit(X, y) # Return the optimal model after fitting the data return grid.best_estimator_
Making Predictions
Once a model has been trained on a given set of data, it can now be used to make predictions on new sets of input data.
In the case of a decision tree regressor, the model has learned what the best questions to ask about the input data are, and can respond with a prediction for the target variable.
We can use these predictions to gain information about data where the value of the target variable is unknown, such as data the model was not trained on.
Optimal Model
The following code snippet finds the maximum depth that return the optimal model.
# Fit the training data to the model using grid searchreg = fit_model(X_train, y_train)# Produce the value for 'max_depth'print("Parameter 'max_depth' is {} for the optimal model.".format(reg.get_params()['max_depth']))
Predicting Selling Prices
Imagine that we were a real estate agent in the Boston area looking to use this model to help price homes owned by our clients that they wish to sell. We have collected the following information from three of our clients:
What price would we recommend each client sell his/her home at?
Do these prices seem reasonable given the values for the respective features?
To find out the answers of these questions we will execute the folowing code snippet and discuss its output.
# Produce a matrix for client dataclient_data = [[5, 17, 15], # Client 1 [4, 32, 22], # Client 2 [8, 3, 12]] # Client 3# Show predictionsfor i, price in enumerate(reg.predict(client_data)): print("Predicted selling price for Client {}'s home: ${:,.2f}".format(i+1, price))
From the statistical calculations done at the beginning of the project we found out the following information:
Minimum price: $105000.0
Maximum price: $1024800.0
Mean price: $454342.944
Median price $438900.0
Standard deviation of prices: $165340.277
Given these values, we can conclude:
Selling price for client 3 is near the million dollars, which is near the maximum of the dataset. This is a reasonable price because of its features (8 rooms, very low poverty level and low student-teacher ratio), the house may be in a wealthy neighborhood.
Selling price for client 2 is the lowest of the three and given its features is reasonable as it is near the minimum of the dataset.
For client 1, we can see that its features are intermediate between the latter 2, and therefore, its price is quite near the mean and median.
And our initial assumptions of the features are confirmed:
‘RM’, has a directy proportional relationship with the dependent variable ‘Prices’.
In contrast, ‘LSTAT’ and ‘PTRATIO’ have a inversely proportional relationship with the dependent variable ‘PRICES’.
Model’s Sensitivity
An optimal model is not necessarily a robust model. Sometimes, a model is either too complex or too simple to sufficiently generalize to new data.
Sometimes, a model could use a learning algorithm that is not appropriate for the structure of the data given.
Other times, the data itself could be too noisy or contain too few samples to allow a model to adequately capture the target variable — i.e., the model is underfitted.
The code cell below run the fit_model function ten times with different training and testing sets to see how the prediction for a specific client changes with respect to the data it's trained on.
vs.PredictTrials(features, prices, fit_model, client_data)
We obtained a range in prices of nearly 70k$, this is a quite large deviation as it represents approximately a 17% of the median value of house prices.
Model’s Applicability
Now, we use these results to discuss whether the constructed model should or should not be used in a real-world setting. Some questions that are worth to answer are:
How relevant today is data that was collected from 1978? How important is inflation?
Data collected from 1978 is not of much value in today’s world. Society and economics have changed so much and inflation has made a great impact on the prices.
Are the features present in the data sufficient to describe a home? Do you think factors like quality of apppliances in the home, square feet of the plot area, presence of pool or not etc should factor in?
The dataset considered is quite limited, there are a lot of features, like the size of the house in square feet, the presence of pool or not, and others, that are very relevant when considering a house price.
Is the model robust enough to make consistent predictions?
Given the high variance on the prince range, we can assure that it is not a robust model and, therefore, not appropiate for making predictions.
Would data collected in an urban city like Boston be applicable in a rural city?
Data collected from a big urban city like Boston would not be applicable in a rural city, as for equal value of feaures prices are much higher in the urban area.
Is it fair to judge the price of an individual home based on the characteristics of the entire neighborhood?
In general it is not fair to estimate or predict the price of an indivual home based on the features of the entire neighborhood. In the same neighborhood there can be huge differences in prices.
Throughout this article we made a machine learning regression project from end-to-end and we learned and obtained several insights about regression models and how they are developed.
This was the first of the machine learning projects that will be developed on this series. If you liked it, stay tuned for the next article! Which will be an introduction to the theory and concepts regarding to classification algorithms.
If you liked this post then you can take a look at my other posts on Data Science and Machine Learning here.
If you want to learn more about Machine Learning, Data Science and Artificial Intelligence follow me on Medium, and stay tuned for my next posts!
|
[
{
"code": null,
"e": 340,
"s": 172,
"text": "In this project, we will develop and evaluate the performance and the predictive power of a model trained and tested on data collected from houses in Boston’s suburbs."
},
{
"code": null,
"e": 458,
"s": 340,
"text": "Once we get a good fit, we will use this model to predict the monetary value of a house located at the Boston’s area."
},
{
"code": null,
"e": 587,
"s": 458,
"text": "A model like this would be very valuable for a real state agent who could make use of the information provided in a dayly basis."
},
{
"code": null,
"e": 667,
"s": 587,
"text": "You can find the complete project, documentation and dataset on my GitHub page:"
},
{
"code": null,
"e": 777,
"s": 667,
"text": "https://github.com/rromanss23/Machine_Leaning_Engineer_Udacity_NanoDegree/tree/master/projects/boston_housing"
},
{
"code": null,
"e": 1018,
"s": 777,
"text": "The dataset used in this project comes from the UCI Machine Learning Repository. This data was collected in 1978 and each of the 506 entries represents aggregate information about 14 features of homes from various suburbs located in Boston."
},
{
"code": null,
"e": 1061,
"s": 1018,
"text": "The features can be summarized as follows:"
},
{
"code": null,
"e": 1109,
"s": 1061,
"text": "CRIM: This is the per capita crime rate by town"
},
{
"code": null,
"e": 1197,
"s": 1109,
"text": "ZN: This is the proportion of residential land zoned for lots larger than 25,000 sq.ft."
},
{
"code": null,
"e": 1266,
"s": 1197,
"text": "INDUS: This is the proportion of non-retail business acres per town."
},
{
"code": null,
"e": 1369,
"s": 1266,
"text": "CHAS: This is the Charles River dummy variable (this is equal to 1 if tract bounds river; 0 otherwise)"
},
{
"code": null,
"e": 1437,
"s": 1369,
"text": "NOX: This is the nitric oxides concentration (parts per 10 million)"
},
{
"code": null,
"e": 1490,
"s": 1437,
"text": "RM: This is the average number of rooms per dwelling"
},
{
"code": null,
"e": 1562,
"s": 1490,
"text": "AGE: This is the proportion of owner-occupied units built prior to 1940"
},
{
"code": null,
"e": 1632,
"s": 1562,
"text": "DIS: This is the weighted distances to five Boston employment centers"
},
{
"code": null,
"e": 1691,
"s": 1632,
"text": "RAD: This is the index of accessibility to radial highways"
},
{
"code": null,
"e": 1749,
"s": 1691,
"text": "TAX: This is the full-value property-tax rate per $10,000"
},
{
"code": null,
"e": 1798,
"s": 1749,
"text": "PTRATIO: This is the pupil-teacher ratio by town"
},
{
"code": null,
"e": 1914,
"s": 1798,
"text": "B: This is calculated as 1000(Bk — 0.63)2, where Bk is the proportion of people of African American descent by town"
},
{
"code": null,
"e": 1975,
"s": 1914,
"text": "LSTAT: This is the percentage lower status of the population"
},
{
"code": null,
"e": 2040,
"s": 1975,
"text": "MEDV: This is the median value of owner-occupied homes in $1000s"
},
{
"code": null,
"e": 2113,
"s": 2040,
"text": "This is an overview of the original dataset, with its original features:"
},
{
"code": null,
"e": 2190,
"s": 2113,
"text": "For the purpose of the project the dataset has been preprocessed as follows:"
},
{
"code": null,
"e": 2314,
"s": 2190,
"text": "The essential features for the project are: ‘RM’, ‘LSTAT’, ‘PTRATIO’ and ‘MEDV’. The remaining features have been excluded."
},
{
"code": null,
"e": 2427,
"s": 2314,
"text": "16 data points with a ‘MEDV’ value of 50.0 have been removed. As they likely contain censored or missing values."
},
{
"code": null,
"e": 2557,
"s": 2427,
"text": "1 data point with a ‘RM’ value of 8.78 it is considered an outlier and has been removed for the optimal performance of the model."
},
{
"code": null,
"e": 2680,
"s": 2557,
"text": "As this data is out of date, the ‘MEDV’ value has been scaled multiplicatively to account for 35 years of markt inflation."
},
{
"code": null,
"e": 2890,
"s": 2680,
"text": "We’ll now open a python 3 Jupyter Notebook and execute the following code snippet to load the dataset and remove the non-essential features. Recieving a success message if the actions were correclty performed."
},
{
"code": null,
"e": 3108,
"s": 2890,
"text": "As our goal is to develop a model that has the capacity of predicting the value of houses, we will split the dataset into features and the target variable. And store them in features and prices variables, respectively"
},
{
"code": null,
"e": 3238,
"s": 3108,
"text": "The features ‘RM’, ‘LSTAT’ and ‘PTRATIO’, give us quantitative information abouth each datapoint. We will store them in features."
},
{
"code": null,
"e": 3336,
"s": 3238,
"text": "The target variable, ‘MEDV’, will be the variable we seek to predict. We will store it in prices."
},
{
"code": null,
"e": 3820,
"s": 3336,
"text": "# Import libraries necessary for this projectimport numpy as npimport pandas as pdfrom sklearn.model_selection import ShuffleSplit# Import supplementary visualizations code visuals.pyimport visuals as vs# Pretty display for notebooks%matplotlib inline# Load the Boston housing datasetdata = pd.read_csv('housing.csv')prices = data['MEDV']features = data.drop('MEDV', axis = 1) # Successprint(\"Boston housing dataset has {} data points with {} variables each.\".format(*data.shape))"
},
{
"code": null,
"e": 3940,
"s": 3820,
"text": "In the first section of the project, we will make an exploratory analysis of the dataset and provide some observations."
},
{
"code": null,
"e": 3961,
"s": 3940,
"text": "Calculate Statistics"
},
{
"code": null,
"e": 4585,
"s": 3961,
"text": "# Minimum price of the dataminimum_price = np.amin(prices)# Maximum price of the datamaximum_price = np.amax(prices)# Mean price of the datamean_price = np.mean(prices)# Median price of the datamedian_price = np.median(prices)# Standard deviation of prices of the datastd_price = np.std(prices)# Show the calculated statisticsprint(\"Statistics for Boston housing dataset:\\n\")print(\"Minimum price: ${}\".format(minimum_price)) print(\"Maximum price: ${}\".format(maximum_price))print(\"Mean price: ${}\".format(mean_price))print(\"Median price ${}\".format(median_price))print(\"Standard deviation of prices: ${}\".format(std_price))"
},
{
"code": null,
"e": 4789,
"s": 4585,
"text": "Data Science is the process of making some assumptions and hypothesis on the data, and testing them by performing some tasks. Initially we could make the following intuitive assumptions for each feature:"
},
{
"code": null,
"e": 5005,
"s": 4789,
"text": "Houses with more rooms (higher ‘RM’ value) will worth more. Usually houses with more rooms are bigger and can fit more people, so it is reasonable that they cost more money. They are directly proportional variables."
},
{
"code": null,
"e": 5283,
"s": 5005,
"text": "Neighborhoods with more lower class workers (higher ‘LSTAT’ value) will worth less. If the percentage of lower working class people is higher, it is likely that they have low purchasing power and therefore, they houses will cost less. They are inversely proportional variables."
},
{
"code": null,
"e": 5738,
"s": 5283,
"text": "Neighborhoods with more students to teachers ratio (higher ‘PTRATIO’ value) will be worth less. If the percentage of students to teachers ratio people is higher, it is likely that in the neighborhood there are less schools, this could be because there is less tax income which could be because in that neighborhood people earn less money. If people earn less money it is likely that their houses are worth less. They are inversely proportional variables."
},
{
"code": null,
"e": 5807,
"s": 5738,
"text": "We’ll find out if these assumptions are correct through the project."
},
{
"code": null,
"e": 5834,
"s": 5807,
"text": "Scatterplot and Histograms"
},
{
"code": null,
"e": 5990,
"s": 5834,
"text": "We will start by creating a scatterplot matrix that will allow us to visualize the pair-wise relationships and correlations between the different features."
},
{
"code": null,
"e": 6111,
"s": 5990,
"text": "It is also quite useful to have a quick overview of how the data is distributed and wheter it cointains or not outliers."
},
{
"code": null,
"e": 6257,
"s": 6111,
"text": "import matplotlib.pyplot as pltimport seaborn as sns%matplotlib inline# Calculate and show pairplotsns.pairplot(data, size=2.5)plt.tight_layout()"
},
{
"code": null,
"e": 6462,
"s": 6257,
"text": "We can spot a linear relationship between ‘RM’ and House prices ‘MEDV’. In addition, we can infer from the histogram that the ‘MEDV’ variable seems to be normally distributed but contain several outliers."
},
{
"code": null,
"e": 6481,
"s": 6462,
"text": "Correlation Matrix"
},
{
"code": null,
"e": 6596,
"s": 6481,
"text": "We are going to create now a correlation matrix to quantify and summarize the relationships between the variables."
},
{
"code": null,
"e": 6758,
"s": 6596,
"text": "This correlation matrix is closely related witn covariance matrix, in fact it is a rescaled version of the covariance matrix, computed from standardize features."
},
{
"code": null,
"e": 6877,
"s": 6758,
"text": "It is a square matrix (with the same number of columns and rows) that contains the Person’s r correlation coefficient."
},
{
"code": null,
"e": 7203,
"s": 6877,
"text": "# Calculate and show correlation matrixcm = np.corrcoef(data.values.T)sns.set(font_scale=1.5)hm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f', annot_kws={'size': 15}, yticklabels=cols, xticklabels=cols)"
},
{
"code": null,
"e": 7434,
"s": 7203,
"text": "To fit a regression model, the features of interest are the ones with a high correlation with the target variable ‘MEDV’. From the previous correlation matrix, we can see that this condition is achieved for our selected variables."
},
{
"code": null,
"e": 7734,
"s": 7434,
"text": "In this second section of the project, we will develop the tools and techniques necessary for a model to make a prediction. Being able to make accurate evaluations of each model’s performance through the use of these tools and techniques helps to reinforce greatly the confidence in the predictions."
},
{
"code": null,
"e": 7763,
"s": 7734,
"text": "Defining a Performace Metric"
},
{
"code": null,
"e": 8055,
"s": 7763,
"text": "It is difficult to measure the quality of a given model without quantifying its performance on the training and testing. This is typically done using some type of performance metric, whether it is through calculating some type of error, the goodness of fit, or some other useful measurement."
},
{
"code": null,
"e": 8327,
"s": 8055,
"text": "For this project, we will calculate the coefficient of determination, R2, to quantify the model’s performance. The coefficient of determination for a model is a useful statistic in regression analysis, as it often describes how “good” that model is at making predictions."
},
{
"code": null,
"e": 8481,
"s": 8327,
"text": "The values for R2 range from 0 to 1, which captures the percentage of squared correlation between the predicted and actual values of the target variable."
},
{
"code": null,
"e": 8585,
"s": 8481,
"text": "A model with an R2 of 0 is no better than a model that always predicts the mean of the target variable."
},
{
"code": null,
"e": 8657,
"s": 8585,
"text": "Whereas a model with an R2 of 1 perfectly predicts the target variable."
},
{
"code": null,
"e": 8785,
"s": 8657,
"text": "Any value between 0 and 1 indicates what percentage of the target variable, using this model, can be explained by the features."
},
{
"code": null,
"e": 8944,
"s": 8785,
"text": "A model can be given a negative R2 as well, which indicates that the model is arbitrarily worse than one that always predicts the mean of the target variable."
},
{
"code": null,
"e": 9274,
"s": 8944,
"text": "# Import 'r2_score'from sklearn.metrics import r2_scoredef performance_metric(y_true, y_predict): \"\"\" Calculates and returns the performance score between true (y_true) and predicted (y_predict) values based on the metric chosen. \"\"\" score = r2_score(y_true, y_predict) # Return the score return score"
},
{
"code": null,
"e": 9297,
"s": 9274,
"text": "Shuffle and Split Data"
},
{
"code": null,
"e": 9563,
"s": 9297,
"text": "For this section we will take the Boston housing dataset and split the data into training and testing subsets. Typically, the data is also shuffled into a random order when creating the training and testing subsets to remove any bias in the ordering of the dataset."
},
{
"code": null,
"e": 9868,
"s": 9563,
"text": "# Import 'train_test_split'from sklearn.model_selection import train_test_split# Shuffle and split the data into training and testing subsetsX_train, X_test, y_train, y_test = train_test_split(features, prices, test_size=0.2, random_state = 42)# Successprint(\"Training and testing split was successful.\")"
},
{
"code": null,
"e": 9889,
"s": 9868,
"text": "Training and Testing"
},
{
"code": null,
"e": 9906,
"s": 9889,
"text": "You may ask now:"
},
{
"code": null,
"e": 10023,
"s": 9906,
"text": "What is the benefit to splitting a dataset into some ratio of training and testing subsets for a learning algorithm?"
},
{
"code": null,
"e": 10193,
"s": 10023,
"text": "It is useful to evaluate our model once it is trained. We want to know if it has learned properly from a training split of the data. There can be 3 different situations:"
},
{
"code": null,
"e": 10361,
"s": 10193,
"text": "1) The model didn ́t learn well on the data, and can’t predict even the outcomes of the training set, this is called underfitting and it is caused because a high bias."
},
{
"code": null,
"e": 10552,
"s": 10361,
"text": "2) The model learn too well the training data, up to the point that it memorized it and is not able to generalize on new data, this is called overfitting, it is caused because high variance."
},
{
"code": null,
"e": 10691,
"s": 10552,
"text": "3) The model just had the right balance between bias and variance, it learned well and is able predict correctly the outcomes on new data."
},
{
"code": null,
"e": 10837,
"s": 10691,
"text": "In this third section of the project, we’ll take a look at several models’ learning and testing performances on various subsets of training data."
},
{
"code": null,
"e": 11013,
"s": 10837,
"text": "Additionally, we’ll investigate one particular algorithm with an increasing 'max_depth' parameter on the full training set to observe how model complexity affects performance."
},
{
"code": null,
"e": 11200,
"s": 11013,
"text": "Graphing the model's performance based on varying criteria can be beneficial in the analysis process, such as visualizing behavior that may not have been apparent from the results alone."
},
{
"code": null,
"e": 11216,
"s": 11200,
"text": "Learning Curves"
},
{
"code": null,
"e": 11449,
"s": 11216,
"text": "The following code cell produces four graphs for a decision tree model with different maximum depths. Each graph visualizes the learning curves of the model for both training and testing as the size of the training set is increased."
},
{
"code": null,
"e": 11675,
"s": 11449,
"text": "Note that the shaded region of a learning curve denotes the uncertainty of that curve (measured as the standard deviation). The model is scored on both the training and testing sets using R2, the coefficient of determination."
},
{
"code": null,
"e": 11785,
"s": 11675,
"text": "# Produce learning curves for varying training set sizes and maximum depthsvs.ModelLearning(features, prices)"
},
{
"code": null,
"e": 11803,
"s": 11785,
"text": "Learning the Data"
},
{
"code": null,
"e": 11865,
"s": 11803,
"text": "If we take a close look at the graph with the max depth of 3:"
},
{
"code": null,
"e": 11978,
"s": 11865,
"text": "As the number of training points increases, the training score decreases. In contrast, the test score increases."
},
{
"code": null,
"e": 12120,
"s": 11978,
"text": "As both scores (training and testing) tend to converge, from the 300 points treshold, having more training points will not benefit the model."
},
{
"code": null,
"e": 12299,
"s": 12120,
"text": "In general, with more columns for each observation, we’ll get more information and the model will be able to learn better from the dataset and therefore, make better predictions."
},
{
"code": null,
"e": 12317,
"s": 12299,
"text": "Complexity Curves"
},
{
"code": null,
"e": 12557,
"s": 12317,
"text": "The following code cell produces a graph for a decision tree model that has been trained and validated on the training data using different maximum depths. The graph produces two complexity curves — one for training and one for validation."
},
{
"code": null,
"e": 12782,
"s": 12557,
"text": "Similar to the learning curves, the shaded regions of both the complexity curves denote the uncertainty in those curves, and the model is scored on both the training and validation sets using the performance_metric function."
},
{
"code": null,
"e": 12895,
"s": 12782,
"text": "# Produce complexity curve for varying training set sizes and maximum depthsvs.ModelComplexity(X_train, y_train)"
},
{
"code": null,
"e": 12918,
"s": 12895,
"text": "Bias-Variance Tradeoff"
},
{
"code": null,
"e": 13002,
"s": 12918,
"text": "If we analize how the bias-variance vary with the maximun depth, we can infer that:"
},
{
"code": null,
"e": 13324,
"s": 13002,
"text": "With the maximun depth of one, the graphic shows that the model does not return good score in neither training nor testing data, which is a symptom of underfitting and so, high bias. To improve performance, we should increase model’s complexity, in this case increasing the max_depth hyperparameter to get better results."
},
{
"code": null,
"e": 13764,
"s": 13324,
"text": "With the maximun depth of ten, the graphic shows that the model learn perfectly well from training data (with a score close to one) and also returns poor results on test data, which is an indicator of overfitting, not being able to generalize well on new data. This is a problem of High Variance. To improve performance, we should decrease the model’s complexity, in this case decreasing the max_depth hyperparameter to get better results."
},
{
"code": null,
"e": 13789,
"s": 13764,
"text": "Best-Guess Optimal Model"
},
{
"code": null,
"e": 13933,
"s": 13789,
"text": "From the complexity curve, we can infer that the best maximum depth for the model is 4, as it is the one that yields the best validation score."
},
{
"code": null,
"e": 14067,
"s": 13933,
"text": "In addition, for more depth although the training score increases, validation score tends to decrease which is a sign of overfitting."
},
{
"code": null,
"e": 14222,
"s": 14067,
"text": "In this final section of the project, we will construct a model and make a prediction on the client’s feature set using an optimized model from fit_model."
},
{
"code": null,
"e": 14234,
"s": 14222,
"text": "Grid Search"
},
{
"code": null,
"e": 14461,
"s": 14234,
"text": "The grid search technique exhaustively generates candidates from a grid of parameter values specified with the param_grid parameter, which is a dictionary with the values of the hyperparameters to evaluate. One example can be:"
},
{
"code": null,
"e": 14599,
"s": 14461,
"text": "param_grid = [ {‘C’: [1, 10, 100, 1000], ‘kernel’: [‘linear’]}, {‘C’: [1, 10, 100, 1000], ‘gamma’: [0.001, 0.0001], ‘kernel’: [‘rbf’]}, ]"
},
{
"code": null,
"e": 14843,
"s": 14599,
"text": "In this example, two grids should be explored: one with a linear kernel an C values of [1,10,100,1000], and the second one with an RBF kernel, and the cross product of C values ranging in [1, 10, 100, 1000] and gamma values in [0.001, 0.0001]."
},
{
"code": null,
"e": 14974,
"s": 14843,
"text": "When fitting it on a dataset all the possible combinations of parameter values are evaluated and the best combination is retained."
},
{
"code": null,
"e": 15318,
"s": 14974,
"text": "K-fold cross-validation is a technique used for making sure that our model is well trained, without using the test set. It consist in splitting data into k partitions of equal size. For each partition i, we train the model on the remaining k-1 parameters and evaluate it on partition i. The final score is the average of the K scores obtained."
},
{
"code": null,
"e": 15643,
"s": 15318,
"text": "When evaluating different hyperparameters for estimators, there is still a risk of overfitting on the test set because the parameters can be tweaked until the estimator performs optimally. This way, knowledge about the test set can “leak” into the model and evaluation metrics no longer report on generalization performance."
},
{
"code": null,
"e": 15934,
"s": 15643,
"text": "To solve this problem, yet another part of the dataset can be held out as a so-called “validation set”: training proceeds on the training set, after which evaluation is done on the validation set, and when the experiment seems to be successful, final evaluation can be done on the test set."
},
{
"code": null,
"e": 16198,
"s": 15934,
"text": "However, by partitioning the available data into three sets (training, validating and testing sets), we drastically reduce the number of samples which can be used for learning the model, and the resulting model may not be sufficiently well trained (underfitting)."
},
{
"code": null,
"e": 16410,
"s": 16198,
"text": "By using k-fold validation we make sure that the model uses all the training data available for tunning the model, it can be computationally expensive but allows to train models even if little data is available."
},
{
"code": null,
"e": 16516,
"s": 16410,
"text": "The main purpose of k-fold validation is to get an unbiased estimate of model generalization on new data."
},
{
"code": null,
"e": 16532,
"s": 16516,
"text": "Fitting a Model"
},
{
"code": null,
"e": 16653,
"s": 16532,
"text": "The final implementation requires that we bring everything together and train a model using the decision tree algorithm."
},
{
"code": null,
"e": 16976,
"s": 16653,
"text": "To ensure that we are producing an optimized model, we will train the model using the grid search technique to optimize the 'max_depth'parameter for the decision tree. The 'max_depth' parameter can be thought of as how many questions the decision tree algorithm is allowed to ask about the data before making a prediction."
},
{
"code": null,
"e": 17290,
"s": 16976,
"text": "In addition, we will find your implementation is using ShuffleSplit() for an alternative form of cross-validation (see the 'cv_sets'variable). The ShuffleSplit() implementation below will create 10 ('n_splits') shuffled sets, and for each shuffle, 20% ('test_size') of the data will be used as the validation set."
},
{
"code": null,
"e": 18463,
"s": 17290,
"text": "# Import 'make_scorer', 'DecisionTreeRegressor', and 'GridSearchCV'from sklearn.tree import DecisionTreeRegressorfrom sklearn.metrics import make_scorerfrom sklearn.model_selection import GridSearchCVdef fit_model(X, y): \"\"\" Performs grid search over the 'max_depth' parameter for a decision tree regressor trained on the input data [X, y]. \"\"\" # Create cross-validation sets from the training data cv_sets = ShuffleSplit(n_splits = 10, test_size = 0.20, random_state = 0) # Create a decision tree regressor object regressor = DecisionTreeRegressor() # Create a dictionary for the parameter 'max_depth' with a range from 1 to 10 params = {'max_depth':[1,2,3,4,5,6,7,8,9,10]} # Transform 'performance_metric' into a scoring function using 'make_scorer' scoring_fnc = make_scorer(performance_metric) # Create the grid search cv object --> GridSearchCV() grid = GridSearchCV(estimator=regressor, param_grid=params, scoring=scoring_fnc, cv=cv_sets) # Fit the grid search object to the data to compute the optimal model grid = grid.fit(X, y) # Return the optimal model after fitting the data return grid.best_estimator_"
},
{
"code": null,
"e": 18482,
"s": 18463,
"text": "Making Predictions"
},
{
"code": null,
"e": 18602,
"s": 18482,
"text": "Once a model has been trained on a given set of data, it can now be used to make predictions on new sets of input data."
},
{
"code": null,
"e": 18782,
"s": 18602,
"text": "In the case of a decision tree regressor, the model has learned what the best questions to ask about the input data are, and can respond with a prediction for the target variable."
},
{
"code": null,
"e": 18936,
"s": 18782,
"text": "We can use these predictions to gain information about data where the value of the target variable is unknown, such as data the model was not trained on."
},
{
"code": null,
"e": 18950,
"s": 18936,
"text": "Optimal Model"
},
{
"code": null,
"e": 19032,
"s": 18950,
"text": "The following code snippet finds the maximum depth that return the optimal model."
},
{
"code": null,
"e": 19252,
"s": 19032,
"text": "# Fit the training data to the model using grid searchreg = fit_model(X_train, y_train)# Produce the value for 'max_depth'print(\"Parameter 'max_depth' is {} for the optimal model.\".format(reg.get_params()['max_depth']))"
},
{
"code": null,
"e": 19278,
"s": 19252,
"text": "Predicting Selling Prices"
},
{
"code": null,
"e": 19500,
"s": 19278,
"text": "Imagine that we were a real estate agent in the Boston area looking to use this model to help price homes owned by our clients that they wish to sell. We have collected the following information from three of our clients:"
},
{
"code": null,
"e": 19564,
"s": 19500,
"text": "What price would we recommend each client sell his/her home at?"
},
{
"code": null,
"e": 19642,
"s": 19564,
"text": "Do these prices seem reasonable given the values for the respective features?"
},
{
"code": null,
"e": 19751,
"s": 19642,
"text": "To find out the answers of these questions we will execute the folowing code snippet and discuss its output."
},
{
"code": null,
"e": 20056,
"s": 19751,
"text": "# Produce a matrix for client dataclient_data = [[5, 17, 15], # Client 1 [4, 32, 22], # Client 2 [8, 3, 12]] # Client 3# Show predictionsfor i, price in enumerate(reg.predict(client_data)): print(\"Predicted selling price for Client {}'s home: ${:,.2f}\".format(i+1, price))"
},
{
"code": null,
"e": 20167,
"s": 20056,
"text": "From the statistical calculations done at the beginning of the project we found out the following information:"
},
{
"code": null,
"e": 20192,
"s": 20167,
"text": "Minimum price: $105000.0"
},
{
"code": null,
"e": 20218,
"s": 20192,
"text": "Maximum price: $1024800.0"
},
{
"code": null,
"e": 20242,
"s": 20218,
"text": "Mean price: $454342.944"
},
{
"code": null,
"e": 20265,
"s": 20242,
"text": "Median price $438900.0"
},
{
"code": null,
"e": 20307,
"s": 20265,
"text": "Standard deviation of prices: $165340.277"
},
{
"code": null,
"e": 20344,
"s": 20307,
"text": "Given these values, we can conclude:"
},
{
"code": null,
"e": 20602,
"s": 20344,
"text": "Selling price for client 3 is near the million dollars, which is near the maximum of the dataset. This is a reasonable price because of its features (8 rooms, very low poverty level and low student-teacher ratio), the house may be in a wealthy neighborhood."
},
{
"code": null,
"e": 20735,
"s": 20602,
"text": "Selling price for client 2 is the lowest of the three and given its features is reasonable as it is near the minimum of the dataset."
},
{
"code": null,
"e": 20877,
"s": 20735,
"text": "For client 1, we can see that its features are intermediate between the latter 2, and therefore, its price is quite near the mean and median."
},
{
"code": null,
"e": 20936,
"s": 20877,
"text": "And our initial assumptions of the features are confirmed:"
},
{
"code": null,
"e": 21020,
"s": 20936,
"text": "‘RM’, has a directy proportional relationship with the dependent variable ‘Prices’."
},
{
"code": null,
"e": 21136,
"s": 21020,
"text": "In contrast, ‘LSTAT’ and ‘PTRATIO’ have a inversely proportional relationship with the dependent variable ‘PRICES’."
},
{
"code": null,
"e": 21156,
"s": 21136,
"text": "Model’s Sensitivity"
},
{
"code": null,
"e": 21303,
"s": 21156,
"text": "An optimal model is not necessarily a robust model. Sometimes, a model is either too complex or too simple to sufficiently generalize to new data."
},
{
"code": null,
"e": 21414,
"s": 21303,
"text": "Sometimes, a model could use a learning algorithm that is not appropriate for the structure of the data given."
},
{
"code": null,
"e": 21582,
"s": 21414,
"text": "Other times, the data itself could be too noisy or contain too few samples to allow a model to adequately capture the target variable — i.e., the model is underfitted."
},
{
"code": null,
"e": 21778,
"s": 21582,
"text": "The code cell below run the fit_model function ten times with different training and testing sets to see how the prediction for a specific client changes with respect to the data it's trained on."
},
{
"code": null,
"e": 21837,
"s": 21778,
"text": "vs.PredictTrials(features, prices, fit_model, client_data)"
},
{
"code": null,
"e": 21989,
"s": 21837,
"text": "We obtained a range in prices of nearly 70k$, this is a quite large deviation as it represents approximately a 17% of the median value of house prices."
},
{
"code": null,
"e": 22011,
"s": 21989,
"text": "Model’s Applicability"
},
{
"code": null,
"e": 22177,
"s": 22011,
"text": "Now, we use these results to discuss whether the constructed model should or should not be used in a real-world setting. Some questions that are worth to answer are:"
},
{
"code": null,
"e": 22262,
"s": 22177,
"text": "How relevant today is data that was collected from 1978? How important is inflation?"
},
{
"code": null,
"e": 22422,
"s": 22262,
"text": "Data collected from 1978 is not of much value in today’s world. Society and economics have changed so much and inflation has made a great impact on the prices."
},
{
"code": null,
"e": 22628,
"s": 22422,
"text": "Are the features present in the data sufficient to describe a home? Do you think factors like quality of apppliances in the home, square feet of the plot area, presence of pool or not etc should factor in?"
},
{
"code": null,
"e": 22837,
"s": 22628,
"text": "The dataset considered is quite limited, there are a lot of features, like the size of the house in square feet, the presence of pool or not, and others, that are very relevant when considering a house price."
},
{
"code": null,
"e": 22896,
"s": 22837,
"text": "Is the model robust enough to make consistent predictions?"
},
{
"code": null,
"e": 23040,
"s": 22896,
"text": "Given the high variance on the prince range, we can assure that it is not a robust model and, therefore, not appropiate for making predictions."
},
{
"code": null,
"e": 23121,
"s": 23040,
"text": "Would data collected in an urban city like Boston be applicable in a rural city?"
},
{
"code": null,
"e": 23283,
"s": 23121,
"text": "Data collected from a big urban city like Boston would not be applicable in a rural city, as for equal value of feaures prices are much higher in the urban area."
},
{
"code": null,
"e": 23392,
"s": 23283,
"text": "Is it fair to judge the price of an individual home based on the characteristics of the entire neighborhood?"
},
{
"code": null,
"e": 23587,
"s": 23392,
"text": "In general it is not fair to estimate or predict the price of an indivual home based on the features of the entire neighborhood. In the same neighborhood there can be huge differences in prices."
},
{
"code": null,
"e": 23770,
"s": 23587,
"text": "Throughout this article we made a machine learning regression project from end-to-end and we learned and obtained several insights about regression models and how they are developed."
},
{
"code": null,
"e": 24008,
"s": 23770,
"text": "This was the first of the machine learning projects that will be developed on this series. If you liked it, stay tuned for the next article! Which will be an introduction to the theory and concepts regarding to classification algorithms."
},
{
"code": null,
"e": 24117,
"s": 24008,
"text": "If you liked this post then you can take a look at my other posts on Data Science and Machine Learning here."
}
] |
Bell Numbers - Number of ways to Partition a Set in C++
|
A bell number is used to denote the number of ways a set of n elements can be partitioned into subsets that are not empty (i.e. have at least one element).
In this program, we are given a set of n elements and we have to find the number of ways to partition the set into non-empty subsets.
Input : 3
Output : 5
Explanation − let the set of three elements {1, 2, 3}.
The subsets are {{1} , {2} , {3}} ; {{1} , {2,3}} ; {{1 , 2} , {3}} ; {{2} , {1 , 3}} ; {1 , 2 , 3}.
Bell number: A bell number bell(n) gives the value of sum of s(n,k) for all values of k ranging from 1 to n. Here s(n,k) is the number of partitions of n elements into k subsets.
The formula would be −
bell(n)=∑k=0nS(n,k)
The function s(n,k) is recursively as −
s(n+1,k) = k*s(n,k) + s(n,k-1).
On adding (n+1)th element to k partitions, there are two possibilities −
It adds one to the k partitions of existing partitions i.e. s(n,k-1).
It adds one to the k partitions of existing partitions i.e. s(n,k-1).
Adding value to all sets of partition, i.e. k*s(n,k).
Adding value to all sets of partition, i.e. k*s(n,k).
First few Bell numbers are 1 , 1 , 2 ,5 ,15 , 52 , 205
For finding the Bells number, we have a few methods,
Simple method is to one by one compute s(n,k) for k = 1 to n and add sum of all values of the number.
Simple method is to one by one compute s(n,k) for k = 1 to n and add sum of all values of the number.
Using bell triangle is to use bell’s triangle as given below −
Using bell triangle is to use bell’s triangle as given below −
1
1 2
2 3 5
5 7 10 15
15 20 27 37 52
#include<iostream>
using namespace std;
int bellNumber(int n) {
int bell[n+1][n+1];
bell[0][0] = 1;
for (int i=1; i<=n; i++) {
bell[i][0] = bell[i-1][i-1];
for (int j=1; j<=i; j++)
bell[i][j] = bell[i-1][j-1] + bell[i][j-1];
}
return bell[n][0];
}
int main() {
for (int n=0; n<=5; n++)
cout<<"Bell Number "<<n<<" is "<< bellNumber(n)<<endl;
return 0;
}
|
[
{
"code": null,
"e": 1218,
"s": 1062,
"text": "A bell number is used to denote the number of ways a set of n elements can be partitioned into subsets that are not empty (i.e. have at least one element)."
},
{
"code": null,
"e": 1352,
"s": 1218,
"text": "In this program, we are given a set of n elements and we have to find the number of ways to partition the set into non-empty subsets."
},
{
"code": null,
"e": 1373,
"s": 1352,
"text": "Input : 3\nOutput : 5"
},
{
"code": null,
"e": 1428,
"s": 1373,
"text": "Explanation − let the set of three elements {1, 2, 3}."
},
{
"code": null,
"e": 1529,
"s": 1428,
"text": "The subsets are {{1} , {2} , {3}} ; {{1} , {2,3}} ; {{1 , 2} , {3}} ; {{2} , {1 , 3}} ; {1 , 2 , 3}."
},
{
"code": null,
"e": 1708,
"s": 1529,
"text": "Bell number: A bell number bell(n) gives the value of sum of s(n,k) for all values of k ranging from 1 to n. Here s(n,k) is the number of partitions of n elements into k subsets."
},
{
"code": null,
"e": 1731,
"s": 1708,
"text": "The formula would be −"
},
{
"code": null,
"e": 1751,
"s": 1731,
"text": "bell(n)=∑k=0nS(n,k)"
},
{
"code": null,
"e": 1791,
"s": 1751,
"text": "The function s(n,k) is recursively as −"
},
{
"code": null,
"e": 1823,
"s": 1791,
"text": "s(n+1,k) = k*s(n,k) + s(n,k-1)."
},
{
"code": null,
"e": 1896,
"s": 1823,
"text": "On adding (n+1)th element to k partitions, there are two possibilities −"
},
{
"code": null,
"e": 1966,
"s": 1896,
"text": "It adds one to the k partitions of existing partitions i.e. s(n,k-1)."
},
{
"code": null,
"e": 2036,
"s": 1966,
"text": "It adds one to the k partitions of existing partitions i.e. s(n,k-1)."
},
{
"code": null,
"e": 2090,
"s": 2036,
"text": "Adding value to all sets of partition, i.e. k*s(n,k)."
},
{
"code": null,
"e": 2144,
"s": 2090,
"text": "Adding value to all sets of partition, i.e. k*s(n,k)."
},
{
"code": null,
"e": 2199,
"s": 2144,
"text": "First few Bell numbers are 1 , 1 , 2 ,5 ,15 , 52 , 205"
},
{
"code": null,
"e": 2252,
"s": 2199,
"text": "For finding the Bells number, we have a few methods,"
},
{
"code": null,
"e": 2354,
"s": 2252,
"text": "Simple method is to one by one compute s(n,k) for k = 1 to n and add sum of all values of the number."
},
{
"code": null,
"e": 2456,
"s": 2354,
"text": "Simple method is to one by one compute s(n,k) for k = 1 to n and add sum of all values of the number."
},
{
"code": null,
"e": 2519,
"s": 2456,
"text": "Using bell triangle is to use bell’s triangle as given below −"
},
{
"code": null,
"e": 2582,
"s": 2519,
"text": "Using bell triangle is to use bell’s triangle as given below −"
},
{
"code": null,
"e": 2626,
"s": 2582,
"text": "1\n1 2\n2 3 5\n5 7 10 15\n15 20 27 37 52"
},
{
"code": null,
"e": 3021,
"s": 2626,
"text": "#include<iostream>\nusing namespace std;\nint bellNumber(int n) {\n int bell[n+1][n+1];\n bell[0][0] = 1;\n for (int i=1; i<=n; i++) {\n bell[i][0] = bell[i-1][i-1];\n for (int j=1; j<=i; j++)\n bell[i][j] = bell[i-1][j-1] + bell[i][j-1];\n }\n return bell[n][0];\n}\nint main() {\n for (int n=0; n<=5; n++)\n cout<<\"Bell Number \"<<n<<\" is \"<< bellNumber(n)<<endl;\n return 0;\n}"
}
] |
Java String toUpperCase() Method
|
❮ String Methods
Convert a string to upper case and lower case letters:
String txt = "Hello World";
System.out.println(txt.toUpperCase());
System.out.println(txt.toLowerCase());
Try it Yourself »
The toUpperCase() method converts a string to upper case letters.
Note: The toLowerCase() method converts a string to lower case letters.
public String toUpperCase()
None.
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 19,
"s": 0,
"text": "\n❮ String Methods\n"
},
{
"code": null,
"e": 74,
"s": 19,
"text": "Convert a string to upper case and lower case letters:"
},
{
"code": null,
"e": 180,
"s": 74,
"text": "String txt = \"Hello World\";\nSystem.out.println(txt.toUpperCase());\nSystem.out.println(txt.toLowerCase());"
},
{
"code": null,
"e": 200,
"s": 180,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 266,
"s": 200,
"text": "The toUpperCase() method converts a string to upper case letters."
},
{
"code": null,
"e": 338,
"s": 266,
"text": "Note: The toLowerCase() method converts a string to lower case letters."
},
{
"code": null,
"e": 367,
"s": 338,
"text": "public String toUpperCase()\n"
},
{
"code": null,
"e": 373,
"s": 367,
"text": "None."
},
{
"code": null,
"e": 406,
"s": 373,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 448,
"s": 406,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 555,
"s": 448,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 574,
"s": 555,
"text": "[email protected]"
}
] |
Find out the current working directory in C/C++
|
In this section, we will see how to get the current working directory using C or C++. We have defined some flags for the current operating system.
Live Demo
#ifdef WINDOWS
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrentDir getcwd
#endif
#include<iostream>
using namespace std;
std::string get_current_dir() {
char buff[FILENAME_MAX]; //create string buffer to hold path
GetCurrentDir( buff, FILENAME_MAX );
string current_working_dir(buff);
return current_working_dir;
}
main() {
cout << get_current_dir() << endl;
}
D:\C++ Programs\section 53
|
[
{
"code": null,
"e": 1209,
"s": 1062,
"text": "In this section, we will see how to get the current working directory using C or C++. We have defined some flags for the current operating system."
},
{
"code": null,
"e": 1220,
"s": 1209,
"text": " Live Demo"
},
{
"code": null,
"e": 1645,
"s": 1220,
"text": "#ifdef WINDOWS\n#include <direct.h>\n#define GetCurrentDir _getcwd\n#else\n#include <unistd.h>\n#define GetCurrentDir getcwd\n#endif\n\n#include<iostream>\nusing namespace std;\n\nstd::string get_current_dir() {\n char buff[FILENAME_MAX]; //create string buffer to hold path\n GetCurrentDir( buff, FILENAME_MAX );\n string current_working_dir(buff);\n return current_working_dir;\n}\n\nmain() {\n cout << get_current_dir() << endl;\n}"
},
{
"code": null,
"e": 1672,
"s": 1645,
"text": "D:\\C++ Programs\\section 53"
}
] |
Object detection and tracking in PyTorch | by Chris Fotache | Towards Data Science
|
In my previous story, I went over how to train an image classifier in PyTorch, with your own images, and then use it for image recognition. Now I’ll show you how to use a pre-trained classifier to detect multiple objects in an image, and later track them across a video.
What’s the difference between image classification (recognition) and object detection? In classification, you identify what’s the main object in the image and the entire image is classified by a single class. In detection, multiple objects are identified in the image, classified, and a location is also determined (as a bounding box).
There are several algorithms for object detection, with YOLO and SSD among the most popular. For this story, I’ll use YOLOv3. I won’t get into the technical details of how YOLO (You Only Look Once) works — you can read that here — but focus instead of how to use it in your own application.
So let’s jump into the code! The Yolo detection code here is based on Erik Lindernoren’s implementation of Joseph Redmon and Ali Farhadi’s paper. The code snippets below are from a Jupyter Notebook you can find in my Github repo. Before you run this, you’ll need to run the download_weights.sh script in the config folder to download the Yolo weights file. We start by importing the required modules:
from models import *from utils import *import os, sys, time, datetime, randomimport torchfrom torch.utils.data import DataLoaderfrom torchvision import datasets, transformsfrom torch.autograd import Variableimport matplotlib.pyplot as pltimport matplotlib.patches as patchesfrom PIL import Image
Then we load the pre-trained configuration and weights, as well as the class names of the COCO dataset on which the Darknet model was trained. As always in PyTorch, don’t forget to set the model in eval mode after loading.
config_path='config/yolov3.cfg'weights_path='config/yolov3.weights'class_path='config/coco.names'img_size=416conf_thres=0.8nms_thres=0.4# Load model and weightsmodel = Darknet(config_path, img_size=img_size)model.load_weights(weights_path)model.cuda()model.eval()classes = utils.load_classes(class_path)Tensor = torch.cuda.FloatTensor
There are also a few pre-defined values above: The image size (416px squares), confidence threshold and the non-maximum suppression threshold.
Below is the basic function that will return detections for a specified image. Note that it requires a Pillow image as input. Most of the code deals with resizing the image to a 416px square while maintaining its aspect ratio and padding the overflow. The actual detection is in the last 4 lines.
def detect_image(img): # scale and pad image ratio = min(img_size/img.size[0], img_size/img.size[1]) imw = round(img.size[0] * ratio) imh = round(img.size[1] * ratio) img_transforms=transforms.Compose([transforms.Resize((imh,imw)), transforms.Pad((max(int((imh-imw)/2),0), max(int((imw-imh)/2),0), max(int((imh-imw)/2),0), max(int((imw-imh)/2),0)), (128,128,128)), transforms.ToTensor(), ]) # convert image to Tensor image_tensor = img_transforms(img).float() image_tensor = image_tensor.unsqueeze_(0) input_img = Variable(image_tensor.type(Tensor)) # run inference on the model and get detections with torch.no_grad(): detections = model(input_img) detections = utils.non_max_suppression(detections, 80, conf_thres, nms_thres) return detections[0]
Finally, let’s put it together by loading an image, getting the detections, and then displaying it with the bounding boxes around detected objects. Again, most of the code here deals with scaling and padding the image, as well as getting different colors for each detected class.
# load image and get detectionsimg_path = "images/blueangels.jpg"prev_time = time.time()img = Image.open(img_path)detections = detect_image(img)inference_time = datetime.timedelta(seconds=time.time() - prev_time)print ('Inference Time: %s' % (inference_time))# Get bounding-box colorscmap = plt.get_cmap('tab20b')colors = [cmap(i) for i in np.linspace(0, 1, 20)]img = np.array(img)plt.figure()fig, ax = plt.subplots(1, figsize=(12,9))ax.imshow(img)pad_x = max(img.shape[0] - img.shape[1], 0) * (img_size / max(img.shape))pad_y = max(img.shape[1] - img.shape[0], 0) * (img_size / max(img.shape))unpad_h = img_size - pad_yunpad_w = img_size - pad_xif detections is not None: unique_labels = detections[:, -1].cpu().unique() n_cls_preds = len(unique_labels) bbox_colors = random.sample(colors, n_cls_preds) # browse detections and draw bounding boxes for x1, y1, x2, y2, conf, cls_conf, cls_pred in detections: box_h = ((y2 - y1) / unpad_h) * img.shape[0] box_w = ((x2 - x1) / unpad_w) * img.shape[1] y1 = ((y1 - pad_y // 2) / unpad_h) * img.shape[0] x1 = ((x1 - pad_x // 2) / unpad_w) * img.shape[1] color = bbox_colors[int(np.where( unique_labels == int(cls_pred))[0])] bbox = patches.Rectangle((x1, y1), box_w, box_h, linewidth=2, edgecolor=color, facecolor='none') ax.add_patch(bbox) plt.text(x1, y1, s=classes[int(cls_pred)], color='white', verticalalignment='top', bbox={'color': color, 'pad': 0})plt.axis('off')# save imageplt.savefig(img_path.replace(".jpg", "-det.jpg"), bbox_inches='tight', pad_inches=0.0)plt.show()
You can put together these code fragments to run the code, or download the notebook from my Github. Here are a few examples of object detection in images:
So now you know how to detect different objects in an image. The visualization might be pretty cool when you do it frame by frame in a video and you see those tracking boxes moving around. But if there are multiple objects in those video frames, how do you know if an object in one frame is the same as one in a previous frame? That’s called object tracking, and uses multiple detections to identify a specific object over time.
There are several algorithms that do it, and I decided to use SORT, which is very easy to use and pretty fast. SORT (Simple Online and Realtime Tracking) is a 2017 paper by Alex Bewley, Zongyuan Ge, Lionel Ott, Fabio Ramos, Ben Upcroft which proposes using a Kalman filter to predict the track of previously identified objects, and match them with new detections. Author Alex Bewley also wrote a versatile Python implementation that I’m gonna use for this story. Make sure you download the Sort version from my Github repo since I had to make a few small changes to integrate it in my project.
Now on to the code, the first 3 code segments will be the same as in the single image detection, since they deal with getting the YOLO detections on a single frame. The difference comes in the final part where for each detection we call the Update function of the Sort object in order to get references to the objects in the image. So instead of the regular detections from the previous example (which include the coordinates of the bounding box and a class prediction), we’ll get tracked objects which, besides the parameters above, also include an object ID. Then we display the almost the same way, but adding that ID and using different colors so you can easily see the objects across the video frames.
I also used OpenCV to read the video and display the video frames. Note that the Jupyter notebook is quite slow in processing the video. You can use it for testing and simple visualizations, but I also provided a standalone Python script that will read the source video, and output a copy with the tracked objects. Playing an OpenCV video in a notebook is not easy, so you can keep this code for other experiments.
videopath = 'video/intersection.mp4'%pylab inline import cv2from IPython.display import clear_outputcmap = plt.get_cmap('tab20b')colors = [cmap(i)[:3] for i in np.linspace(0, 1, 20)]# initialize Sort object and video capturefrom sort import *vid = cv2.VideoCapture(videopath)mot_tracker = Sort()#while(True):for ii in range(40): ret, frame = vid.read() frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) pilimg = Image.fromarray(frame) detections = detect_image(pilimg) img = np.array(pilimg) pad_x = max(img.shape[0] - img.shape[1], 0) * (img_size / max(img.shape)) pad_y = max(img.shape[1] - img.shape[0], 0) * (img_size / max(img.shape)) unpad_h = img_size - pad_y unpad_w = img_size - pad_x if detections is not None: tracked_objects = mot_tracker.update(detections.cpu()) unique_labels = detections[:, -1].cpu().unique() n_cls_preds = len(unique_labels) for x1, y1, x2, y2, obj_id, cls_pred in tracked_objects: box_h = int(((y2 - y1) / unpad_h) * img.shape[0]) box_w = int(((x2 - x1) / unpad_w) * img.shape[1]) y1 = int(((y1 - pad_y // 2) / unpad_h) * img.shape[0]) x1 = int(((x1 - pad_x // 2) / unpad_w) * img.shape[1]) color = colors[int(obj_id) % len(colors)] color = [i * 255 for i in color] cls = classes[int(cls_pred)] cv2.rectangle(frame, (x1, y1), (x1+box_w, y1+box_h), color, 4) cv2.rectangle(frame, (x1, y1-35), (x1+len(cls)*19+60, y1), color, -1) cv2.putText(frame, cls + "-" + str(int(obj_id)), (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 3) fig=figure(figsize=(12, 8)) title("Video Stream") imshow(frame) show() clear_output(wait=True)
After you play with the notebook, you can use the regular Python script both for live processing (you can take input from a camera) and to save videos. Here’s a sample of videos I generated with this program.
And that’s it, you can now try on your own to detect multiple objects in images and to track those objects across video frames.
If you want to detect and track your own objects on a custom image dataset, you can read my next story about Training Yolo for Object Detection on a Custom Dataset.
Chris Fotache is an AI researcher with CYNET.ai based in New Jersey. He covers topics related to artificial intelligence in our life, Python programming, machine learning, computer vision, natural language processing and more.
|
[
{
"code": null,
"e": 443,
"s": 172,
"text": "In my previous story, I went over how to train an image classifier in PyTorch, with your own images, and then use it for image recognition. Now I’ll show you how to use a pre-trained classifier to detect multiple objects in an image, and later track them across a video."
},
{
"code": null,
"e": 779,
"s": 443,
"text": "What’s the difference between image classification (recognition) and object detection? In classification, you identify what’s the main object in the image and the entire image is classified by a single class. In detection, multiple objects are identified in the image, classified, and a location is also determined (as a bounding box)."
},
{
"code": null,
"e": 1070,
"s": 779,
"text": "There are several algorithms for object detection, with YOLO and SSD among the most popular. For this story, I’ll use YOLOv3. I won’t get into the technical details of how YOLO (You Only Look Once) works — you can read that here — but focus instead of how to use it in your own application."
},
{
"code": null,
"e": 1471,
"s": 1070,
"text": "So let’s jump into the code! The Yolo detection code here is based on Erik Lindernoren’s implementation of Joseph Redmon and Ali Farhadi’s paper. The code snippets below are from a Jupyter Notebook you can find in my Github repo. Before you run this, you’ll need to run the download_weights.sh script in the config folder to download the Yolo weights file. We start by importing the required modules:"
},
{
"code": null,
"e": 1767,
"s": 1471,
"text": "from models import *from utils import *import os, sys, time, datetime, randomimport torchfrom torch.utils.data import DataLoaderfrom torchvision import datasets, transformsfrom torch.autograd import Variableimport matplotlib.pyplot as pltimport matplotlib.patches as patchesfrom PIL import Image"
},
{
"code": null,
"e": 1990,
"s": 1767,
"text": "Then we load the pre-trained configuration and weights, as well as the class names of the COCO dataset on which the Darknet model was trained. As always in PyTorch, don’t forget to set the model in eval mode after loading."
},
{
"code": null,
"e": 2325,
"s": 1990,
"text": "config_path='config/yolov3.cfg'weights_path='config/yolov3.weights'class_path='config/coco.names'img_size=416conf_thres=0.8nms_thres=0.4# Load model and weightsmodel = Darknet(config_path, img_size=img_size)model.load_weights(weights_path)model.cuda()model.eval()classes = utils.load_classes(class_path)Tensor = torch.cuda.FloatTensor"
},
{
"code": null,
"e": 2468,
"s": 2325,
"text": "There are also a few pre-defined values above: The image size (416px squares), confidence threshold and the non-maximum suppression threshold."
},
{
"code": null,
"e": 2765,
"s": 2468,
"text": "Below is the basic function that will return detections for a specified image. Note that it requires a Pillow image as input. Most of the code deals with resizing the image to a 416px square while maintaining its aspect ratio and padding the overflow. The actual detection is in the last 4 lines."
},
{
"code": null,
"e": 3639,
"s": 2765,
"text": "def detect_image(img): # scale and pad image ratio = min(img_size/img.size[0], img_size/img.size[1]) imw = round(img.size[0] * ratio) imh = round(img.size[1] * ratio) img_transforms=transforms.Compose([transforms.Resize((imh,imw)), transforms.Pad((max(int((imh-imw)/2),0), max(int((imw-imh)/2),0), max(int((imh-imw)/2),0), max(int((imw-imh)/2),0)), (128,128,128)), transforms.ToTensor(), ]) # convert image to Tensor image_tensor = img_transforms(img).float() image_tensor = image_tensor.unsqueeze_(0) input_img = Variable(image_tensor.type(Tensor)) # run inference on the model and get detections with torch.no_grad(): detections = model(input_img) detections = utils.non_max_suppression(detections, 80, conf_thres, nms_thres) return detections[0]"
},
{
"code": null,
"e": 3919,
"s": 3639,
"text": "Finally, let’s put it together by loading an image, getting the detections, and then displaying it with the bounding boxes around detected objects. Again, most of the code here deals with scaling and padding the image, as well as getting different colors for each detected class."
},
{
"code": null,
"e": 5594,
"s": 3919,
"text": "# load image and get detectionsimg_path = \"images/blueangels.jpg\"prev_time = time.time()img = Image.open(img_path)detections = detect_image(img)inference_time = datetime.timedelta(seconds=time.time() - prev_time)print ('Inference Time: %s' % (inference_time))# Get bounding-box colorscmap = plt.get_cmap('tab20b')colors = [cmap(i) for i in np.linspace(0, 1, 20)]img = np.array(img)plt.figure()fig, ax = plt.subplots(1, figsize=(12,9))ax.imshow(img)pad_x = max(img.shape[0] - img.shape[1], 0) * (img_size / max(img.shape))pad_y = max(img.shape[1] - img.shape[0], 0) * (img_size / max(img.shape))unpad_h = img_size - pad_yunpad_w = img_size - pad_xif detections is not None: unique_labels = detections[:, -1].cpu().unique() n_cls_preds = len(unique_labels) bbox_colors = random.sample(colors, n_cls_preds) # browse detections and draw bounding boxes for x1, y1, x2, y2, conf, cls_conf, cls_pred in detections: box_h = ((y2 - y1) / unpad_h) * img.shape[0] box_w = ((x2 - x1) / unpad_w) * img.shape[1] y1 = ((y1 - pad_y // 2) / unpad_h) * img.shape[0] x1 = ((x1 - pad_x // 2) / unpad_w) * img.shape[1] color = bbox_colors[int(np.where( unique_labels == int(cls_pred))[0])] bbox = patches.Rectangle((x1, y1), box_w, box_h, linewidth=2, edgecolor=color, facecolor='none') ax.add_patch(bbox) plt.text(x1, y1, s=classes[int(cls_pred)], color='white', verticalalignment='top', bbox={'color': color, 'pad': 0})plt.axis('off')# save imageplt.savefig(img_path.replace(\".jpg\", \"-det.jpg\"), bbox_inches='tight', pad_inches=0.0)plt.show()"
},
{
"code": null,
"e": 5749,
"s": 5594,
"text": "You can put together these code fragments to run the code, or download the notebook from my Github. Here are a few examples of object detection in images:"
},
{
"code": null,
"e": 6178,
"s": 5749,
"text": "So now you know how to detect different objects in an image. The visualization might be pretty cool when you do it frame by frame in a video and you see those tracking boxes moving around. But if there are multiple objects in those video frames, how do you know if an object in one frame is the same as one in a previous frame? That’s called object tracking, and uses multiple detections to identify a specific object over time."
},
{
"code": null,
"e": 6772,
"s": 6178,
"text": "There are several algorithms that do it, and I decided to use SORT, which is very easy to use and pretty fast. SORT (Simple Online and Realtime Tracking) is a 2017 paper by Alex Bewley, Zongyuan Ge, Lionel Ott, Fabio Ramos, Ben Upcroft which proposes using a Kalman filter to predict the track of previously identified objects, and match them with new detections. Author Alex Bewley also wrote a versatile Python implementation that I’m gonna use for this story. Make sure you download the Sort version from my Github repo since I had to make a few small changes to integrate it in my project."
},
{
"code": null,
"e": 7479,
"s": 6772,
"text": "Now on to the code, the first 3 code segments will be the same as in the single image detection, since they deal with getting the YOLO detections on a single frame. The difference comes in the final part where for each detection we call the Update function of the Sort object in order to get references to the objects in the image. So instead of the regular detections from the previous example (which include the coordinates of the bounding box and a class prediction), we’ll get tracked objects which, besides the parameters above, also include an object ID. Then we display the almost the same way, but adding that ID and using different colors so you can easily see the objects across the video frames."
},
{
"code": null,
"e": 7894,
"s": 7479,
"text": "I also used OpenCV to read the video and display the video frames. Note that the Jupyter notebook is quite slow in processing the video. You can use it for testing and simple visualizations, but I also provided a standalone Python script that will read the source video, and output a copy with the tracked objects. Playing an OpenCV video in a notebook is not easy, so you can keep this code for other experiments."
},
{
"code": null,
"e": 9762,
"s": 7894,
"text": "videopath = 'video/intersection.mp4'%pylab inline import cv2from IPython.display import clear_outputcmap = plt.get_cmap('tab20b')colors = [cmap(i)[:3] for i in np.linspace(0, 1, 20)]# initialize Sort object and video capturefrom sort import *vid = cv2.VideoCapture(videopath)mot_tracker = Sort()#while(True):for ii in range(40): ret, frame = vid.read() frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) pilimg = Image.fromarray(frame) detections = detect_image(pilimg) img = np.array(pilimg) pad_x = max(img.shape[0] - img.shape[1], 0) * (img_size / max(img.shape)) pad_y = max(img.shape[1] - img.shape[0], 0) * (img_size / max(img.shape)) unpad_h = img_size - pad_y unpad_w = img_size - pad_x if detections is not None: tracked_objects = mot_tracker.update(detections.cpu()) unique_labels = detections[:, -1].cpu().unique() n_cls_preds = len(unique_labels) for x1, y1, x2, y2, obj_id, cls_pred in tracked_objects: box_h = int(((y2 - y1) / unpad_h) * img.shape[0]) box_w = int(((x2 - x1) / unpad_w) * img.shape[1]) y1 = int(((y1 - pad_y // 2) / unpad_h) * img.shape[0]) x1 = int(((x1 - pad_x // 2) / unpad_w) * img.shape[1]) color = colors[int(obj_id) % len(colors)] color = [i * 255 for i in color] cls = classes[int(cls_pred)] cv2.rectangle(frame, (x1, y1), (x1+box_w, y1+box_h), color, 4) cv2.rectangle(frame, (x1, y1-35), (x1+len(cls)*19+60, y1), color, -1) cv2.putText(frame, cls + \"-\" + str(int(obj_id)), (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 3) fig=figure(figsize=(12, 8)) title(\"Video Stream\") imshow(frame) show() clear_output(wait=True)"
},
{
"code": null,
"e": 9971,
"s": 9762,
"text": "After you play with the notebook, you can use the regular Python script both for live processing (you can take input from a camera) and to save videos. Here’s a sample of videos I generated with this program."
},
{
"code": null,
"e": 10099,
"s": 9971,
"text": "And that’s it, you can now try on your own to detect multiple objects in images and to track those objects across video frames."
},
{
"code": null,
"e": 10264,
"s": 10099,
"text": "If you want to detect and track your own objects on a custom image dataset, you can read my next story about Training Yolo for Object Detection on a Custom Dataset."
}
] |
How to exclude particular class name from CSS selector ?
|
30 Jul, 2021
In CSS, to exclude a particular class, we can use the pseudo-class :not selector also known as negation pseudo-class or not selector. This selector is used to set the style to every element that is not the specified by given selector. Since it is used to prevent a specific items from list of selected items.
Syntax:
:not(element) {
// CSS Property
}
Example:
<!DOCTYPE html> <html> <head> <title> How to exclude particular class name from CSS selector ? </title> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width, initial-scale=1"> <link rel="stylesheet" href= "https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <style> h1, h3 { text-align: center; } .todo { color: gray; } /* Style to all li element except todo class name */ li:not(.todo) { text-decoration: line-through; color: green; } </style> </head> <body> <div class="container"> <h1 class="text-success"> GeeksforGeeks </h1> <hr/> <h3>To-Do List:</h3> <ul class="list-group"> <li class="list-group-item"> Complete The Online Course </li> <li class="list-group-item"> Goto Kolkata On Wednesday </li> <li class="todo list-group-item"> Write Another Article For GeeksforGeeks </li> <li class="todo list-group-item"> Complete Java Assignment </li> <li class="todo list-group-item"> Buy Books On JavaScript </li> </ul> </div> </body> </html>
Output:
CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
Picked
CSS
Technical Scripter
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": "\n30 Jul, 2021"
},
{
"code": null,
"e": 337,
"s": 28,
"text": "In CSS, to exclude a particular class, we can use the pseudo-class :not selector also known as negation pseudo-class or not selector. This selector is used to set the style to every element that is not the specified by given selector. Since it is used to prevent a specific items from list of selected items."
},
{
"code": null,
"e": 345,
"s": 337,
"text": "Syntax:"
},
{
"code": null,
"e": 383,
"s": 345,
"text": ":not(element) {\n // CSS Property\n}"
},
{
"code": null,
"e": 392,
"s": 383,
"text": "Example:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title> How to exclude particular class name from CSS selector ? </title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href= \"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <style> h1, h3 { text-align: center; } .todo { color: gray; } /* Style to all li element except todo class name */ li:not(.todo) { text-decoration: line-through; color: green; } </style> </head> <body> <div class=\"container\"> <h1 class=\"text-success\"> GeeksforGeeks </h1> <hr/> <h3>To-Do List:</h3> <ul class=\"list-group\"> <li class=\"list-group-item\"> Complete The Online Course </li> <li class=\"list-group-item\"> Goto Kolkata On Wednesday </li> <li class=\"todo list-group-item\"> Write Another Article For GeeksforGeeks </li> <li class=\"todo list-group-item\"> Complete Java Assignment </li> <li class=\"todo list-group-item\"> Buy Books On JavaScript </li> </ul> </div> </body> </html>",
"e": 1895,
"s": 392,
"text": null
},
{
"code": null,
"e": 1903,
"s": 1895,
"text": "Output:"
},
{
"code": null,
"e": 2089,
"s": 1903,
"text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples."
},
{
"code": null,
"e": 2096,
"s": 2089,
"text": "Picked"
},
{
"code": null,
"e": 2100,
"s": 2096,
"text": "CSS"
},
{
"code": null,
"e": 2119,
"s": 2100,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2136,
"s": 2119,
"text": "Web Technologies"
},
{
"code": null,
"e": 2163,
"s": 2136,
"text": "Web technologies Questions"
}
] |
Taking a Snapshot from System Camera using OpenCV in Java
|
13 Jan, 2021
The OpenCV library in Java contains a class named ‘VideoCapture’ which provides a method called read (which is predefined) to scan pictures from the webcam. Mat object is passed as a parameter in the read method.
Concept:
The ‘javax.swing’ PackageThe Abstract Window Toolkit (AWT)
The ‘javax.swing’ Package
The Abstract Window Toolkit (AWT)
Let’s discuss them briefly before diving into the procedure and implementation part.
The ‘javax.swing’ package is used as this package provides classes for Java Swing API such as JButton, JTextArea, JCheckbox, JMenu, etc. Concepts of java involved here are Swing class and abstract windows toolkit as mentioned below:javax.swing.ImageIcon : The class ImageIcon is an implementation of the Icon interface that paints Icons from Images.javax.swing.Jframe : The class JFrame is a type of container which inherits the java. JFrame works like the main window where components like labels, buttons, text fields are added to create a GUI.javax.swing.JLabel : The class JLabel is used to display a short string or an image icon.x
javax.swing.ImageIcon : The class ImageIcon is an implementation of the Icon interface that paints Icons from Images.
javax.swing.Jframe : The class JFrame is a type of container which inherits the java. JFrame works like the main window where components like labels, buttons, text fields are added to create a GUI.
javax.swing.JLabel : The class JLabel is used to display a short string or an image icon.x
The Abstract Window Toolkit (AWT) is a Java package used for creating graphical user interfaces. AWT features include:A set of native interface components.A robust event-handling model.Graphics and imaging tools, including shape, color, and font classes.Layout managers, for flexible window layouts that do not depend on a particular window size or screen resolution.Data transfer classes, for cut and paste through the native platform clipboard.
A set of native interface components.
A robust event-handling model.
Graphics and imaging tools, including shape, color, and font classes.
Layout managers, for flexible window layouts that do not depend on a particular window size or screen resolution.
Data transfer classes, for cut and paste through the native platform clipboard.
Procedure: Steps to draw geometric shapes on images in OpenCV
Create a project and add an OpenCV library.Create PackageCreate a ClassCreate a folder named “images” to save the captured images.Writing the desired java program to a java file.
Create a project and add an OpenCV library.
Create Package
Create a Class
Create a folder named “images” to save the captured images.
Writing the desired java program to a java file.
Implementation: Writing the following java program in the java file to take a snapshot from the system camera.
Example
Java
// Java Program to take a Snapshot from System Camera// using OpenCV // Importing openCV modulespackage com.opencvcamera;// importing swing and awt classesimport java.awt.Dimension;import java.awt.EventQueue;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;// Importing date class of sql packageimport java.sql.Date;import java.text.DateFormat;import java.text.SimpleDateFormat;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import org.opencv.core.Core;import org.opencv.core.Mat;import org.opencv.core.MatOfByte;import org.opencv.imgcodecs.Imgcodecs;// Importing VideoCapture class// This class is responsible for taking screenshotimport org.opencv.videoio.VideoCapture; // Class - Swing Classpublic class Camera extends JFrame { // Camera screen private JLabel cameraScreen; // Button for image capture private JButton btnCapture; // Start camera private VideoCapture capture; // Store image as 2D matrix private Mat image; private boolean clicked = false; public Camera() { // Designing UI setLayout(null); cameraScreen = new JLabel(); cameraScreen.setBounds(0, 0, 640, 480); add(cameraScreen); btnCapture = new JButton("capture"); btnCapture.setBounds(300, 480, 80, 40); add(btnCapture); btnCapture.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { clicked = true; } }); setSize(new Dimension(640, 560)); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } // Creating a camera public void startCamera() { capture = new VideoCapture(0); image = new Mat(); byte[] imageData; ImageIcon icon; while (true) { // read image to matrix capture.read(image); // convert matrix to byte final MatOfByte buf = new MatOfByte(); Imgcodecs.imencode(".jpg", image, buf); imageData = buf.toArray(); // Add to JLabel icon = new ImageIcon(imageData); cameraScreen.setIcon(icon); // Capture and save to file if (clicked) { // prompt for enter image name String name = JOptionPane.showInputDialog( this, "Enter image name"); if (name == null) { name = new SimpleDateFormat( "yyyy-mm-dd-hh-mm-ss") .format(new Date( HEIGHT, WIDTH, getX())); } // Write to file Imgcodecs.imwrite("images/" + name + ".jpg", image); clicked = false; } } } // Main driver method public static void main(String[] args) { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); EventQueue.invokeLater(new Runnable() { // Overriding existing run() method @Override public void run() { final Camera camera = new Camera(); // Start camera in thread new Thread(new Runnable() { @Override public void run() { camera.startCamera(); } }).start(); } }); }}
Output:
After a successful compilation of the program, the execution is as follows as the webcam will open up where you click on the “Capture” button and the rest image will be named. Now, click on the “OK” button to save the image. The output image will be saved in the folder which was created earlier.
Java-OpenCV
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Jan, 2021"
},
{
"code": null,
"e": 241,
"s": 28,
"text": "The OpenCV library in Java contains a class named ‘VideoCapture’ which provides a method called read (which is predefined) to scan pictures from the webcam. Mat object is passed as a parameter in the read method."
},
{
"code": null,
"e": 251,
"s": 241,
"text": "Concept: "
},
{
"code": null,
"e": 310,
"s": 251,
"text": "The ‘javax.swing’ PackageThe Abstract Window Toolkit (AWT)"
},
{
"code": null,
"e": 336,
"s": 310,
"text": "The ‘javax.swing’ Package"
},
{
"code": null,
"e": 370,
"s": 336,
"text": "The Abstract Window Toolkit (AWT)"
},
{
"code": null,
"e": 455,
"s": 370,
"text": "Let’s discuss them briefly before diving into the procedure and implementation part."
},
{
"code": null,
"e": 1092,
"s": 455,
"text": "The ‘javax.swing’ package is used as this package provides classes for Java Swing API such as JButton, JTextArea, JCheckbox, JMenu, etc. Concepts of java involved here are Swing class and abstract windows toolkit as mentioned below:javax.swing.ImageIcon : The class ImageIcon is an implementation of the Icon interface that paints Icons from Images.javax.swing.Jframe : The class JFrame is a type of container which inherits the java. JFrame works like the main window where components like labels, buttons, text fields are added to create a GUI.javax.swing.JLabel : The class JLabel is used to display a short string or an image icon.x"
},
{
"code": null,
"e": 1210,
"s": 1092,
"text": "javax.swing.ImageIcon : The class ImageIcon is an implementation of the Icon interface that paints Icons from Images."
},
{
"code": null,
"e": 1408,
"s": 1210,
"text": "javax.swing.Jframe : The class JFrame is a type of container which inherits the java. JFrame works like the main window where components like labels, buttons, text fields are added to create a GUI."
},
{
"code": null,
"e": 1499,
"s": 1408,
"text": "javax.swing.JLabel : The class JLabel is used to display a short string or an image icon.x"
},
{
"code": null,
"e": 1946,
"s": 1499,
"text": "The Abstract Window Toolkit (AWT) is a Java package used for creating graphical user interfaces. AWT features include:A set of native interface components.A robust event-handling model.Graphics and imaging tools, including shape, color, and font classes.Layout managers, for flexible window layouts that do not depend on a particular window size or screen resolution.Data transfer classes, for cut and paste through the native platform clipboard."
},
{
"code": null,
"e": 1984,
"s": 1946,
"text": "A set of native interface components."
},
{
"code": null,
"e": 2015,
"s": 1984,
"text": "A robust event-handling model."
},
{
"code": null,
"e": 2085,
"s": 2015,
"text": "Graphics and imaging tools, including shape, color, and font classes."
},
{
"code": null,
"e": 2199,
"s": 2085,
"text": "Layout managers, for flexible window layouts that do not depend on a particular window size or screen resolution."
},
{
"code": null,
"e": 2279,
"s": 2199,
"text": "Data transfer classes, for cut and paste through the native platform clipboard."
},
{
"code": null,
"e": 2341,
"s": 2279,
"text": "Procedure: Steps to draw geometric shapes on images in OpenCV"
},
{
"code": null,
"e": 2520,
"s": 2341,
"text": "Create a project and add an OpenCV library.Create PackageCreate a ClassCreate a folder named “images” to save the captured images.Writing the desired java program to a java file."
},
{
"code": null,
"e": 2564,
"s": 2520,
"text": "Create a project and add an OpenCV library."
},
{
"code": null,
"e": 2579,
"s": 2564,
"text": "Create Package"
},
{
"code": null,
"e": 2594,
"s": 2579,
"text": "Create a Class"
},
{
"code": null,
"e": 2654,
"s": 2594,
"text": "Create a folder named “images” to save the captured images."
},
{
"code": null,
"e": 2703,
"s": 2654,
"text": "Writing the desired java program to a java file."
},
{
"code": null,
"e": 2814,
"s": 2703,
"text": "Implementation: Writing the following java program in the java file to take a snapshot from the system camera."
},
{
"code": null,
"e": 2822,
"s": 2814,
"text": "Example"
},
{
"code": null,
"e": 2827,
"s": 2822,
"text": "Java"
},
{
"code": "// Java Program to take a Snapshot from System Camera// using OpenCV // Importing openCV modulespackage com.opencvcamera;// importing swing and awt classesimport java.awt.Dimension;import java.awt.EventQueue;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;// Importing date class of sql packageimport java.sql.Date;import java.text.DateFormat;import java.text.SimpleDateFormat;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import org.opencv.core.Core;import org.opencv.core.Mat;import org.opencv.core.MatOfByte;import org.opencv.imgcodecs.Imgcodecs;// Importing VideoCapture class// This class is responsible for taking screenshotimport org.opencv.videoio.VideoCapture; // Class - Swing Classpublic class Camera extends JFrame { // Camera screen private JLabel cameraScreen; // Button for image capture private JButton btnCapture; // Start camera private VideoCapture capture; // Store image as 2D matrix private Mat image; private boolean clicked = false; public Camera() { // Designing UI setLayout(null); cameraScreen = new JLabel(); cameraScreen.setBounds(0, 0, 640, 480); add(cameraScreen); btnCapture = new JButton(\"capture\"); btnCapture.setBounds(300, 480, 80, 40); add(btnCapture); btnCapture.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { clicked = true; } }); setSize(new Dimension(640, 560)); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } // Creating a camera public void startCamera() { capture = new VideoCapture(0); image = new Mat(); byte[] imageData; ImageIcon icon; while (true) { // read image to matrix capture.read(image); // convert matrix to byte final MatOfByte buf = new MatOfByte(); Imgcodecs.imencode(\".jpg\", image, buf); imageData = buf.toArray(); // Add to JLabel icon = new ImageIcon(imageData); cameraScreen.setIcon(icon); // Capture and save to file if (clicked) { // prompt for enter image name String name = JOptionPane.showInputDialog( this, \"Enter image name\"); if (name == null) { name = new SimpleDateFormat( \"yyyy-mm-dd-hh-mm-ss\") .format(new Date( HEIGHT, WIDTH, getX())); } // Write to file Imgcodecs.imwrite(\"images/\" + name + \".jpg\", image); clicked = false; } } } // Main driver method public static void main(String[] args) { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); EventQueue.invokeLater(new Runnable() { // Overriding existing run() method @Override public void run() { final Camera camera = new Camera(); // Start camera in thread new Thread(new Runnable() { @Override public void run() { camera.startCamera(); } }).start(); } }); }}",
"e": 6442,
"s": 2827,
"text": null
},
{
"code": null,
"e": 6450,
"s": 6442,
"text": "Output:"
},
{
"code": null,
"e": 6747,
"s": 6450,
"text": "After a successful compilation of the program, the execution is as follows as the webcam will open up where you click on the “Capture” button and the rest image will be named. Now, click on the “OK” button to save the image. The output image will be saved in the folder which was created earlier."
},
{
"code": null,
"e": 6759,
"s": 6747,
"text": "Java-OpenCV"
},
{
"code": null,
"e": 6766,
"s": 6759,
"text": "Picked"
},
{
"code": null,
"e": 6790,
"s": 6766,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 6795,
"s": 6790,
"text": "Java"
},
{
"code": null,
"e": 6809,
"s": 6795,
"text": "Java Programs"
},
{
"code": null,
"e": 6828,
"s": 6809,
"text": "Technical Scripter"
},
{
"code": null,
"e": 6833,
"s": 6828,
"text": "Java"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.