title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Python model of Covid-19 epidemic | Towards Data Science
|
How long will the epidemic last? How long do we need to keep social distancing? What if it is lifted? What if nothing was done?
One month ago, with contributions from doctors and data scientists, I created a model in Python to forecast the evolution of the Coronavirus epidemic in the metropolitan region of São Paulo and answer the questions above. While some were skeptical about the scenarios forecasted, I am currently shocked by how accurate the predictions have proven to be. The model has since been improved and open-sourced, and that is why I want to share with you how to use it, for any region you want to model.
When predictions were made, we expected there was some delay in confirmation of deaths, but that was not part of the model, yet. By then, we still knew about deaths from hospital reports, before they reached official statistics. So we expected the official counts to follow a curve like projected, shifted to the right by a few days.
The model was saying: I don't know what will happen in the long term, but for the next 2–3 weeks any scenario looks the same. No surprise we got right those 3 weeks if we did model correctly the disease. For the last 10 days, the inclination of the curve seems to be in the middle between the two scenarios considered.
The current model can deal with uncertainties about how the epidemic behaves, and "learns" from observations. Nobody is still sure exactly how contagious the disease is, or how people are behaving. The shadowed areas around projections in the graphs represent that uncertainty. When learning, the model identifies which combinations of hypotheses can explain reality, and which can not.
Still, we can start asking questions.
What if... there was a lockdown as of April 20th? (In São Paulo, stay-at-home is just a recommendation, and some data points to 40% of people not staying at home each day)
What if... nobody was using masks outside hospitals? Assuming they are about 40% effective if the sick wears them, and another 20% effective for the susceptible person, we would expect the spread of the virus to be worse if nobody was using them.
What is... the effect of social distancing? Let's check how the model expects the reproductive number (the number of people infected by each infected person) has behaved in Rio de Janeiro:
As expected, social distancing is very effective in reducing transmission. People who can't afford to stay at home, or don't even have a home to stay, can't isolate as effectively, as shown by the higher reproductive number.
But wait... why does the reproductive number have a higher starting point (R0) for the very low income? While other social classes start at 3.4, very low income begins at 4.0. This non-obvious behavior has a simple explanation: more people living together increases the chances of transmission at home, as the model correctly pointed.
Finally, Why... death counts accelerated so badly in mid-April, to then seem to drop, and then increase again? (This happened in São Paulo, and the explanation explains similar patterns in New York and other places)
Taking into account the delays in diagnosis and death confirmations, and how they change during time can explain non-obvious behaviors seen in official numbers. We expect that real deaths were higher than the official counts for many weeks until mid-April, due to lack of testing capacity. When testing catches up, things seem out of control for a few days.
For simulations about Brasil, you can find detailed historical data here. For world data, this Kaggle dataset can be a good start.
(In case you are not interested in Python modeling, you can jump to the graphs near the end, with projections for New York State)
When modeling São Paulo, one thing was clear for me from the start: social inequality matters. So I knew the model would be more complex than most models built until then. Using a time-series model would be helpless because countries ahead in the curve had very different societies. Building a compartmental model (SIR, SEIR and the likes), predefining states, and specifying differential equations for transitions, would be unfeasible due to the many important aspects to be modeled. An individual-based simulation was the go.
By using Simpy, it was easy to model arbitrary characteristics of the disease or about people's behavior. No need to know in advance what are the state transitions, not even how many possible states, just the state variables and the logic governing them.
In short, we create a population randomly, following characteristics of its subsegments, we designate a few seed infections, and we let individuals interact. All rules about how people interact, what will be the outcome for a sick person, how long each phase of the disease will take, all that can be programmed explicitly. One event can trigger parallel logic, running independently from each other, with independent randomness. It is like writing asynchronous code, that will run synchronously in simulation time.
Python is great, but when modeling a disease that can have effects on small fractions of the population, a lot of individuals need to be simulated. 10.000 individuals and memory consumption and CPU usage sky-rocketed. To solve that, each individual became an object in Cython, with little changes in the code, but enabling the simulation of 1.000.000 individuals with about 1GB RAM consumed and huge performance gains.
Disease evolution and transmission were then modeled in detail. Most parameters came from these two sources:
Estimates of the severity of coronavirus disease 2019: a model-based analysis
Epidemic Calculator — Contains estimates for several disease parameters.
The current source code of the model can be found here:
github.com
First, let's clone the repo, set up a virtual environment, and install the simulation code. (Installation will download requirements, compile Cython code and install everything as a package)
git clone https://github.com/ArroyoAndre/covidsimulation.gitcd covidsimulation/python3 -m venv venv. venv/bin/activate./setup.sh
Then, start Jupyter:
jupyter notebook
In a notebook, let's start with the imports:
Now, we will define a population. To model a region for real, you can define several populations (e.g. city and country-side, rich and poor, general population and essential service workers, ...)
We will simulate New York State. Numbers are provided for didactic purposes. (for example, I invented age distributions and home sizes)
We also need to specify the Interventions. We will use two kinds of interventions. SocialDistanceChange will account for school closures and social gatherings banning on March 10th, and stay-at-home orders on March 22nd. On April 10th and 12th, we will use the DiagnosisDelayChange intervention to reduce the delay on testing results, to account for a spike in deaths reported a few days later.
Wait... Why did I start diagnosis_delay at 10 days, to then reduce it to 5 days? It seems reasonable that the time for exams to be collected, sent to a lab, tested, results to come back, and deaths to be reported, can sum to around 5 days. According to Wikipedia, NY had around 700 deaths each day between April 10th and April 15th. On the 16th and 17th, there were 3500 more deaths than the previous average, to then return to the previous trend. So we can hypothesize there were about 5-days-worth deaths pending confirmation, that finally got confirmed. Therefore the previous delay of 10 days.
Now, we need to wrap all of that into a region's Parameters object.
Because with few infectees the time for the epidemic to gain traction can vary a lot, we align all simulations in D0, defined as the date in which the number of people infected reaches a threshold. We will define D0 as March 10th (because not much happened before that). Since we don't know how many people were infected by then, we set that as a RandomParameter with a uniform distribution between 10k and 200k.
We have added two uncertain parameters to the model. A few others, like the rate of transmission from an infected person, are also not known or might vary between regions, and default to RandomParameter. That's why we need to calibrate our model.
Often, the variable with fewer biases that we can use for calibration is the official death count. There might be some systemic underreporting and systemic delay, but that is better than other biases. We are already assuming the average delay for confirmation of cases begins at 10 days and changes to 5 days in mid-April, so we should be fine.
We will create a score function that will give lower loss values to simulations that better match the official death count at certain dates:
We will then start the calibration process. First, we will try several combinations of values for the model's internal parameters, using small populations of 100k individuals. (I use a virtual instance with 32 CPU cores for this. On a laptop, it might take a while...) We will do 1000 trials and keep the 100 best (p=0.1).
Second, we will try those 100 best on populations of 1 million individuals, to reduce noise when separating the best ones. We will then keep the 16 best.
Those random_states are our posterior of the joint distribution of all uncertain parameters in the model. With appropriate naming, it is possible to use the posterior from one region as a prior for another region, to get a refined posterior.
After all the time spent calibrating you probably want to save the random_states found so far. (How to do it using pickle is beyond the purpose of this post, but you are encouraged to google it)
We are now in shape to do a real simulation, and predict something in the future. We will take the 16 best random_states found, and apply each of them twice, on a population of 2 million individuals. Again, we will keep the 16 simulations (0.5 of them) that best fitted our calibration data.
Let’s plot the confirmed deaths, to do the first check:
And total deaths, without the confirmation delay, in log scale:
We can also satisfy our curiosity and see which values were learned for our RandomParameters.
It is possible to see the implemented metrics:
What about the fatality rates? There is not a metric for that, but we can create one.
Although this was quick modeling (sorry if you are running a laptop) for didactic purposes, the results are impressively realistic.
Good priors are gold. In many cases, avoiding UniformParameters, even if replacing them by a different distribution, can make the difference between a model that can just learn the past, and one that can really forecast non-obvious behaviors about the future. Remember:
sh*t in → sh*t out
Performing many simulations (starting from 10k random_states at least), and performing them with large populations (2 million for presentation purposes) can also substantially increase accuracy.
Adding different types of metrics to the scoring function can make more output variables accurate.
There are many more features that were not explored here, like studying the effect of hygiene measures or of using masks. It is also possible to simulate different social distancing scenarios, including intermittent distancing, and to take into account the health system’s capacity.
I hope you can make good use of the model, either to inform people about forecasts and scenarios in your region, or just to learn about how it was built and how to do cooler stuff in Python.
You are invited to collaborate to improve the model, to model new regions, to add new features, and to share your results.
Note from the editors: Towards Data Science is a Medium publication primarily based on the study of data science and machine learning. We are not health professionals or epidemiologists, and the opinions of this article should not be interpreted as professional advice. To learn more about the coronavirus pandemic, you can click here.
Some rights reserved
|
[
{
"code": null,
"e": 299,
"s": 171,
"text": "How long will the epidemic last? How long do we need to keep social distancing? What if it is lifted? What if nothing was done?"
},
{
"code": null,
"e": 796,
"s": 299,
"text": "One month ago, with contributions from doctors and data scientists, I created a model in Python to forecast the evolution of the Coronavirus epidemic in the metropolitan region of São Paulo and answer the questions above. While some were skeptical about the scenarios forecasted, I am currently shocked by how accurate the predictions have proven to be. The model has since been improved and open-sourced, and that is why I want to share with you how to use it, for any region you want to model."
},
{
"code": null,
"e": 1130,
"s": 796,
"text": "When predictions were made, we expected there was some delay in confirmation of deaths, but that was not part of the model, yet. By then, we still knew about deaths from hospital reports, before they reached official statistics. So we expected the official counts to follow a curve like projected, shifted to the right by a few days."
},
{
"code": null,
"e": 1449,
"s": 1130,
"text": "The model was saying: I don't know what will happen in the long term, but for the next 2–3 weeks any scenario looks the same. No surprise we got right those 3 weeks if we did model correctly the disease. For the last 10 days, the inclination of the curve seems to be in the middle between the two scenarios considered."
},
{
"code": null,
"e": 1836,
"s": 1449,
"text": "The current model can deal with uncertainties about how the epidemic behaves, and \"learns\" from observations. Nobody is still sure exactly how contagious the disease is, or how people are behaving. The shadowed areas around projections in the graphs represent that uncertainty. When learning, the model identifies which combinations of hypotheses can explain reality, and which can not."
},
{
"code": null,
"e": 1874,
"s": 1836,
"text": "Still, we can start asking questions."
},
{
"code": null,
"e": 2047,
"s": 1874,
"text": "What if... there was a lockdown as of April 20th? (In São Paulo, stay-at-home is just a recommendation, and some data points to 40% of people not staying at home each day)"
},
{
"code": null,
"e": 2294,
"s": 2047,
"text": "What if... nobody was using masks outside hospitals? Assuming they are about 40% effective if the sick wears them, and another 20% effective for the susceptible person, we would expect the spread of the virus to be worse if nobody was using them."
},
{
"code": null,
"e": 2483,
"s": 2294,
"text": "What is... the effect of social distancing? Let's check how the model expects the reproductive number (the number of people infected by each infected person) has behaved in Rio de Janeiro:"
},
{
"code": null,
"e": 2708,
"s": 2483,
"text": "As expected, social distancing is very effective in reducing transmission. People who can't afford to stay at home, or don't even have a home to stay, can't isolate as effectively, as shown by the higher reproductive number."
},
{
"code": null,
"e": 3043,
"s": 2708,
"text": "But wait... why does the reproductive number have a higher starting point (R0) for the very low income? While other social classes start at 3.4, very low income begins at 4.0. This non-obvious behavior has a simple explanation: more people living together increases the chances of transmission at home, as the model correctly pointed."
},
{
"code": null,
"e": 3260,
"s": 3043,
"text": "Finally, Why... death counts accelerated so badly in mid-April, to then seem to drop, and then increase again? (This happened in São Paulo, and the explanation explains similar patterns in New York and other places)"
},
{
"code": null,
"e": 3618,
"s": 3260,
"text": "Taking into account the delays in diagnosis and death confirmations, and how they change during time can explain non-obvious behaviors seen in official numbers. We expect that real deaths were higher than the official counts for many weeks until mid-April, due to lack of testing capacity. When testing catches up, things seem out of control for a few days."
},
{
"code": null,
"e": 3749,
"s": 3618,
"text": "For simulations about Brasil, you can find detailed historical data here. For world data, this Kaggle dataset can be a good start."
},
{
"code": null,
"e": 3879,
"s": 3749,
"text": "(In case you are not interested in Python modeling, you can jump to the graphs near the end, with projections for New York State)"
},
{
"code": null,
"e": 4408,
"s": 3879,
"text": "When modeling São Paulo, one thing was clear for me from the start: social inequality matters. So I knew the model would be more complex than most models built until then. Using a time-series model would be helpless because countries ahead in the curve had very different societies. Building a compartmental model (SIR, SEIR and the likes), predefining states, and specifying differential equations for transitions, would be unfeasible due to the many important aspects to be modeled. An individual-based simulation was the go."
},
{
"code": null,
"e": 4663,
"s": 4408,
"text": "By using Simpy, it was easy to model arbitrary characteristics of the disease or about people's behavior. No need to know in advance what are the state transitions, not even how many possible states, just the state variables and the logic governing them."
},
{
"code": null,
"e": 5179,
"s": 4663,
"text": "In short, we create a population randomly, following characteristics of its subsegments, we designate a few seed infections, and we let individuals interact. All rules about how people interact, what will be the outcome for a sick person, how long each phase of the disease will take, all that can be programmed explicitly. One event can trigger parallel logic, running independently from each other, with independent randomness. It is like writing asynchronous code, that will run synchronously in simulation time."
},
{
"code": null,
"e": 5598,
"s": 5179,
"text": "Python is great, but when modeling a disease that can have effects on small fractions of the population, a lot of individuals need to be simulated. 10.000 individuals and memory consumption and CPU usage sky-rocketed. To solve that, each individual became an object in Cython, with little changes in the code, but enabling the simulation of 1.000.000 individuals with about 1GB RAM consumed and huge performance gains."
},
{
"code": null,
"e": 5707,
"s": 5598,
"text": "Disease evolution and transmission were then modeled in detail. Most parameters came from these two sources:"
},
{
"code": null,
"e": 5785,
"s": 5707,
"text": "Estimates of the severity of coronavirus disease 2019: a model-based analysis"
},
{
"code": null,
"e": 5858,
"s": 5785,
"text": "Epidemic Calculator — Contains estimates for several disease parameters."
},
{
"code": null,
"e": 5914,
"s": 5858,
"text": "The current source code of the model can be found here:"
},
{
"code": null,
"e": 5925,
"s": 5914,
"text": "github.com"
},
{
"code": null,
"e": 6116,
"s": 5925,
"text": "First, let's clone the repo, set up a virtual environment, and install the simulation code. (Installation will download requirements, compile Cython code and install everything as a package)"
},
{
"code": null,
"e": 6245,
"s": 6116,
"text": "git clone https://github.com/ArroyoAndre/covidsimulation.gitcd covidsimulation/python3 -m venv venv. venv/bin/activate./setup.sh"
},
{
"code": null,
"e": 6266,
"s": 6245,
"text": "Then, start Jupyter:"
},
{
"code": null,
"e": 6283,
"s": 6266,
"text": "jupyter notebook"
},
{
"code": null,
"e": 6328,
"s": 6283,
"text": "In a notebook, let's start with the imports:"
},
{
"code": null,
"e": 6524,
"s": 6328,
"text": "Now, we will define a population. To model a region for real, you can define several populations (e.g. city and country-side, rich and poor, general population and essential service workers, ...)"
},
{
"code": null,
"e": 6660,
"s": 6524,
"text": "We will simulate New York State. Numbers are provided for didactic purposes. (for example, I invented age distributions and home sizes)"
},
{
"code": null,
"e": 7055,
"s": 6660,
"text": "We also need to specify the Interventions. We will use two kinds of interventions. SocialDistanceChange will account for school closures and social gatherings banning on March 10th, and stay-at-home orders on March 22nd. On April 10th and 12th, we will use the DiagnosisDelayChange intervention to reduce the delay on testing results, to account for a spike in deaths reported a few days later."
},
{
"code": null,
"e": 7653,
"s": 7055,
"text": "Wait... Why did I start diagnosis_delay at 10 days, to then reduce it to 5 days? It seems reasonable that the time for exams to be collected, sent to a lab, tested, results to come back, and deaths to be reported, can sum to around 5 days. According to Wikipedia, NY had around 700 deaths each day between April 10th and April 15th. On the 16th and 17th, there were 3500 more deaths than the previous average, to then return to the previous trend. So we can hypothesize there were about 5-days-worth deaths pending confirmation, that finally got confirmed. Therefore the previous delay of 10 days."
},
{
"code": null,
"e": 7721,
"s": 7653,
"text": "Now, we need to wrap all of that into a region's Parameters object."
},
{
"code": null,
"e": 8134,
"s": 7721,
"text": "Because with few infectees the time for the epidemic to gain traction can vary a lot, we align all simulations in D0, defined as the date in which the number of people infected reaches a threshold. We will define D0 as March 10th (because not much happened before that). Since we don't know how many people were infected by then, we set that as a RandomParameter with a uniform distribution between 10k and 200k."
},
{
"code": null,
"e": 8381,
"s": 8134,
"text": "We have added two uncertain parameters to the model. A few others, like the rate of transmission from an infected person, are also not known or might vary between regions, and default to RandomParameter. That's why we need to calibrate our model."
},
{
"code": null,
"e": 8726,
"s": 8381,
"text": "Often, the variable with fewer biases that we can use for calibration is the official death count. There might be some systemic underreporting and systemic delay, but that is better than other biases. We are already assuming the average delay for confirmation of cases begins at 10 days and changes to 5 days in mid-April, so we should be fine."
},
{
"code": null,
"e": 8867,
"s": 8726,
"text": "We will create a score function that will give lower loss values to simulations that better match the official death count at certain dates:"
},
{
"code": null,
"e": 9190,
"s": 8867,
"text": "We will then start the calibration process. First, we will try several combinations of values for the model's internal parameters, using small populations of 100k individuals. (I use a virtual instance with 32 CPU cores for this. On a laptop, it might take a while...) We will do 1000 trials and keep the 100 best (p=0.1)."
},
{
"code": null,
"e": 9344,
"s": 9190,
"text": "Second, we will try those 100 best on populations of 1 million individuals, to reduce noise when separating the best ones. We will then keep the 16 best."
},
{
"code": null,
"e": 9586,
"s": 9344,
"text": "Those random_states are our posterior of the joint distribution of all uncertain parameters in the model. With appropriate naming, it is possible to use the posterior from one region as a prior for another region, to get a refined posterior."
},
{
"code": null,
"e": 9781,
"s": 9586,
"text": "After all the time spent calibrating you probably want to save the random_states found so far. (How to do it using pickle is beyond the purpose of this post, but you are encouraged to google it)"
},
{
"code": null,
"e": 10073,
"s": 9781,
"text": "We are now in shape to do a real simulation, and predict something in the future. We will take the 16 best random_states found, and apply each of them twice, on a population of 2 million individuals. Again, we will keep the 16 simulations (0.5 of them) that best fitted our calibration data."
},
{
"code": null,
"e": 10129,
"s": 10073,
"text": "Let’s plot the confirmed deaths, to do the first check:"
},
{
"code": null,
"e": 10193,
"s": 10129,
"text": "And total deaths, without the confirmation delay, in log scale:"
},
{
"code": null,
"e": 10287,
"s": 10193,
"text": "We can also satisfy our curiosity and see which values were learned for our RandomParameters."
},
{
"code": null,
"e": 10334,
"s": 10287,
"text": "It is possible to see the implemented metrics:"
},
{
"code": null,
"e": 10420,
"s": 10334,
"text": "What about the fatality rates? There is not a metric for that, but we can create one."
},
{
"code": null,
"e": 10552,
"s": 10420,
"text": "Although this was quick modeling (sorry if you are running a laptop) for didactic purposes, the results are impressively realistic."
},
{
"code": null,
"e": 10822,
"s": 10552,
"text": "Good priors are gold. In many cases, avoiding UniformParameters, even if replacing them by a different distribution, can make the difference between a model that can just learn the past, and one that can really forecast non-obvious behaviors about the future. Remember:"
},
{
"code": null,
"e": 10841,
"s": 10822,
"text": "sh*t in → sh*t out"
},
{
"code": null,
"e": 11036,
"s": 10841,
"text": "Performing many simulations (starting from 10k random_states at least), and performing them with large populations (2 million for presentation purposes) can also substantially increase accuracy."
},
{
"code": null,
"e": 11135,
"s": 11036,
"text": "Adding different types of metrics to the scoring function can make more output variables accurate."
},
{
"code": null,
"e": 11418,
"s": 11135,
"text": "There are many more features that were not explored here, like studying the effect of hygiene measures or of using masks. It is also possible to simulate different social distancing scenarios, including intermittent distancing, and to take into account the health system’s capacity."
},
{
"code": null,
"e": 11609,
"s": 11418,
"text": "I hope you can make good use of the model, either to inform people about forecasts and scenarios in your region, or just to learn about how it was built and how to do cooler stuff in Python."
},
{
"code": null,
"e": 11732,
"s": 11609,
"text": "You are invited to collaborate to improve the model, to model new regions, to add new features, and to share your results."
},
{
"code": null,
"e": 12068,
"s": 11732,
"text": "Note from the editors: Towards Data Science is a Medium publication primarily based on the study of data science and machine learning. We are not health professionals or epidemiologists, and the opinions of this article should not be interpreted as professional advice. To learn more about the coronavirus pandemic, you can click here."
}
] |
How to update a range of records in MySQL?
|
To update a range of records in MySQL, you can use BETWEEN. Let us first create a table:
mysql> create table DemoTable
(
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
Name varchar(20),
Age int
);
Query OK, 0 rows affected (0.53 sec)
Following is the query to insert some records in the table using insert command:
mysql> insert into DemoTable(Name,Age) values('Larry',23);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(Name,Age) values('Sam',24);
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable(Name,Age) values('Chris',21);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(Name,Age) values('Carol',25);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(Name,Age) values('David',22);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(Name,Age) values('Robert',26);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(Name,Age) values('John',20);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(Name,Age) values('Mike',27);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(Name,Age) values('Johnny',28);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(Name,Age) values('James',23);
Query OK, 1 row affected (0.23 sec)
Following is the query to display records from the table using select command:
mysql> select *from DemoTable;
This will produce the following output:
+----+--------+------+
| Id | Name | Age |
+----+--------+------+
| 1 | Larry | 23 |
| 2 | Sam | 24 |
| 3 | Chris | 21 |
| 4 | Carol | 25 |
| 5 | David | 22 |
| 6 | Robert | 26 |
| 7 | John | 20 |
| 8 | Mike | 27 |
| 9 | Johnny | 28 |
| 10 | James | 23 |
+----+--------+------+
10 rows in set (0.00 sec)
Following is the query to update a range of records in MySQL. We are updating the Name to ‘Bob’ for Ids in the range 5 to 10:
mysql> update DemoTable set Name='Bob', Age=23 where Id between 5 AND 10;
Query OK, 6 rows affected (0.25 sec)
Rows matched: 6 Changed: 6 Warnings: 0
Let us now display all records including updated records:
mysql> select *from DemoTable;
This will produce the following output
+----+-------+------+
| Id | Name | Age |
+----+-------+------+
| 1 | Larry | 23 |
| 2 | Sam | 24 |
| 3 | Chris | 21 |
| 4 | Carol | 25 |
| 5 | Bob | 23 |
| 6 | Bob | 23 |
| 7 | Bob | 23 |
| 8 | Bob | 23 |
| 9 | Bob | 23 |
| 10 | Bob | 23 |
+----+-------+------+
10 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1151,
"s": 1062,
"text": "To update a range of records in MySQL, you can use BETWEEN. Let us first create a table:"
},
{
"code": null,
"e": 1302,
"s": 1151,
"text": "mysql> create table DemoTable\n(\n Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n Name varchar(20),\n Age int\n);\nQuery OK, 0 rows affected (0.53 sec)"
},
{
"code": null,
"e": 1383,
"s": 1302,
"text": "Following is the query to insert some records in the table using insert command:"
},
{
"code": null,
"e": 2331,
"s": 1383,
"text": "mysql> insert into DemoTable(Name,Age) values('Larry',23);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable(Name,Age) values('Sam',24);\nQuery OK, 1 row affected (0.21 sec)\nmysql> insert into DemoTable(Name,Age) values('Chris',21);\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable(Name,Age) values('Carol',25);\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable(Name,Age) values('David',22);\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable(Name,Age) values('Robert',26);\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable(Name,Age) values('John',20);\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable(Name,Age) values('Mike',27);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable(Name,Age) values('Johnny',28);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable(Name,Age) values('James',23);\nQuery OK, 1 row affected (0.23 sec)"
},
{
"code": null,
"e": 2410,
"s": 2331,
"text": "Following is the query to display records from the table using select command:"
},
{
"code": null,
"e": 2441,
"s": 2410,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 2481,
"s": 2441,
"text": "This will produce the following output:"
},
{
"code": null,
"e": 2785,
"s": 2481,
"text": "+----+--------+------+\n| Id | Name | Age |\n+----+--------+------+\n| 1 | Larry | 23 |\n| 2 | Sam | 24 |\n| 3 | Chris | 21 |\n| 4 | Carol | 25 |\n| 5 | David | 22 |\n| 6 | Robert | 26 |\n| 7 | John | 20 |\n| 8 | Mike | 27 |\n| 9 | Johnny | 28 |\n| 10 | James | 23 |\n+----+--------+------+\n10 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2911,
"s": 2785,
"text": "Following is the query to update a range of records in MySQL. We are updating the Name to ‘Bob’ for Ids in the range 5 to 10:"
},
{
"code": null,
"e": 3061,
"s": 2911,
"text": "mysql> update DemoTable set Name='Bob', Age=23 where Id between 5 AND 10;\nQuery OK, 6 rows affected (0.25 sec)\nRows matched: 6 Changed: 6 Warnings: 0"
},
{
"code": null,
"e": 3119,
"s": 3061,
"text": "Let us now display all records including updated records:"
},
{
"code": null,
"e": 3150,
"s": 3119,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 3189,
"s": 3150,
"text": "This will produce the following output"
},
{
"code": null,
"e": 3523,
"s": 3189,
"text": "+----+-------+------+\n| Id | Name | Age |\n+----+-------+------+\n| 1 | Larry | 23 |\n| 2 | Sam | 24 |\n| 3 | Chris | 21 |\n| 4 | Carol | 25 |\n| 5 | Bob | 23 |\n| 6 | Bob | 23 |\n| 7 | Bob | 23 |\n| 8 | Bob | 23 |\n| 9 | Bob | 23 |\n| 10 | Bob | 23 |\n+----+-------+------+\n10 rows in set (0.00 sec)"
}
] |
Java - String Buffer replace() Method
|
This method replaces the characters in a substring of this StringBuffer with characters in the specified String.
The substring begins at the specified start and extends to the character at index end - 1 or to the end of the StringBuffer, if no such character exists. First the characters in the substring are removed and then the specified String is inserted at start.
Here is the syntax of this method −
public StringBuffer replace(int start, int end, String str)
Here is the detail of parameters −
start − The beginning index, inclusive.
start − The beginning index, inclusive.
end − The ending index, exclusive.
end − The ending index, exclusive.
str − String that will replace previous contents.
str − String that will replace previous contents.
This method returns the modified StringBuffer object.
public class Test {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("abcdefghijk");
sb.replace(3, 8, "ZARA");
System.out.println(sb);
}
}
This will produce the following result −
abcZARAijk
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2490,
"s": 2377,
"text": "This method replaces the characters in a substring of this StringBuffer with characters in the specified String."
},
{
"code": null,
"e": 2746,
"s": 2490,
"text": "The substring begins at the specified start and extends to the character at index end - 1 or to the end of the StringBuffer, if no such character exists. First the characters in the substring are removed and then the specified String is inserted at start."
},
{
"code": null,
"e": 2782,
"s": 2746,
"text": "Here is the syntax of this method −"
},
{
"code": null,
"e": 2843,
"s": 2782,
"text": "public StringBuffer replace(int start, int end, String str)\n"
},
{
"code": null,
"e": 2878,
"s": 2843,
"text": "Here is the detail of parameters −"
},
{
"code": null,
"e": 2918,
"s": 2878,
"text": "start − The beginning index, inclusive."
},
{
"code": null,
"e": 2958,
"s": 2918,
"text": "start − The beginning index, inclusive."
},
{
"code": null,
"e": 2993,
"s": 2958,
"text": "end − The ending index, exclusive."
},
{
"code": null,
"e": 3028,
"s": 2993,
"text": "end − The ending index, exclusive."
},
{
"code": null,
"e": 3078,
"s": 3028,
"text": "str − String that will replace previous contents."
},
{
"code": null,
"e": 3128,
"s": 3078,
"text": "str − String that will replace previous contents."
},
{
"code": null,
"e": 3182,
"s": 3128,
"text": "This method returns the modified StringBuffer object."
},
{
"code": null,
"e": 3376,
"s": 3182,
"text": "public class Test {\n\n public static void main(String args[]) {\n StringBuffer sb = new StringBuffer(\"abcdefghijk\");\n sb.replace(3, 8, \"ZARA\");\n System.out.println(sb); \n } \n}"
},
{
"code": null,
"e": 3417,
"s": 3376,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3429,
"s": 3417,
"text": "abcZARAijk\n"
},
{
"code": null,
"e": 3462,
"s": 3429,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3478,
"s": 3462,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3511,
"s": 3478,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3527,
"s": 3511,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3562,
"s": 3527,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3576,
"s": 3562,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3610,
"s": 3576,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3624,
"s": 3610,
"text": " Tushar Kale"
},
{
"code": null,
"e": 3661,
"s": 3624,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3676,
"s": 3661,
"text": " Monica Mittal"
},
{
"code": null,
"e": 3709,
"s": 3676,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3728,
"s": 3709,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3735,
"s": 3728,
"text": " Print"
},
{
"code": null,
"e": 3746,
"s": 3735,
"text": " Add Notes"
}
] |
How do I see what character set a MySQL database / table / column is?
|
To check what character set a MySQL database/ table/ column is, let us see an example: A database which has the name ‘business’ and table name is ‘student’ which is already present in the database is used.
Syntax in order to check the table character set.
SELECT CCSA.character_set_name
FROM information_schema.`TABLES` T,information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` CCSA
WHERE CCSA.collation_name = T.table_collation
AND T.table_schema = "yourDatabaseName"
AND T.table_name = "yourTableName";
Applying the above syntax to display character set for table student.
mysql> SELECT CCSA.character_set_name
FROM information_schema.`TABLES` T,
-> information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` CCSA
-> WHERE CCSA.collation_name = T.table_collation
-> AND T.table_schema = "business"
-> AND T.table_name = "student";
The following is the output.
+--------------------+
| CHARACTER_SET_NAME |
+--------------------+
| utf8mb4 |
+--------------------+
1 row in set (0.13 sec)
To find character set for database, here is the syntax.
SELECT default_character_set_name FROM information_schema.SCHEMATA
WHERE schema_name = "yourDatabaseName";
Applying the above syntax in order to see the character set for database.
mysql> SELECT default_character_set_name FROM information_schema.SCHEMATA
-> WHERE schema_name = "business";
The following is the output.
+----------------------------+
| DEFAULT_CHARACTER_SET_NAME |
+----------------------------+
| utf8mb4 |
+----------------------------+
1 row in set (0.00 sec)
To find the character set for column.
SELECT character_set_name FROM information_schema.`COLUMNS`
WHERE table_schema = "yourDatabaseName"
AND table_name = "yourTableName"
AND column_name = "yourColumnName";
Applying the above syntax in order to see what character set is for column name ‘Name’ for the “student” table and “business” database.
mysql> SELECT character_set_name FROM information_schema.`COLUMNS`
-> WHERE table_schema = "business"
-> AND table_name = "student"
-> AND column_name = "Name";
The following is the output.
+--------------------+
| CHARACTER_SET_NAME |
+--------------------+
| utf8mb4 |
+--------------------+
1 row in set (0.00 sec)
|
[
{
"code": null,
"e": 1268,
"s": 1062,
"text": "To check what character set a MySQL database/ table/ column is, let us see an example: A database which has the name ‘business’ and table name is ‘student’ which is already present in the database is used."
},
{
"code": null,
"e": 1318,
"s": 1268,
"text": "Syntax in order to check the table character set."
},
{
"code": null,
"e": 1571,
"s": 1318,
"text": "SELECT CCSA.character_set_name \nFROM information_schema.`TABLES` T,information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` CCSA\nWHERE CCSA.collation_name = T.table_collation\nAND T.table_schema = \"yourDatabaseName\"\nAND T.table_name = \"yourTableName\";"
},
{
"code": null,
"e": 1641,
"s": 1571,
"text": "Applying the above syntax to display character set for table student."
},
{
"code": null,
"e": 1914,
"s": 1641,
"text": "mysql> SELECT CCSA.character_set_name \nFROM information_schema.`TABLES` T,\n -> information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` CCSA\n -> WHERE CCSA.collation_name = T.table_collation\n -> AND T.table_schema = \"business\"\n -> AND T.table_name = \"student\";"
},
{
"code": null,
"e": 1943,
"s": 1914,
"text": "The following is the output."
},
{
"code": null,
"e": 2083,
"s": 1943,
"text": "+--------------------+\n| CHARACTER_SET_NAME |\n+--------------------+\n| utf8mb4 |\n+--------------------+\n1 row in set (0.13 sec)\n"
},
{
"code": null,
"e": 2139,
"s": 2083,
"text": "To find character set for database, here is the syntax."
},
{
"code": null,
"e": 2250,
"s": 2139,
"text": "SELECT default_character_set_name FROM information_schema.SCHEMATA\n WHERE schema_name = \"yourDatabaseName\";"
},
{
"code": null,
"e": 2324,
"s": 2250,
"text": "Applying the above syntax in order to see the character set for database."
},
{
"code": null,
"e": 2436,
"s": 2324,
"text": "mysql> SELECT default_character_set_name FROM information_schema.SCHEMATA\n -> WHERE schema_name = \"business\";"
},
{
"code": null,
"e": 2465,
"s": 2436,
"text": "The following is the output."
},
{
"code": null,
"e": 2645,
"s": 2465,
"text": "+----------------------------+\n| DEFAULT_CHARACTER_SET_NAME |\n+----------------------------+\n| utf8mb4 |\n+----------------------------+\n1 row in set (0.00 sec)\n"
},
{
"code": null,
"e": 2683,
"s": 2645,
"text": "To find the character set for column."
},
{
"code": null,
"e": 2861,
"s": 2683,
"text": "SELECT character_set_name FROM information_schema.`COLUMNS`\n WHERE table_schema = \"yourDatabaseName\"\n AND table_name = \"yourTableName\"\n AND column_name = \"yourColumnName\";"
},
{
"code": null,
"e": 2997,
"s": 2861,
"text": "Applying the above syntax in order to see what character set is for column name ‘Name’ for the “student” table and “business” database."
},
{
"code": null,
"e": 3168,
"s": 2997,
"text": "mysql> SELECT character_set_name FROM information_schema.`COLUMNS`\n -> WHERE table_schema = \"business\"\n -> AND table_name = \"student\"\n -> AND column_name = \"Name\";"
},
{
"code": null,
"e": 3197,
"s": 3168,
"text": "The following is the output."
},
{
"code": null,
"e": 3337,
"s": 3197,
"text": "+--------------------+\n| CHARACTER_SET_NAME |\n+--------------------+\n| utf8mb4 |\n+--------------------+\n1 row in set (0.00 sec)\n"
}
] |
How to perform double click on an element in Selenium with python?
|
We can perform double click on an element in Selenium with the help of
Action Chains class. These classes are generally used for automating interactions
like context menu click, mouse button actions, key press and mouse movements.
These types of actions are mainly common in complex scenarios like drag and drop
and hovering over an element on the page. The methods of the Action Chains class
are utilized by advanced scripts. We can manipulate DOM with the help of Action
Chains in Selenium.
The action chain object implements the ActionChains in the form of a queue and
then executes the perform() method. On calling the method perform(), all the
actions on action chains will be performed.
The method of creating an Action Chain object is listed below −
First we need to import the Action Chain class and then the driver will be
passed as an argument to it.
First we need to import the Action Chain class and then the driver will be
passed as an argument to it.
Now all the operations of action chains can be done with the help of this
object.
Now all the operations of action chains can be done with the help of this
object.
Syntax for creating an object of Action Chains −
from selenium import webdriver
# import Action chains
from selenium.webdriver import ActionChains
# create webdriver object
driver = webdriver.Firefox()
# create action chain object
action = ActionChains(driver)
After creating an object of Action Chains, we can perform numerous operations
one by one like a chain which is queued.
double_click() - This method performs double click operation on an element of the
page.
double_click(args)
Where args is the element which has to be double clicked. If omitted, the click on
the present mouse position is performed.
#element
source = driver.find_element_by_id("name")
#action chain object
action = ActionChains(driver)
# double click operation
action.double_click(source)
Code Implementation for double click operation.
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then
#invoke actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/index.htm")
#to refresh the browser
driver.refresh()
# identifying the source element
source= driver.find_element_by_xpath("//*[text()='GATE Exams']");
# action chain object creation
action = ActionChains(driver)
# double click operation and perform
action.double_click(source).perform()
#to close the browser
driver.close()
|
[
{
"code": null,
"e": 1293,
"s": 1062,
"text": "We can perform double click on an element in Selenium with the help of\nAction Chains class. These classes are generally used for automating interactions\nlike context menu click, mouse button actions, key press and mouse movements."
},
{
"code": null,
"e": 1555,
"s": 1293,
"text": "These types of actions are mainly common in complex scenarios like drag and drop\nand hovering over an element on the page. The methods of the Action Chains class\nare utilized by advanced scripts. We can manipulate DOM with the help of Action\nChains in Selenium."
},
{
"code": null,
"e": 1755,
"s": 1555,
"text": "The action chain object implements the ActionChains in the form of a queue and\nthen executes the perform() method. On calling the method perform(), all the\nactions on action chains will be performed."
},
{
"code": null,
"e": 1819,
"s": 1755,
"text": "The method of creating an Action Chain object is listed below −"
},
{
"code": null,
"e": 1923,
"s": 1819,
"text": "First we need to import the Action Chain class and then the driver will be\npassed as an argument to it."
},
{
"code": null,
"e": 2027,
"s": 1923,
"text": "First we need to import the Action Chain class and then the driver will be\npassed as an argument to it."
},
{
"code": null,
"e": 2109,
"s": 2027,
"text": "Now all the operations of action chains can be done with the help of this\nobject."
},
{
"code": null,
"e": 2191,
"s": 2109,
"text": "Now all the operations of action chains can be done with the help of this\nobject."
},
{
"code": null,
"e": 2240,
"s": 2191,
"text": "Syntax for creating an object of Action Chains −"
},
{
"code": null,
"e": 2271,
"s": 2240,
"text": "from selenium import webdriver"
},
{
"code": null,
"e": 2452,
"s": 2271,
"text": "# import Action chains\nfrom selenium.webdriver import ActionChains\n# create webdriver object\ndriver = webdriver.Firefox()\n# create action chain object\naction = ActionChains(driver)"
},
{
"code": null,
"e": 2571,
"s": 2452,
"text": "After creating an object of Action Chains, we can perform numerous operations\none by one like a chain which is queued."
},
{
"code": null,
"e": 2659,
"s": 2571,
"text": "double_click() - This method performs double click operation on an element of the\npage."
},
{
"code": null,
"e": 2678,
"s": 2659,
"text": "double_click(args)"
},
{
"code": null,
"e": 2802,
"s": 2678,
"text": "Where args is the element which has to be double clicked. If omitted, the click on\nthe present mouse position is performed."
},
{
"code": null,
"e": 2958,
"s": 2802,
"text": "#element\nsource = driver.find_element_by_id(\"name\")\n#action chain object\naction = ActionChains(driver)\n# double click operation\naction.double_click(source)"
},
{
"code": null,
"e": 3006,
"s": 2958,
"text": "Code Implementation for double click operation."
},
{
"code": null,
"e": 3784,
"s": 3006,
"text": "from selenium import webdriver\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.common.keys import Keys\n#browser exposes an executable file\n#Through Selenium test we will invoke the executable file which will then\n#invoke actual browser\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\n# to maximize the browser window\ndriver.maximize_window()\n#get method to launch the URL\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n#to refresh the browser\ndriver.refresh()\n# identifying the source element\nsource= driver.find_element_by_xpath(\"//*[text()='GATE Exams']\");\n# action chain object creation\naction = ActionChains(driver)\n# double click operation and perform\naction.double_click(source).perform()\n#to close the browser\ndriver.close()"
}
] |
Analysis of Algorithms | Set 5 (Practice Problems) - GeeksforGeeks
|
31 Mar, 2022
We have discussed Asymptotic Analysis, Worst, Average and Best Cases , Asymptotic Notations and Analysis of loops in previous posts.In this post, practice problems on the analysis of algorithms are discussed.Problem 1: Find the complexity of below recurrence:
{ 3T(n-1), if n>0,
T(n) = { 1, otherwise
Solution:
Let us solve using substitution.
T(n) = 3T(n-1)
= 3(3T(n-2))
= 32T(n-2)
= 33T(n-3)
...
...
= 3nT(n-n)
= 3nT(0)
= 3n
This clearly shows that the complexity
of this function is O(3n).
Problem 2: Find the complexity of the recurrence:
{ 2T(n-1) - 1, if n>0,
T(n) = { 1, otherwise
Solution:
Let us try solving this function with substitution.
T(n) = 2T(n-1) - 1
= 2(2T(n-2)-1)-1
= 22(T(n-2)) - 2 - 1
= 22(2T(n-3)-1) - 2 - 1
= 23T(n-3) - 22 - 21 - 20
.....
.....
= 2nT(n-n) - 2n-1 - 2n-2 - 2n-3
..... 22 - 21 - 20
= 2n - 2n-1 - 2n-2 - 2n-3
..... 22 - 21 - 20
= 2n - (2n-1)
[Note: 2n-1 + 2n-2 + ...... + 20 = 2n - 1]
T(n) = 1
Time Complexity is O(1). Note that while
the recurrence relation looks exponential
the solution to the recurrence relation
here gives a different result.
Problem 3: Find the complexity of the below program:
CPP
function(int n){ if (n==1) return; for (int i=1; i<=n; i++) { for (int j=1; j<=n; j++) { printf("*"); break; } }}
Solution: Consider the comments in the following function.
CPP
function(int n){ if (n==1) return; for (int i=1; i<=n; i++) { // Inner loop executes only one // time due to break statement. for (int j=1; j<=n; j++) { printf("*"); break; } }}
Time Complexity of the above function O(n). Even though the inner loop is bounded by n, but due to the break statement, it is executing only once. Problem 4: Find the complexity of the below program:
CPP
Java
C#
Javascript
void function(int n){ int count = 0; for (int i=n/2; i<=n; i++) for (int j=1; j<=n; j = 2 * j) for (int k=1; k<=n; k = k * 2) count++;}
static void function(int n){ int count = 0; for (int i = n / 2; i <= n; i++) for (int j = 1; j <= n; j = 2 * j) for (int k = 1; k <= n; k = k * 2) count++;} // This code is contributed by rutvik_56.
static void function(int n){ int count = 0; for (int i = n / 2; i <= n; i++) for (int j = 1; j <= n; j = 2 * j) for (int k = 1; k <= n; k = k * 2) count++;} // This code is contributed by pratham76.
<script>function function1(n){ var count = 0; for (i = n / 2; i <= n; i++) for (j = 1; j <= n; j = 2 * j) for (k = 1; k <= n; k = k * 2) count++;} // This code is contributed by umadevi9616</script>
Solution: Consider the comments in the following function.
CPP
void function(int n){ int count = 0; for (int i=n/2; i<=n; i++) // Executes O(Log n) times for (int j=1; j<=n; j = 2 * j) // Executes O(Log n) times for (int k=1; k<=n; k = k * 2) count++;}
Time Complexity of the above function O(n log2n). Problem 5: Find the complexity of the below program:
CPP
void function(int n){ int count = 0; for (int i=n/2; i<=n; i++) for (int j=1; j+n/2<=n; j = j++) for (int k=1; k<=n; k = k * 2) count++;}
Solution: Consider the comments in the following function.
CPP
void function(int n){ int count = 0; // outer loop executes n/2 times for (int i=n/2; i<=n; i++) // middle loop executes n/2 times for (int j=1; j+n/2<=n; j = j++) // inner loop executes logn times for (int k=1; k<=n; k = k * 2) count++;}
Time Complexity of the above function O(n2logn). Problem 6: Find the complexity of the below program:
CPP
void function(int n){ int i = 1, s =1; while (s <= n) { i++; s += i; printf("*"); }}
Solution: We can define the terms ‘s’ according to relation si = si-1 + i. The value of ‘i’ increases by one for each iteration. The value contained in ‘s’ at the ith iteration is the sum of the first ‘i’ positive integers. If k is total number of iterations taken by the program, then while loop terminates if: 1 + 2 + 3 ....+ k = [k(k+1)/2] > n So k = O(√n).Time Complexity of the above function O(√n). Problem 7: Find a tight upper bound on the complexity of the below program:
CPP
void function(int n){ int count = 0; for (int i=0; i<n; i++) for (int j=i; j< i*i; j++) if (j%i == 0) { for (int k=0; k<j; k++) printf("*"); }}
Solution: Consider the comments in the following function.
CPP
void function(int n){ int count = 0; // executes n times for (int i=0; i<n; i++) // executes O(n*n) times. for (int j=i; j< i*i; j++) if (j%i == 0) { // executes j times = O(n*n) times for (int k=0; k<j; k++) printf("*"); }}
Time Complexity of the above function O(n5).
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
sugyan
rutvik_56
pratham76
surinderdawra388
umadevi9616
Analysis
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Time Complexity and Space Complexity
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Analysis of different sorting techniques
Analysis of Algorithms | Big-O analysis
Cyclomatic Complexity
Difference between Big Oh, Big Omega and Big Theta
Complexity Analysis of Binary Search
Time complexities of different data structures
Tail Recursion
Difference between NP hard and NP complete problem
|
[
{
"code": null,
"e": 24158,
"s": 24130,
"text": "\n31 Mar, 2022"
},
{
"code": null,
"e": 24420,
"s": 24158,
"text": "We have discussed Asymptotic Analysis, Worst, Average and Best Cases , Asymptotic Notations and Analysis of loops in previous posts.In this post, practice problems on the analysis of algorithms are discussed.Problem 1: Find the complexity of below recurrence: "
},
{
"code": null,
"e": 24472,
"s": 24420,
"text": " { 3T(n-1), if n>0,\nT(n) = { 1, otherwise"
},
{
"code": null,
"e": 24484,
"s": 24472,
"text": "Solution: "
},
{
"code": null,
"e": 24713,
"s": 24484,
"text": "Let us solve using substitution.\nT(n) = 3T(n-1)\n = 3(3T(n-2)) \n = 32T(n-2)\n = 33T(n-3)\n ...\n ...\n = 3nT(n-n)\n = 3nT(0) \n = 3n\nThis clearly shows that the complexity \nof this function is O(3n)."
},
{
"code": null,
"e": 24765,
"s": 24713,
"text": "Problem 2: Find the complexity of the recurrence: "
},
{
"code": null,
"e": 24820,
"s": 24765,
"text": " { 2T(n-1) - 1, if n>0,\nT(n) = { 1, otherwise"
},
{
"code": null,
"e": 24831,
"s": 24820,
"text": "Solution: "
},
{
"code": null,
"e": 25388,
"s": 24831,
"text": "Let us try solving this function with substitution.\nT(n) = 2T(n-1) - 1\n = 2(2T(n-2)-1)-1 \n = 22(T(n-2)) - 2 - 1\n = 22(2T(n-3)-1) - 2 - 1 \n = 23T(n-3) - 22 - 21 - 20\n .....\n .....\n = 2nT(n-n) - 2n-1 - 2n-2 - 2n-3\n ..... 22 - 21 - 20\n\n = 2n - 2n-1 - 2n-2 - 2n-3\n ..... 22 - 21 - 20\n = 2n - (2n-1) \n[Note: 2n-1 + 2n-2 + ...... + 20 = 2n - 1]\nT(n) = 1\nTime Complexity is O(1). Note that while \nthe recurrence relation looks exponential\nthe solution to the recurrence relation \nhere gives a different result."
},
{
"code": null,
"e": 25443,
"s": 25388,
"text": "Problem 3: Find the complexity of the below program: "
},
{
"code": null,
"e": 25447,
"s": 25443,
"text": "CPP"
},
{
"code": "function(int n){ if (n==1) return; for (int i=1; i<=n; i++) { for (int j=1; j<=n; j++) { printf(\"*\"); break; } }}",
"e": 25622,
"s": 25447,
"text": null
},
{
"code": null,
"e": 25682,
"s": 25622,
"text": "Solution: Consider the comments in the following function. "
},
{
"code": null,
"e": 25686,
"s": 25682,
"text": "CPP"
},
{
"code": "function(int n){ if (n==1) return; for (int i=1; i<=n; i++) { // Inner loop executes only one // time due to break statement. for (int j=1; j<=n; j++) { printf(\"*\"); break; } }}",
"e": 25939,
"s": 25686,
"text": null
},
{
"code": null,
"e": 26140,
"s": 25939,
"text": "Time Complexity of the above function O(n). Even though the inner loop is bounded by n, but due to the break statement, it is executing only once. Problem 4: Find the complexity of the below program: "
},
{
"code": null,
"e": 26144,
"s": 26140,
"text": "CPP"
},
{
"code": null,
"e": 26149,
"s": 26144,
"text": "Java"
},
{
"code": null,
"e": 26152,
"s": 26149,
"text": "C#"
},
{
"code": null,
"e": 26163,
"s": 26152,
"text": "Javascript"
},
{
"code": "void function(int n){ int count = 0; for (int i=n/2; i<=n; i++) for (int j=1; j<=n; j = 2 * j) for (int k=1; k<=n; k = k * 2) count++;}",
"e": 26338,
"s": 26163,
"text": null
},
{
"code": "static void function(int n){ int count = 0; for (int i = n / 2; i <= n; i++) for (int j = 1; j <= n; j = 2 * j) for (int k = 1; k <= n; k = k * 2) count++;} // This code is contributed by rutvik_56.",
"e": 26576,
"s": 26338,
"text": null
},
{
"code": "static void function(int n){ int count = 0; for (int i = n / 2; i <= n; i++) for (int j = 1; j <= n; j = 2 * j) for (int k = 1; k <= n; k = k * 2) count++;} // This code is contributed by pratham76.",
"e": 26814,
"s": 26576,
"text": null
},
{
"code": "<script>function function1(n){ var count = 0; for (i = n / 2; i <= n; i++) for (j = 1; j <= n; j = 2 * j) for (k = 1; k <= n; k = k * 2) count++;} // This code is contributed by umadevi9616</script>",
"e": 27052,
"s": 26814,
"text": null
},
{
"code": null,
"e": 27112,
"s": 27052,
"text": "Solution: Consider the comments in the following function. "
},
{
"code": null,
"e": 27116,
"s": 27112,
"text": "CPP"
},
{
"code": "void function(int n){ int count = 0; for (int i=n/2; i<=n; i++) // Executes O(Log n) times for (int j=1; j<=n; j = 2 * j) // Executes O(Log n) times for (int k=1; k<=n; k = k * 2) count++;}",
"e": 27365,
"s": 27116,
"text": null
},
{
"code": null,
"e": 27469,
"s": 27365,
"text": "Time Complexity of the above function O(n log2n). Problem 5: Find the complexity of the below program: "
},
{
"code": null,
"e": 27473,
"s": 27469,
"text": "CPP"
},
{
"code": "void function(int n){ int count = 0; for (int i=n/2; i<=n; i++) for (int j=1; j+n/2<=n; j = j++) for (int k=1; k<=n; k = k * 2) count++;}",
"e": 27650,
"s": 27473,
"text": null
},
{
"code": null,
"e": 27711,
"s": 27650,
"text": "Solution: Consider the comments in the following function. "
},
{
"code": null,
"e": 27715,
"s": 27711,
"text": "CPP"
},
{
"code": "void function(int n){ int count = 0; // outer loop executes n/2 times for (int i=n/2; i<=n; i++) // middle loop executes n/2 times for (int j=1; j+n/2<=n; j = j++) // inner loop executes logn times for (int k=1; k<=n; k = k * 2) count++;}",
"e": 28018,
"s": 27715,
"text": null
},
{
"code": null,
"e": 28122,
"s": 28018,
"text": "Time Complexity of the above function O(n2logn). Problem 6: Find the complexity of the below program: "
},
{
"code": null,
"e": 28126,
"s": 28122,
"text": "CPP"
},
{
"code": "void function(int n){ int i = 1, s =1; while (s <= n) { i++; s += i; printf(\"*\"); }}",
"e": 28244,
"s": 28126,
"text": null
},
{
"code": null,
"e": 28727,
"s": 28244,
"text": "Solution: We can define the terms ‘s’ according to relation si = si-1 + i. The value of ‘i’ increases by one for each iteration. The value contained in ‘s’ at the ith iteration is the sum of the first ‘i’ positive integers. If k is total number of iterations taken by the program, then while loop terminates if: 1 + 2 + 3 ....+ k = [k(k+1)/2] > n So k = O(√n).Time Complexity of the above function O(√n). Problem 7: Find a tight upper bound on the complexity of the below program: "
},
{
"code": null,
"e": 28731,
"s": 28727,
"text": "CPP"
},
{
"code": "void function(int n){ int count = 0; for (int i=0; i<n; i++) for (int j=i; j< i*i; j++) if (j%i == 0) { for (int k=0; k<j; k++) printf(\"*\"); }}",
"e": 28955,
"s": 28731,
"text": null
},
{
"code": null,
"e": 29016,
"s": 28955,
"text": "Solution: Consider the comments in the following function. "
},
{
"code": null,
"e": 29020,
"s": 29016,
"text": "CPP"
},
{
"code": "void function(int n){ int count = 0; // executes n times for (int i=0; i<n; i++) // executes O(n*n) times. for (int j=i; j< i*i; j++) if (j%i == 0) { // executes j times = O(n*n) times for (int k=0; k<j; k++) printf(\"*\"); }}",
"e": 29352,
"s": 29020,
"text": null
},
{
"code": null,
"e": 29397,
"s": 29352,
"text": "Time Complexity of the above function O(n5)."
},
{
"code": null,
"e": 29824,
"s": 29397,
"text": "This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 29831,
"s": 29824,
"text": "sugyan"
},
{
"code": null,
"e": 29841,
"s": 29831,
"text": "rutvik_56"
},
{
"code": null,
"e": 29851,
"s": 29841,
"text": "pratham76"
},
{
"code": null,
"e": 29868,
"s": 29851,
"text": "surinderdawra388"
},
{
"code": null,
"e": 29880,
"s": 29868,
"text": "umadevi9616"
},
{
"code": null,
"e": 29889,
"s": 29880,
"text": "Analysis"
},
{
"code": null,
"e": 29987,
"s": 29889,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29996,
"s": 29987,
"text": "Comments"
},
{
"code": null,
"e": 30009,
"s": 29996,
"text": "Old Comments"
},
{
"code": null,
"e": 30046,
"s": 30009,
"text": "Time Complexity and Space Complexity"
},
{
"code": null,
"e": 30129,
"s": 30046,
"text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree"
},
{
"code": null,
"e": 30170,
"s": 30129,
"text": "Analysis of different sorting techniques"
},
{
"code": null,
"e": 30210,
"s": 30170,
"text": "Analysis of Algorithms | Big-O analysis"
},
{
"code": null,
"e": 30232,
"s": 30210,
"text": "Cyclomatic Complexity"
},
{
"code": null,
"e": 30283,
"s": 30232,
"text": "Difference between Big Oh, Big Omega and Big Theta"
},
{
"code": null,
"e": 30320,
"s": 30283,
"text": "Complexity Analysis of Binary Search"
},
{
"code": null,
"e": 30367,
"s": 30320,
"text": "Time complexities of different data structures"
},
{
"code": null,
"e": 30382,
"s": 30367,
"text": "Tail Recursion"
}
] |
How do I get into a Docker container's shell?
|
Once you have your Docker container up and running, you can work with the environment of the Docker container in the same way you would do with an Ubuntu machine. You can access the bash or shell of the container and execute commands inside it and play around with the file system. You can build, test, and deploy your applications inside the container itself.
Predominantly, there are 3 ways to access the shell of a running container. These are -
Using the Docker run command to run a container and access its shell.
Using the Docker exec command to run commands in an active container.
Using the Docker start command and attach a shell to a stopped container.
In this article, we will discuss all these approaches one by one with practical examples. Let’s see how to do so.
If you don’t have a container running, you can use the Docker run command to create and run a container associated with an image and access the bash of the container. Let’s try to run an ubuntu container and access it’s bash.
$ docker run -it --name=myubuntu ubuntu:latest bash
In the above command, we have used the -i (interactive) and -t (pseudo-TTY) options which will allow us to interact with the container using a terminal driver. The bash command at the end is run as soon as the container is started. Hence, after executing this command, the daemon will automatically create the container, run it, and provide us access to its shell.
Please note that if you don’t have an Ubuntu image on your system, the daemon will pull the image and create and run a container automatically.
Once you have access to the bash of the container, you can start interacting with the Ubuntu environment and play with its file system.
The Docker exec command is used to run a command inside a container that is already running. You can use this command only if the primary process of the container is running. Any command executed inside the container will run in the default working directory unless you specify the desired directory using the -w option. Moreover, you won’t be able to run any quoted or chained command. Only commands that are executable can be run.
The syntax of the Docker exec command is -
$ docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
You can use this command to start a new bash session of a container that is already running elsewhere.
$ docker exec -it myubuntu bash
This command uses the interactive and pseudo-TTY options to start the bash of the ubuntu container that is already running.
If you have a container in the exited state and you want to start a bash associated with that container, you can use the Docker start command along with the --attach and --interactive options. This will attach a new terminal and will allow you to interact with the container easily. Let’s see how to do so.
The original syntax of the Docker start command is -
$ docker start [OPTIONS] CONTAINER [CONTAINER...]
If you want to check the status of the container, you can try to list all the containers.
$ docker container ps -a
You can use the following command to create a bash session of a stopped container -
$ docker start -ai myubuntu
To sum up, in this article, we discussed how to get into a Docker container’s shell for a running, stopped, or by creating a new container. We have used the Docker run, exec, and start commands to do so. According to your own use case, you can use any of the above-discussed methods to achieve your goal.
|
[
{
"code": null,
"e": 1423,
"s": 1062,
"text": "Once you have your Docker container up and running, you can work with the environment of the Docker container in the same way you would do with an Ubuntu machine. You can access the bash or shell of the container and execute commands inside it and play around with the file system. You can build, test, and deploy your applications inside the container itself."
},
{
"code": null,
"e": 1511,
"s": 1423,
"text": "Predominantly, there are 3 ways to access the shell of a running container. These are -"
},
{
"code": null,
"e": 1581,
"s": 1511,
"text": "Using the Docker run command to run a container and access its shell."
},
{
"code": null,
"e": 1651,
"s": 1581,
"text": "Using the Docker exec command to run commands in an active container."
},
{
"code": null,
"e": 1725,
"s": 1651,
"text": "Using the Docker start command and attach a shell to a stopped container."
},
{
"code": null,
"e": 1839,
"s": 1725,
"text": "In this article, we will discuss all these approaches one by one with practical examples. Let’s see how to do so."
},
{
"code": null,
"e": 2065,
"s": 1839,
"text": "If you don’t have a container running, you can use the Docker run command to create and run a container associated with an image and access the bash of the container. Let’s try to run an ubuntu container and access it’s bash."
},
{
"code": null,
"e": 2117,
"s": 2065,
"text": "$ docker run -it --name=myubuntu ubuntu:latest bash"
},
{
"code": null,
"e": 2482,
"s": 2117,
"text": "In the above command, we have used the -i (interactive) and -t (pseudo-TTY) options which will allow us to interact with the container using a terminal driver. The bash command at the end is run as soon as the container is started. Hence, after executing this command, the daemon will automatically create the container, run it, and provide us access to its shell."
},
{
"code": null,
"e": 2626,
"s": 2482,
"text": "Please note that if you don’t have an Ubuntu image on your system, the daemon will pull the image and create and run a container automatically."
},
{
"code": null,
"e": 2762,
"s": 2626,
"text": "Once you have access to the bash of the container, you can start interacting with the Ubuntu environment and play with its file system."
},
{
"code": null,
"e": 3195,
"s": 2762,
"text": "The Docker exec command is used to run a command inside a container that is already running. You can use this command only if the primary process of the container is running. Any command executed inside the container will run in the default working directory unless you specify the desired directory using the -w option. Moreover, you won’t be able to run any quoted or chained command. Only commands that are executable can be run."
},
{
"code": null,
"e": 3238,
"s": 3195,
"text": "The syntax of the Docker exec command is -"
},
{
"code": null,
"e": 3289,
"s": 3238,
"text": "$ docker exec [OPTIONS] CONTAINER COMMAND [ARG...]"
},
{
"code": null,
"e": 3392,
"s": 3289,
"text": "You can use this command to start a new bash session of a container that is already running elsewhere."
},
{
"code": null,
"e": 3424,
"s": 3392,
"text": "$ docker exec -it myubuntu bash"
},
{
"code": null,
"e": 3548,
"s": 3424,
"text": "This command uses the interactive and pseudo-TTY options to start the bash of the ubuntu container that is already running."
},
{
"code": null,
"e": 3855,
"s": 3548,
"text": "If you have a container in the exited state and you want to start a bash associated with that container, you can use the Docker start command along with the --attach and --interactive options. This will attach a new terminal and will allow you to interact with the container easily. Let’s see how to do so."
},
{
"code": null,
"e": 3908,
"s": 3855,
"text": "The original syntax of the Docker start command is -"
},
{
"code": null,
"e": 3959,
"s": 3908,
"text": "$ docker start [OPTIONS] CONTAINER [CONTAINER...]\n"
},
{
"code": null,
"e": 4049,
"s": 3959,
"text": "If you want to check the status of the container, you can try to list all the containers."
},
{
"code": null,
"e": 4074,
"s": 4049,
"text": "$ docker container ps -a"
},
{
"code": null,
"e": 4158,
"s": 4074,
"text": "You can use the following command to create a bash session of a stopped container -"
},
{
"code": null,
"e": 4186,
"s": 4158,
"text": "$ docker start -ai myubuntu"
},
{
"code": null,
"e": 4491,
"s": 4186,
"text": "To sum up, in this article, we discussed how to get into a Docker container’s shell for a running, stopped, or by creating a new container. We have used the Docker run, exec, and start commands to do so. According to your own use case, you can use any of the above-discussed methods to achieve your goal."
}
] |
53 Python Interview Questions and Answers | by GreekDataGuy | Towards Data Science
|
Not so long ago I started a new role as a “Data Scientist” which turned out to be “Python Engineer” in practice.
I would have been more prepared if I’d brushed up on Python’s thread lifecycle instead of recommender systems in advance.
In that spirit, here are my python interview/job preparation questions and answers. Most data scientists write a lot code so this applies to both scientists and engineers.
Whether you’re interviewing candidates, preparing to apply to jobs or just brushing up on Python, I think this list will be invaluable.
Questions are unordered. Let’s begin.
I’ve been asked this question in every python / data science interview I’ve ever had. Know the answer like the back of your hand.
Lists are mutable. They can be modified after creation.
Tuples are immutable. Once a tuple is created it cannot by changed
Lists have order. They are an ordered sequences, typically of the same type of object. Ie: all user names ordered by creation date, ["Seth", "Ema", "Eli"]
Tuples have structure. Different data types may exist at each index. Ie: a database record in memory, (2, "Ema", "2020–04–16") # id, name, created_at
Without importing the Template class, there are 3 ways to interpolate strings.
name = 'Chris'# 1. f stringsprint(f'Hello {name}')# 2. % operatorprint('Hey %s %s' % (name, name))# 3. formatprint( "My name is {}".format((name)))
Early in my python career I assumed these were the same... hello bugs. So for the record, is checks identity and == checks equality.
We’ll walk through an example. Create some lists and assign them to names. Note that b points to the same object as a in below.
a = [1,2,3]b = ac = [1,2,3]
Check equality and note they are all equal.
print(a == b)print(a == c)#=> True#=> True
But do they have the same identity? Nope.
print(a is b)print(a is c)#=> True#=> False
We can verify this by printing their object id’s.
print(id(a))print(id(b))print(id(c))#=> 4369567560#=> 4369567560#=> 4369567624
c has a different id than a and b.
Another questions I’ve been asked in every interview. It’s deserves a post itself, but you’re prepared if you can walk through writing your own example.
A decorator allows adding functionality to an existing function by passing that existing function to a decorator, which executes the existing function as well as additional code.
We’ll write a decorator that that logs when another function is called.
Write the decorator function. This takes a function, func, as an argument. It also defines a function, log_function_called, which calls func() and executes some code, print(f'{func} called.'). Then it return the function it defined
def logging(func): def log_function_called(): print(f'{func} called.') func() return log_function_called
Let’s write other functions that we’ll eventually add the decorator to (but not yet).
def my_name(): print('chris')def friends_name(): print('naruto')my_name()friends_name()#=> chris#=> naruto
Now add the decorator to both.
@loggingdef my_name(): print('chris')@loggingdef friends_name(): print('naruto')my_name()friends_name()#=> <function my_name at 0x10fca5a60> called.#=> chris#=> <function friends_name at 0x10fca5f28> called.#=> naruto
See how we can now easily add logging to any function we write just by adding @logging above it.
Range generates a list of integers and there are 3 ways to use it.
The function takes 1 to 3 arguments. Note I’ve wrapped each usage in list comprehension so we can see the values generated.
range(stop) : generate integers from 0 to the “stop” integer.
[i for i in range(10)]#=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range(start, stop) : generate integers from the “start” to the “stop” integer.
[i for i in range(2,10)]#=> [2, 3, 4, 5, 6, 7, 8, 9]
range(start, stop, step) : generate integers from “start” to “stop” at intervals of “step”.
[i for i in range(2,10,2)]#=> [2, 4, 6, 8]
Thanks Searge Boremchuq for suggesting a more pythonic way to do this!
list(range(2,10,2))#=> [2, 4, 6, 8]
class Car : def __init__(self, color, speed): self.color = color self.speed = speedcar = Car('red','100mph')car.speed#=> '100mph'
Instance methods : accept self parameter and relate to a specific instance of the class.
Static methods : use @staticmethod decorator, are not related to a specific instance, and are self-contained (don’t modify class or instance attributes)
Class methods : accept cls parameter and can modify the class itself
We’re going to illustrate the difference around a fictional CoffeeShop class.
class CoffeeShop: specialty = 'espresso' def __init__(self, coffee_price): self.coffee_price = coffee_price # instance method def make_coffee(self): print(f'Making {self.specialty} for ${self.coffee_price}') # static method @staticmethod def check_weather(): print('Its sunny') # class method @classmethod def change_specialty(cls, specialty): cls.specialty = specialty print(f'Specialty changed to {specialty}')
CoffeeShop class has an attribute, specialty, set to 'espresso' by default. Each instance of CoffeeShop is initialized with an attribute coffee_price . It also has 3 methods, an instance method, a static method and a class method.
Let’s initialize an instance of the coffee shop with a coffee_price of 5. Then call the instance method make_coffee.
coffee_shop = CoffeeShop('5')coffee_shop.make_coffee()#=> Making espresso for $5
Now call the static method. Static methods can’t modify class or instance state so they’re normally used for utility functions, for example, adding 2 numbers. We used ours to check the weather.Its sunny. Great!
coffee_shop.check_weather()#=> Its sunny
Now let’s use the class method to modify the coffee shop’s specialty and then make_coffee.
coffee_shop.change_specialty('drip coffee')#=> Specialty changed to drip coffeecoffee_shop.make_coffee()#=> Making drip coffee for $5
Note how make_coffee used to make espresso but now makes drip coffee!
The purpose of this question is to see if you understand that all functions are also objects in python.
def func(): print('Im a function') func#=> function __main__.func>func() #=> Im a function
func is the object representing the function which can be assigned to a variable or passed to another function. func() with parentheses calls the function and returns what it outputs.
map returns a map object (an iterator) which can iterate over returned values from applying a function to every element in a sequence. The map object can also be converted to a list if required.
def add_three(x): return x + 3li = [1,2,3][i for i in map(add_three, li)]#=> [4, 5, 6]
Above, I added 3 to every element in the list.
A reader suggested a more pythonic implementation. Thanks Chrisjan Wust !
def add_three(x): return x + 3li = [1,2,3]list(map(add_three, li))#=> [4, 5, 6]
Also, thanks Michael Graeme Short for the corrections!
This can be tricky to wrap your head around until you use it a few times.
reduce takes a function and a sequence and iterates over that sequence. On each iteration, both the current element and output from the previous element are passed to the function. In the end, a single value is returned.
from functools import reducedef add_three(x,y): return x + yli = [1,2,3,5]reduce(add_three, li)#=> 11
11 is returned which is the sum of 1+2+3+5.
Filter literally does what the name says. It filters elements in a sequence.
Each element is passed to a function which is returned in the outputted sequence if the function returns True and discarded if the function returns False.
def add_three(x): if x % 2 == 0: return True else: return Falseli = [1,2,3,4,5,6,7,8][i for i in filter(add_three, li)]#=> [2, 4, 6, 8]
Note how all elements not divisible by 2 have been removed.
Be prepared to go down a rabbit hole of semantics if you google this question and read the top few pages.
In a nutshell, all names call by reference, but some memory locations hold objects while others hold pointers to yet other memory locations.
name = 'object'
Let’s see how this works with strings. We’ll instantiate a name and object, point other names to it. Then delete the first name.
x = 'some text'y = xx is y #=> Truedel x # this deletes the 'a' name but does nothing to the object in memoryz = yy is z #=> True
What we see is that all these names point to the same object in memory, which wasn’t affected by del x.
Here’s another interesting example with a function.
name = 'text'def add_chars(str1): print( id(str1) ) #=> 4353702856 print( id(name) ) #=> 4353702856 # new name, same object str2 = str1 # creates a new name (with same name as the first) AND object str1 += 's' print( id(str1) ) #=> 4387143328 # still the original object print( id(str2) ) #=> 4353702856 add_chars(name)print(name) #=>text
Notice how adding an s to the string inside the function created a new name AND a new object. Even though the new name has the same “name” as the existing name.
Thanks Michael P. Reilly for the corrections!
Note how reverse() is called on the list and mutates it. It doesn’t return the mutated list itself.
li = ['a','b','c']print(li)li.reverse()print(li)#=> ['a', 'b', 'c']#=> ['c', 'b', 'a']
Let’s see the results of multiplying the string ‘cat’ by 3.
'cat' * 3#=> 'catcatcat'
The string is concatenated to itself 3 times.
Let’s see the result of multiplying a list, [1,2,3] by 2.
[1,2,3] * 2#=> [1, 2, 3, 1, 2, 3]
A list is outputted containing the contents of [1,2,3] repeated twice.
Self refers to the instance of the class itself. It’s how we give methods access to and the ability to update the object they belong to.
Below, passing self to __init__() gives us the ability to set the color of an instance on initialization.
class Shirt: def __init__(self, color): self.color = color s = Shirt('yellow')s.color#=> 'yellow'
Adding 2 lists together concatenates them. Note that arrays do not function the same way.
a = [1,2]b = [3,4,5]a + b#=> [1, 2, 3, 4, 5]
We’ll discuss this in the context of a mutable object, a list. For immutable objects, shallow vs deep isn’t as relevant.
We’ll walk through 3 scenarios.
i) Reference the original object. This points a new name, li2, to the same place in memory to which li1 points. So any change we make to li1 also occurs to li2.
li1 = [['a'],['b'],['c']]li2 = li1li1.append(['d'])print(li2)#=> [['a'], ['b'], ['c'], ['d']]
ii) Create a shallow copy of the original. We can do this with the list() constructor, or the more pythonic mylist.copy() (thanks Chrisjan Wust !).
A shallow copy creates a new object, but fills it with references to the original. So adding a new object to the original collection, li3, doesn’t propagate to li4, but modifying one of the objects in li3 will propagate to li4.
li3 = [['a'],['b'],['c']]li4 = list(li3)li3.append([4])print(li4)#=> [['a'], ['b'], ['c']]li3[0][0] = ['X']print(li4)#=> [[['X']], ['b'], ['c']]
iii) Create a deep copy. This is done with copy.deepcopy(). The 2 objects are now completely independent and changes to either have no affect on the other.
import copyli5 = [['a'],['b'],['c']]li6 = copy.deepcopy(li5)li5.append([4])li5[0][0] = ['X']print(li6)#=> [['a'], ['b'], ['c']]
Note: Python’s standard library has an array object but here I’m specifically referring to the commonly used Numpy array.
Lists exist in python’s standard library. Arrays are defined by Numpy.
Lists can be populated with different types of data at each index. Arrays require homogeneous elements.
Arithmetic on lists adds or removes elements from the list. Arithmetic on arrays functions per linear algebra.
Arrays also use less memory and come with significantly more functionality.
I wrote another comprehensive post on arrays.
Remember, arrays are not lists. Arrays are from Numpy and arithmetic functions like linear algebra.
We need to use Numpy’s concatenate function to do it.
import numpy as npa = np.array([1,2,3])b = np.array([4,5,6])np.concatenate((a,b))#=> array([1, 2, 3, 4, 5, 6])
Note this is a very subjective question and you’ll want to modify your response based on what the role is looking for.
Python is very readable and there is a pythonic way to do just about everything, meaning a preferred way which is clear and concise.
I’d contrast this to Ruby where there are often many ways to do something without a guideline for which is preferred.
Also subjective, see question 21.
When working with a lot data, nothing is quite as helpful as pandas which makes manipulating and visualizing data a breeze.
Immutable means the state cannot be modified after creation. Examples are: int, float, bool, string and tuple.
Mutable means the state can be modified after creation. Examples are list, dict and set.
Use the round(value, decimal_places) function.
a = 5.12345round(a,3)#=> 5.123
Slicing notation takes 3 arguments, list[start:stop:step], where step is the interval at which elements are returned.
a = [0,1,2,3,4,5,6,7,8,9]print(a[:2])#=> [0, 1]print(a[8:])#=> [8, 9]print(a[2:8])#=> [2, 3, 4, 5, 6, 7]print(a[2:8:2])#=> [2, 4, 6]
Pickling is the go-to method of serializing and unserializing objects in Python.
In the example below, we serialize and unserialize a list of dictionaries.
import pickleobj = [ {'id':1, 'name':'Stuffy'}, {'id':2, 'name': 'Fluffy'}]with open('file.p', 'wb') as f: pickle.dump(obj, f)with open('file.p', 'rb') as f: loaded_obj = pickle.load(f)print(loaded_obj)#=> [{'id': 1, 'name': 'Stuffy'}, {'id': 2, 'name': 'Fluffy'}]
Dict is python datatype, a collection of indexed but unordered keys and values.
JSON is just a string which follows a specified format and is intended for transferring data.
ORMs (object relational mapping) map data models (usually in an app) to database tables and simplifies database transactions.
SQLAlchemy is typically used in the context of Flask, and Django has it’s own ORM.
Any takes a sequence and returns true if any element in the sequence is true.
All returns true only if all elements in the sequence are true.
a = [False, False, False]b = [True, False, False]c = [True, True, True]print( any(a) )print( any(b) )print( any(c) )#=> False#=> True#=> Trueprint( all(a) )print( all(b) )print( all(c) )#=> False#=> False#=> True
Looking up a value in a list takes O(n) time because the whole list needs to be iterated through until the value is found.
Looking up a key in a dictionary takes O(1) time because it’s a hash table.
This can make a huge time difference if there are a lot of values so dictionaries are generally recommended for speed. But they do have other limitations like needing unique keys.
A module is a file (or collection of files) that can be imported together.
import sklearn
A package is a directory of modules.
from sklearn import cross_validation
So packages are modules, but not all modules are packages.
Increments and decrements can be done with +- and -= .
value = 5value += 1print(value)#=> 6value -= 1value -= 1print(value)#=> 4
Use the bin() function.
bin(5)#=> '0b101'
This can be done by converting the list to a set then back to a list.
a = [1,1,1,2,3]a = list(set(a))print(a)#=> [1, 2, 3]
Note that sets will not necessarily maintain the order of a list.
Use in.
'a' in ['a','b','c']#=> True'a' in [1,2,3]#=> False
append adds a value to a list while extend adds values in another list to a list.
a = [1,2,3]b = [1,2,3]a.append(6)print(a)#=> [1, 2, 3, 6]b.extend([4,5])print(b)#=> [1, 2, 3, 4, 5]
This can be done with the abs() function.
abs(2)#=> 2abs(-2)#=> 2
You can use the zip function to combine lists into a list of tuples. This isn’t restricted to only using 2 lists. It can also be done with 3 or more.
a = ['a','b','c']b = [1,2,3][(k,v) for k,v in zip(a,b)]#=> [('a', 1), ('b', 2), ('c', 3)]
You can’t “sort” a dictionary because dictionaries don’t have order but you can return a sorted list of tuples which has the keys and values that are in the dictionary.
d = {'c':3, 'd':4, 'b':2, 'a':1}sorted(d.items())#=> [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
In the below example, Audi, inherits from Car. And with that inheritance comes the instance methods of the parent class.
class Car(): def drive(self): print('vroom')class Audi(Car): passaudi = Audi()audi.drive()
The easiest way is to split the string on whitespace and then rejoin without spaces.
s = 'A string with white space'''.join(s.split())#=> 'Astringwithwhitespace'
2 readers recommended a more pythonic way to handle this following the Python ethos that Explicit is better than Implicit. It’s also faster because python doesn’t create a new list object. Thanks Евгений Крамаров and Chrisjan Wust !
s = 'A string with white space's.replace(' ', '')#=> 'Astringwithwhitespace'
enumerate() allows tracking index when iterating over a sequence. It’s more pythonic than defining and incrementing an integer representing the index.
li = ['a','b','c','d','e']for idx,val in enumerate(li): print(idx, val)#=> 0 a#=> 1 b#=> 2 c#=> 3 d#=> 4 e
pass means do nothing. We typically use it because Python doesn’t allow creating a class, function or if-statement without code inside it.
In the example below, an error would be thrown without code inside the i > 3 so we use pass.
a = [1,2,3,4,5]for i in a: if i > 3: pass print(i)#=> 1#=> 2#=> 3#=> 4#=> 5
continue continues to the next element and halts execution for the current element. So print(i) is never reached for values where i < 3.
for i in a: if i < 3: continue print(i)#=> 3#=> 4#=> 5
break breaks the loop and the sequence is not longer iterated over. So elements from 3 onward are not printed.
for i in a: if i == 3: break print(i) #=> 1#=> 2
This for loop.
a = [1,2,3,4,5] a2 = []for i in a: a2.append(i + 1)print(a2)#=> [2, 3, 4, 5, 6]
Becomes.
a3 = [i+1 for i in a]print(a3)#=> [2, 3, 4, 5, 6]
List comprehension is generally accepted as more pythonic where it’s still readable.
The ternary operator is a one-line if/else statement.
The syntax looks like a if condition else b.
x = 5y = 10'greater' if x > 6 else 'less'#=> 'less''greater' if y > 6 else 'less'#=> 'greater'
You can use isnumeric().
'123a'.isnumeric()#=> False'123'.isnumeric()#=> True
You can use isalpha().
'123a'.isalpha()#=> False'a'.isalpha()#=> True
You can use isalnum().
'123abc...'.isalnum()#=> False'123abc'.isalnum()#=> True
This can be done by passing the dictionary to python’s list() constructor, list().
d = {'id':7, 'name':'Shiba', 'color':'brown', 'speed':'very slow'}list(d)#=> ['id', 'name', 'color', 'speed']
You can use the upper() and lower() string methods.
small_word = 'potatocake'big_word = 'FISHCAKE'small_word.upper()#=> 'POTATOCAKE'big_word.lower()#=> 'fishcake'
remove() remove the first matching value.
li = ['a','b','c','d']li.remove('b')li#=> ['a', 'c', 'd']
del removes an element by index.
li = ['a','b','c','d']del li[0]li#=> ['b', 'c', 'd']
pop() removes an element by index and returns that element.
li = ['a','b','c','d']li.pop(2)#=> 'c'li#=> ['a', 'b', 'd']
Below we’ll create dictionary with letters of the alphabet as keys, and index in the alphabet as values.
# creating a list of lettersimport stringlist(string.ascii_lowercase)alphabet = list(string.ascii_lowercase)# list comprehensiond = {val:idx for idx,val in enumerate(alphabet)} d#=> {'a': 0,#=> 'b': 1,#=> 'c': 2,#=> ...#=> 'x': 23,#=> 'y': 24,#=> 'z': 25}
Python provides 3 words to handle exceptions, try, except and finally.
The syntax looks like this.
try: # try to do thisexcept: # if try block fails then do thisfinally: # always do this
In the simplistic example below, the try block fails because we cannot add integers with strings. The except block sets val = 10 and then the finally block prints complete.
try: val = 1 + 'A'except: val = 10finally: print('complete') print(val)#=> complete#=> 10
You never know what questions will come up in interviews and the best way to prepare is to have a lot of experience writing code.
That said, this list should cover most anything you’ll be asked python-wise for a data scientist or junior/intermediate python developer roles.
I hope this was as helpful for you as writing it was for me.
Are there any great questions I missed?
|
[
{
"code": null,
"e": 285,
"s": 172,
"text": "Not so long ago I started a new role as a “Data Scientist” which turned out to be “Python Engineer” in practice."
},
{
"code": null,
"e": 407,
"s": 285,
"text": "I would have been more prepared if I’d brushed up on Python’s thread lifecycle instead of recommender systems in advance."
},
{
"code": null,
"e": 579,
"s": 407,
"text": "In that spirit, here are my python interview/job preparation questions and answers. Most data scientists write a lot code so this applies to both scientists and engineers."
},
{
"code": null,
"e": 715,
"s": 579,
"text": "Whether you’re interviewing candidates, preparing to apply to jobs or just brushing up on Python, I think this list will be invaluable."
},
{
"code": null,
"e": 753,
"s": 715,
"text": "Questions are unordered. Let’s begin."
},
{
"code": null,
"e": 883,
"s": 753,
"text": "I’ve been asked this question in every python / data science interview I’ve ever had. Know the answer like the back of your hand."
},
{
"code": null,
"e": 939,
"s": 883,
"text": "Lists are mutable. They can be modified after creation."
},
{
"code": null,
"e": 1006,
"s": 939,
"text": "Tuples are immutable. Once a tuple is created it cannot by changed"
},
{
"code": null,
"e": 1161,
"s": 1006,
"text": "Lists have order. They are an ordered sequences, typically of the same type of object. Ie: all user names ordered by creation date, [\"Seth\", \"Ema\", \"Eli\"]"
},
{
"code": null,
"e": 1311,
"s": 1161,
"text": "Tuples have structure. Different data types may exist at each index. Ie: a database record in memory, (2, \"Ema\", \"2020–04–16\") # id, name, created_at"
},
{
"code": null,
"e": 1390,
"s": 1311,
"text": "Without importing the Template class, there are 3 ways to interpolate strings."
},
{
"code": null,
"e": 1538,
"s": 1390,
"text": "name = 'Chris'# 1. f stringsprint(f'Hello {name}')# 2. % operatorprint('Hey %s %s' % (name, name))# 3. formatprint( \"My name is {}\".format((name)))"
},
{
"code": null,
"e": 1671,
"s": 1538,
"text": "Early in my python career I assumed these were the same... hello bugs. So for the record, is checks identity and == checks equality."
},
{
"code": null,
"e": 1799,
"s": 1671,
"text": "We’ll walk through an example. Create some lists and assign them to names. Note that b points to the same object as a in below."
},
{
"code": null,
"e": 1827,
"s": 1799,
"text": "a = [1,2,3]b = ac = [1,2,3]"
},
{
"code": null,
"e": 1871,
"s": 1827,
"text": "Check equality and note they are all equal."
},
{
"code": null,
"e": 1914,
"s": 1871,
"text": "print(a == b)print(a == c)#=> True#=> True"
},
{
"code": null,
"e": 1956,
"s": 1914,
"text": "But do they have the same identity? Nope."
},
{
"code": null,
"e": 2000,
"s": 1956,
"text": "print(a is b)print(a is c)#=> True#=> False"
},
{
"code": null,
"e": 2050,
"s": 2000,
"text": "We can verify this by printing their object id’s."
},
{
"code": null,
"e": 2129,
"s": 2050,
"text": "print(id(a))print(id(b))print(id(c))#=> 4369567560#=> 4369567560#=> 4369567624"
},
{
"code": null,
"e": 2164,
"s": 2129,
"text": "c has a different id than a and b."
},
{
"code": null,
"e": 2317,
"s": 2164,
"text": "Another questions I’ve been asked in every interview. It’s deserves a post itself, but you’re prepared if you can walk through writing your own example."
},
{
"code": null,
"e": 2496,
"s": 2317,
"text": "A decorator allows adding functionality to an existing function by passing that existing function to a decorator, which executes the existing function as well as additional code."
},
{
"code": null,
"e": 2568,
"s": 2496,
"text": "We’ll write a decorator that that logs when another function is called."
},
{
"code": null,
"e": 2800,
"s": 2568,
"text": "Write the decorator function. This takes a function, func, as an argument. It also defines a function, log_function_called, which calls func() and executes some code, print(f'{func} called.'). Then it return the function it defined"
},
{
"code": null,
"e": 2913,
"s": 2800,
"text": "def logging(func): def log_function_called(): print(f'{func} called.') func() return log_function_called"
},
{
"code": null,
"e": 2999,
"s": 2913,
"text": "Let’s write other functions that we’ll eventually add the decorator to (but not yet)."
},
{
"code": null,
"e": 3108,
"s": 2999,
"text": "def my_name(): print('chris')def friends_name(): print('naruto')my_name()friends_name()#=> chris#=> naruto"
},
{
"code": null,
"e": 3139,
"s": 3108,
"text": "Now add the decorator to both."
},
{
"code": null,
"e": 3357,
"s": 3139,
"text": "@loggingdef my_name(): print('chris')@loggingdef friends_name(): print('naruto')my_name()friends_name()#=> <function my_name at 0x10fca5a60> called.#=> chris#=> <function friends_name at 0x10fca5f28> called.#=> naruto"
},
{
"code": null,
"e": 3454,
"s": 3357,
"text": "See how we can now easily add logging to any function we write just by adding @logging above it."
},
{
"code": null,
"e": 3521,
"s": 3454,
"text": "Range generates a list of integers and there are 3 ways to use it."
},
{
"code": null,
"e": 3645,
"s": 3521,
"text": "The function takes 1 to 3 arguments. Note I’ve wrapped each usage in list comprehension so we can see the values generated."
},
{
"code": null,
"e": 3707,
"s": 3645,
"text": "range(stop) : generate integers from 0 to the “stop” integer."
},
{
"code": null,
"e": 3764,
"s": 3707,
"text": "[i for i in range(10)]#=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"
},
{
"code": null,
"e": 3843,
"s": 3764,
"text": "range(start, stop) : generate integers from the “start” to the “stop” integer."
},
{
"code": null,
"e": 3896,
"s": 3843,
"text": "[i for i in range(2,10)]#=> [2, 3, 4, 5, 6, 7, 8, 9]"
},
{
"code": null,
"e": 3988,
"s": 3896,
"text": "range(start, stop, step) : generate integers from “start” to “stop” at intervals of “step”."
},
{
"code": null,
"e": 4031,
"s": 3988,
"text": "[i for i in range(2,10,2)]#=> [2, 4, 6, 8]"
},
{
"code": null,
"e": 4102,
"s": 4031,
"text": "Thanks Searge Boremchuq for suggesting a more pythonic way to do this!"
},
{
"code": null,
"e": 4138,
"s": 4102,
"text": "list(range(2,10,2))#=> [2, 4, 6, 8]"
},
{
"code": null,
"e": 4285,
"s": 4138,
"text": "class Car : def __init__(self, color, speed): self.color = color self.speed = speedcar = Car('red','100mph')car.speed#=> '100mph'"
},
{
"code": null,
"e": 4374,
"s": 4285,
"text": "Instance methods : accept self parameter and relate to a specific instance of the class."
},
{
"code": null,
"e": 4527,
"s": 4374,
"text": "Static methods : use @staticmethod decorator, are not related to a specific instance, and are self-contained (don’t modify class or instance attributes)"
},
{
"code": null,
"e": 4596,
"s": 4527,
"text": "Class methods : accept cls parameter and can modify the class itself"
},
{
"code": null,
"e": 4674,
"s": 4596,
"text": "We’re going to illustrate the difference around a fictional CoffeeShop class."
},
{
"code": null,
"e": 5168,
"s": 4674,
"text": "class CoffeeShop: specialty = 'espresso' def __init__(self, coffee_price): self.coffee_price = coffee_price # instance method def make_coffee(self): print(f'Making {self.specialty} for ${self.coffee_price}') # static method @staticmethod def check_weather(): print('Its sunny') # class method @classmethod def change_specialty(cls, specialty): cls.specialty = specialty print(f'Specialty changed to {specialty}')"
},
{
"code": null,
"e": 5399,
"s": 5168,
"text": "CoffeeShop class has an attribute, specialty, set to 'espresso' by default. Each instance of CoffeeShop is initialized with an attribute coffee_price . It also has 3 methods, an instance method, a static method and a class method."
},
{
"code": null,
"e": 5516,
"s": 5399,
"text": "Let’s initialize an instance of the coffee shop with a coffee_price of 5. Then call the instance method make_coffee."
},
{
"code": null,
"e": 5597,
"s": 5516,
"text": "coffee_shop = CoffeeShop('5')coffee_shop.make_coffee()#=> Making espresso for $5"
},
{
"code": null,
"e": 5808,
"s": 5597,
"text": "Now call the static method. Static methods can’t modify class or instance state so they’re normally used for utility functions, for example, adding 2 numbers. We used ours to check the weather.Its sunny. Great!"
},
{
"code": null,
"e": 5849,
"s": 5808,
"text": "coffee_shop.check_weather()#=> Its sunny"
},
{
"code": null,
"e": 5940,
"s": 5849,
"text": "Now let’s use the class method to modify the coffee shop’s specialty and then make_coffee."
},
{
"code": null,
"e": 6074,
"s": 5940,
"text": "coffee_shop.change_specialty('drip coffee')#=> Specialty changed to drip coffeecoffee_shop.make_coffee()#=> Making drip coffee for $5"
},
{
"code": null,
"e": 6144,
"s": 6074,
"text": "Note how make_coffee used to make espresso but now makes drip coffee!"
},
{
"code": null,
"e": 6248,
"s": 6144,
"text": "The purpose of this question is to see if you understand that all functions are also objects in python."
},
{
"code": null,
"e": 6348,
"s": 6248,
"text": "def func(): print('Im a function') func#=> function __main__.func>func() #=> Im a function"
},
{
"code": null,
"e": 6532,
"s": 6348,
"text": "func is the object representing the function which can be assigned to a variable or passed to another function. func() with parentheses calls the function and returns what it outputs."
},
{
"code": null,
"e": 6727,
"s": 6532,
"text": "map returns a map object (an iterator) which can iterate over returned values from applying a function to every element in a sequence. The map object can also be converted to a list if required."
},
{
"code": null,
"e": 6817,
"s": 6727,
"text": "def add_three(x): return x + 3li = [1,2,3][i for i in map(add_three, li)]#=> [4, 5, 6]"
},
{
"code": null,
"e": 6864,
"s": 6817,
"text": "Above, I added 3 to every element in the list."
},
{
"code": null,
"e": 6938,
"s": 6864,
"text": "A reader suggested a more pythonic implementation. Thanks Chrisjan Wust !"
},
{
"code": null,
"e": 7021,
"s": 6938,
"text": "def add_three(x): return x + 3li = [1,2,3]list(map(add_three, li))#=> [4, 5, 6]"
},
{
"code": null,
"e": 7076,
"s": 7021,
"text": "Also, thanks Michael Graeme Short for the corrections!"
},
{
"code": null,
"e": 7150,
"s": 7076,
"text": "This can be tricky to wrap your head around until you use it a few times."
},
{
"code": null,
"e": 7371,
"s": 7150,
"text": "reduce takes a function and a sequence and iterates over that sequence. On each iteration, both the current element and output from the previous element are passed to the function. In the end, a single value is returned."
},
{
"code": null,
"e": 7476,
"s": 7371,
"text": "from functools import reducedef add_three(x,y): return x + yli = [1,2,3,5]reduce(add_three, li)#=> 11"
},
{
"code": null,
"e": 7520,
"s": 7476,
"text": "11 is returned which is the sum of 1+2+3+5."
},
{
"code": null,
"e": 7597,
"s": 7520,
"text": "Filter literally does what the name says. It filters elements in a sequence."
},
{
"code": null,
"e": 7752,
"s": 7597,
"text": "Each element is passed to a function which is returned in the outputted sequence if the function returns True and discarded if the function returns False."
},
{
"code": null,
"e": 7916,
"s": 7752,
"text": "def add_three(x): if x % 2 == 0: return True else: return Falseli = [1,2,3,4,5,6,7,8][i for i in filter(add_three, li)]#=> [2, 4, 6, 8]"
},
{
"code": null,
"e": 7976,
"s": 7916,
"text": "Note how all elements not divisible by 2 have been removed."
},
{
"code": null,
"e": 8082,
"s": 7976,
"text": "Be prepared to go down a rabbit hole of semantics if you google this question and read the top few pages."
},
{
"code": null,
"e": 8223,
"s": 8082,
"text": "In a nutshell, all names call by reference, but some memory locations hold objects while others hold pointers to yet other memory locations."
},
{
"code": null,
"e": 8239,
"s": 8223,
"text": "name = 'object'"
},
{
"code": null,
"e": 8368,
"s": 8239,
"text": "Let’s see how this works with strings. We’ll instantiate a name and object, point other names to it. Then delete the first name."
},
{
"code": null,
"e": 8498,
"s": 8368,
"text": "x = 'some text'y = xx is y #=> Truedel x # this deletes the 'a' name but does nothing to the object in memoryz = yy is z #=> True"
},
{
"code": null,
"e": 8602,
"s": 8498,
"text": "What we see is that all these names point to the same object in memory, which wasn’t affected by del x."
},
{
"code": null,
"e": 8654,
"s": 8602,
"text": "Here’s another interesting example with a function."
},
{
"code": null,
"e": 9040,
"s": 8654,
"text": "name = 'text'def add_chars(str1): print( id(str1) ) #=> 4353702856 print( id(name) ) #=> 4353702856 # new name, same object str2 = str1 # creates a new name (with same name as the first) AND object str1 += 's' print( id(str1) ) #=> 4387143328 # still the original object print( id(str2) ) #=> 4353702856 add_chars(name)print(name) #=>text"
},
{
"code": null,
"e": 9201,
"s": 9040,
"text": "Notice how adding an s to the string inside the function created a new name AND a new object. Even though the new name has the same “name” as the existing name."
},
{
"code": null,
"e": 9247,
"s": 9201,
"text": "Thanks Michael P. Reilly for the corrections!"
},
{
"code": null,
"e": 9347,
"s": 9247,
"text": "Note how reverse() is called on the list and mutates it. It doesn’t return the mutated list itself."
},
{
"code": null,
"e": 9434,
"s": 9347,
"text": "li = ['a','b','c']print(li)li.reverse()print(li)#=> ['a', 'b', 'c']#=> ['c', 'b', 'a']"
},
{
"code": null,
"e": 9494,
"s": 9434,
"text": "Let’s see the results of multiplying the string ‘cat’ by 3."
},
{
"code": null,
"e": 9519,
"s": 9494,
"text": "'cat' * 3#=> 'catcatcat'"
},
{
"code": null,
"e": 9565,
"s": 9519,
"text": "The string is concatenated to itself 3 times."
},
{
"code": null,
"e": 9623,
"s": 9565,
"text": "Let’s see the result of multiplying a list, [1,2,3] by 2."
},
{
"code": null,
"e": 9657,
"s": 9623,
"text": "[1,2,3] * 2#=> [1, 2, 3, 1, 2, 3]"
},
{
"code": null,
"e": 9728,
"s": 9657,
"text": "A list is outputted containing the contents of [1,2,3] repeated twice."
},
{
"code": null,
"e": 9865,
"s": 9728,
"text": "Self refers to the instance of the class itself. It’s how we give methods access to and the ability to update the object they belong to."
},
{
"code": null,
"e": 9971,
"s": 9865,
"text": "Below, passing self to __init__() gives us the ability to set the color of an instance on initialization."
},
{
"code": null,
"e": 10086,
"s": 9971,
"text": "class Shirt: def __init__(self, color): self.color = color s = Shirt('yellow')s.color#=> 'yellow'"
},
{
"code": null,
"e": 10176,
"s": 10086,
"text": "Adding 2 lists together concatenates them. Note that arrays do not function the same way."
},
{
"code": null,
"e": 10221,
"s": 10176,
"text": "a = [1,2]b = [3,4,5]a + b#=> [1, 2, 3, 4, 5]"
},
{
"code": null,
"e": 10342,
"s": 10221,
"text": "We’ll discuss this in the context of a mutable object, a list. For immutable objects, shallow vs deep isn’t as relevant."
},
{
"code": null,
"e": 10374,
"s": 10342,
"text": "We’ll walk through 3 scenarios."
},
{
"code": null,
"e": 10535,
"s": 10374,
"text": "i) Reference the original object. This points a new name, li2, to the same place in memory to which li1 points. So any change we make to li1 also occurs to li2."
},
{
"code": null,
"e": 10629,
"s": 10535,
"text": "li1 = [['a'],['b'],['c']]li2 = li1li1.append(['d'])print(li2)#=> [['a'], ['b'], ['c'], ['d']]"
},
{
"code": null,
"e": 10777,
"s": 10629,
"text": "ii) Create a shallow copy of the original. We can do this with the list() constructor, or the more pythonic mylist.copy() (thanks Chrisjan Wust !)."
},
{
"code": null,
"e": 11005,
"s": 10777,
"text": "A shallow copy creates a new object, but fills it with references to the original. So adding a new object to the original collection, li3, doesn’t propagate to li4, but modifying one of the objects in li3 will propagate to li4."
},
{
"code": null,
"e": 11150,
"s": 11005,
"text": "li3 = [['a'],['b'],['c']]li4 = list(li3)li3.append([4])print(li4)#=> [['a'], ['b'], ['c']]li3[0][0] = ['X']print(li4)#=> [[['X']], ['b'], ['c']]"
},
{
"code": null,
"e": 11306,
"s": 11150,
"text": "iii) Create a deep copy. This is done with copy.deepcopy(). The 2 objects are now completely independent and changes to either have no affect on the other."
},
{
"code": null,
"e": 11434,
"s": 11306,
"text": "import copyli5 = [['a'],['b'],['c']]li6 = copy.deepcopy(li5)li5.append([4])li5[0][0] = ['X']print(li6)#=> [['a'], ['b'], ['c']]"
},
{
"code": null,
"e": 11556,
"s": 11434,
"text": "Note: Python’s standard library has an array object but here I’m specifically referring to the commonly used Numpy array."
},
{
"code": null,
"e": 11627,
"s": 11556,
"text": "Lists exist in python’s standard library. Arrays are defined by Numpy."
},
{
"code": null,
"e": 11731,
"s": 11627,
"text": "Lists can be populated with different types of data at each index. Arrays require homogeneous elements."
},
{
"code": null,
"e": 11842,
"s": 11731,
"text": "Arithmetic on lists adds or removes elements from the list. Arithmetic on arrays functions per linear algebra."
},
{
"code": null,
"e": 11918,
"s": 11842,
"text": "Arrays also use less memory and come with significantly more functionality."
},
{
"code": null,
"e": 11964,
"s": 11918,
"text": "I wrote another comprehensive post on arrays."
},
{
"code": null,
"e": 12064,
"s": 11964,
"text": "Remember, arrays are not lists. Arrays are from Numpy and arithmetic functions like linear algebra."
},
{
"code": null,
"e": 12118,
"s": 12064,
"text": "We need to use Numpy’s concatenate function to do it."
},
{
"code": null,
"e": 12229,
"s": 12118,
"text": "import numpy as npa = np.array([1,2,3])b = np.array([4,5,6])np.concatenate((a,b))#=> array([1, 2, 3, 4, 5, 6])"
},
{
"code": null,
"e": 12348,
"s": 12229,
"text": "Note this is a very subjective question and you’ll want to modify your response based on what the role is looking for."
},
{
"code": null,
"e": 12481,
"s": 12348,
"text": "Python is very readable and there is a pythonic way to do just about everything, meaning a preferred way which is clear and concise."
},
{
"code": null,
"e": 12599,
"s": 12481,
"text": "I’d contrast this to Ruby where there are often many ways to do something without a guideline for which is preferred."
},
{
"code": null,
"e": 12633,
"s": 12599,
"text": "Also subjective, see question 21."
},
{
"code": null,
"e": 12757,
"s": 12633,
"text": "When working with a lot data, nothing is quite as helpful as pandas which makes manipulating and visualizing data a breeze."
},
{
"code": null,
"e": 12868,
"s": 12757,
"text": "Immutable means the state cannot be modified after creation. Examples are: int, float, bool, string and tuple."
},
{
"code": null,
"e": 12957,
"s": 12868,
"text": "Mutable means the state can be modified after creation. Examples are list, dict and set."
},
{
"code": null,
"e": 13004,
"s": 12957,
"text": "Use the round(value, decimal_places) function."
},
{
"code": null,
"e": 13035,
"s": 13004,
"text": "a = 5.12345round(a,3)#=> 5.123"
},
{
"code": null,
"e": 13153,
"s": 13035,
"text": "Slicing notation takes 3 arguments, list[start:stop:step], where step is the interval at which elements are returned."
},
{
"code": null,
"e": 13286,
"s": 13153,
"text": "a = [0,1,2,3,4,5,6,7,8,9]print(a[:2])#=> [0, 1]print(a[8:])#=> [8, 9]print(a[2:8])#=> [2, 3, 4, 5, 6, 7]print(a[2:8:2])#=> [2, 4, 6]"
},
{
"code": null,
"e": 13367,
"s": 13286,
"text": "Pickling is the go-to method of serializing and unserializing objects in Python."
},
{
"code": null,
"e": 13442,
"s": 13367,
"text": "In the example below, we serialize and unserialize a list of dictionaries."
},
{
"code": null,
"e": 13719,
"s": 13442,
"text": "import pickleobj = [ {'id':1, 'name':'Stuffy'}, {'id':2, 'name': 'Fluffy'}]with open('file.p', 'wb') as f: pickle.dump(obj, f)with open('file.p', 'rb') as f: loaded_obj = pickle.load(f)print(loaded_obj)#=> [{'id': 1, 'name': 'Stuffy'}, {'id': 2, 'name': 'Fluffy'}]"
},
{
"code": null,
"e": 13799,
"s": 13719,
"text": "Dict is python datatype, a collection of indexed but unordered keys and values."
},
{
"code": null,
"e": 13893,
"s": 13799,
"text": "JSON is just a string which follows a specified format and is intended for transferring data."
},
{
"code": null,
"e": 14019,
"s": 13893,
"text": "ORMs (object relational mapping) map data models (usually in an app) to database tables and simplifies database transactions."
},
{
"code": null,
"e": 14102,
"s": 14019,
"text": "SQLAlchemy is typically used in the context of Flask, and Django has it’s own ORM."
},
{
"code": null,
"e": 14180,
"s": 14102,
"text": "Any takes a sequence and returns true if any element in the sequence is true."
},
{
"code": null,
"e": 14244,
"s": 14180,
"text": "All returns true only if all elements in the sequence are true."
},
{
"code": null,
"e": 14457,
"s": 14244,
"text": "a = [False, False, False]b = [True, False, False]c = [True, True, True]print( any(a) )print( any(b) )print( any(c) )#=> False#=> True#=> Trueprint( all(a) )print( all(b) )print( all(c) )#=> False#=> False#=> True"
},
{
"code": null,
"e": 14580,
"s": 14457,
"text": "Looking up a value in a list takes O(n) time because the whole list needs to be iterated through until the value is found."
},
{
"code": null,
"e": 14656,
"s": 14580,
"text": "Looking up a key in a dictionary takes O(1) time because it’s a hash table."
},
{
"code": null,
"e": 14836,
"s": 14656,
"text": "This can make a huge time difference if there are a lot of values so dictionaries are generally recommended for speed. But they do have other limitations like needing unique keys."
},
{
"code": null,
"e": 14911,
"s": 14836,
"text": "A module is a file (or collection of files) that can be imported together."
},
{
"code": null,
"e": 14926,
"s": 14911,
"text": "import sklearn"
},
{
"code": null,
"e": 14963,
"s": 14926,
"text": "A package is a directory of modules."
},
{
"code": null,
"e": 15000,
"s": 14963,
"text": "from sklearn import cross_validation"
},
{
"code": null,
"e": 15059,
"s": 15000,
"text": "So packages are modules, but not all modules are packages."
},
{
"code": null,
"e": 15114,
"s": 15059,
"text": "Increments and decrements can be done with +- and -= ."
},
{
"code": null,
"e": 15188,
"s": 15114,
"text": "value = 5value += 1print(value)#=> 6value -= 1value -= 1print(value)#=> 4"
},
{
"code": null,
"e": 15212,
"s": 15188,
"text": "Use the bin() function."
},
{
"code": null,
"e": 15230,
"s": 15212,
"text": "bin(5)#=> '0b101'"
},
{
"code": null,
"e": 15300,
"s": 15230,
"text": "This can be done by converting the list to a set then back to a list."
},
{
"code": null,
"e": 15353,
"s": 15300,
"text": "a = [1,1,1,2,3]a = list(set(a))print(a)#=> [1, 2, 3]"
},
{
"code": null,
"e": 15419,
"s": 15353,
"text": "Note that sets will not necessarily maintain the order of a list."
},
{
"code": null,
"e": 15427,
"s": 15419,
"text": "Use in."
},
{
"code": null,
"e": 15479,
"s": 15427,
"text": "'a' in ['a','b','c']#=> True'a' in [1,2,3]#=> False"
},
{
"code": null,
"e": 15561,
"s": 15479,
"text": "append adds a value to a list while extend adds values in another list to a list."
},
{
"code": null,
"e": 15661,
"s": 15561,
"text": "a = [1,2,3]b = [1,2,3]a.append(6)print(a)#=> [1, 2, 3, 6]b.extend([4,5])print(b)#=> [1, 2, 3, 4, 5]"
},
{
"code": null,
"e": 15703,
"s": 15661,
"text": "This can be done with the abs() function."
},
{
"code": null,
"e": 15727,
"s": 15703,
"text": "abs(2)#=> 2abs(-2)#=> 2"
},
{
"code": null,
"e": 15877,
"s": 15727,
"text": "You can use the zip function to combine lists into a list of tuples. This isn’t restricted to only using 2 lists. It can also be done with 3 or more."
},
{
"code": null,
"e": 15967,
"s": 15877,
"text": "a = ['a','b','c']b = [1,2,3][(k,v) for k,v in zip(a,b)]#=> [('a', 1), ('b', 2), ('c', 3)]"
},
{
"code": null,
"e": 16136,
"s": 15967,
"text": "You can’t “sort” a dictionary because dictionaries don’t have order but you can return a sorted list of tuples which has the keys and values that are in the dictionary."
},
{
"code": null,
"e": 16230,
"s": 16136,
"text": "d = {'c':3, 'd':4, 'b':2, 'a':1}sorted(d.items())#=> [('a', 1), ('b', 2), ('c', 3), ('d', 4)]"
},
{
"code": null,
"e": 16351,
"s": 16230,
"text": "In the below example, Audi, inherits from Car. And with that inheritance comes the instance methods of the parent class."
},
{
"code": null,
"e": 16455,
"s": 16351,
"text": "class Car(): def drive(self): print('vroom')class Audi(Car): passaudi = Audi()audi.drive()"
},
{
"code": null,
"e": 16540,
"s": 16455,
"text": "The easiest way is to split the string on whitespace and then rejoin without spaces."
},
{
"code": null,
"e": 16621,
"s": 16540,
"text": "s = 'A string with white space'''.join(s.split())#=> 'Astringwithwhitespace'"
},
{
"code": null,
"e": 16855,
"s": 16621,
"text": "2 readers recommended a more pythonic way to handle this following the Python ethos that Explicit is better than Implicit. It’s also faster because python doesn’t create a new list object. Thanks Евгений Крамаров and Chrisjan Wust !"
},
{
"code": null,
"e": 16936,
"s": 16855,
"text": "s = 'A string with white space's.replace(' ', '')#=> 'Astringwithwhitespace'"
},
{
"code": null,
"e": 17087,
"s": 16936,
"text": "enumerate() allows tracking index when iterating over a sequence. It’s more pythonic than defining and incrementing an integer representing the index."
},
{
"code": null,
"e": 17197,
"s": 17087,
"text": "li = ['a','b','c','d','e']for idx,val in enumerate(li): print(idx, val)#=> 0 a#=> 1 b#=> 2 c#=> 3 d#=> 4 e"
},
{
"code": null,
"e": 17336,
"s": 17197,
"text": "pass means do nothing. We typically use it because Python doesn’t allow creating a class, function or if-statement without code inside it."
},
{
"code": null,
"e": 17429,
"s": 17336,
"text": "In the example below, an error would be thrown without code inside the i > 3 so we use pass."
},
{
"code": null,
"e": 17518,
"s": 17429,
"text": "a = [1,2,3,4,5]for i in a: if i > 3: pass print(i)#=> 1#=> 2#=> 3#=> 4#=> 5"
},
{
"code": null,
"e": 17655,
"s": 17518,
"text": "continue continues to the next element and halts execution for the current element. So print(i) is never reached for values where i < 3."
},
{
"code": null,
"e": 17723,
"s": 17655,
"text": "for i in a: if i < 3: continue print(i)#=> 3#=> 4#=> 5"
},
{
"code": null,
"e": 17834,
"s": 17723,
"text": "break breaks the loop and the sequence is not longer iterated over. So elements from 3 onward are not printed."
},
{
"code": null,
"e": 17899,
"s": 17834,
"text": "for i in a: if i == 3: break print(i) #=> 1#=> 2"
},
{
"code": null,
"e": 17914,
"s": 17899,
"text": "This for loop."
},
{
"code": null,
"e": 17998,
"s": 17914,
"text": "a = [1,2,3,4,5] a2 = []for i in a: a2.append(i + 1)print(a2)#=> [2, 3, 4, 5, 6]"
},
{
"code": null,
"e": 18007,
"s": 17998,
"text": "Becomes."
},
{
"code": null,
"e": 18057,
"s": 18007,
"text": "a3 = [i+1 for i in a]print(a3)#=> [2, 3, 4, 5, 6]"
},
{
"code": null,
"e": 18142,
"s": 18057,
"text": "List comprehension is generally accepted as more pythonic where it’s still readable."
},
{
"code": null,
"e": 18196,
"s": 18142,
"text": "The ternary operator is a one-line if/else statement."
},
{
"code": null,
"e": 18241,
"s": 18196,
"text": "The syntax looks like a if condition else b."
},
{
"code": null,
"e": 18336,
"s": 18241,
"text": "x = 5y = 10'greater' if x > 6 else 'less'#=> 'less''greater' if y > 6 else 'less'#=> 'greater'"
},
{
"code": null,
"e": 18361,
"s": 18336,
"text": "You can use isnumeric()."
},
{
"code": null,
"e": 18414,
"s": 18361,
"text": "'123a'.isnumeric()#=> False'123'.isnumeric()#=> True"
},
{
"code": null,
"e": 18437,
"s": 18414,
"text": "You can use isalpha()."
},
{
"code": null,
"e": 18484,
"s": 18437,
"text": "'123a'.isalpha()#=> False'a'.isalpha()#=> True"
},
{
"code": null,
"e": 18507,
"s": 18484,
"text": "You can use isalnum()."
},
{
"code": null,
"e": 18564,
"s": 18507,
"text": "'123abc...'.isalnum()#=> False'123abc'.isalnum()#=> True"
},
{
"code": null,
"e": 18647,
"s": 18564,
"text": "This can be done by passing the dictionary to python’s list() constructor, list()."
},
{
"code": null,
"e": 18757,
"s": 18647,
"text": "d = {'id':7, 'name':'Shiba', 'color':'brown', 'speed':'very slow'}list(d)#=> ['id', 'name', 'color', 'speed']"
},
{
"code": null,
"e": 18809,
"s": 18757,
"text": "You can use the upper() and lower() string methods."
},
{
"code": null,
"e": 18920,
"s": 18809,
"text": "small_word = 'potatocake'big_word = 'FISHCAKE'small_word.upper()#=> 'POTATOCAKE'big_word.lower()#=> 'fishcake'"
},
{
"code": null,
"e": 18962,
"s": 18920,
"text": "remove() remove the first matching value."
},
{
"code": null,
"e": 19020,
"s": 18962,
"text": "li = ['a','b','c','d']li.remove('b')li#=> ['a', 'c', 'd']"
},
{
"code": null,
"e": 19053,
"s": 19020,
"text": "del removes an element by index."
},
{
"code": null,
"e": 19106,
"s": 19053,
"text": "li = ['a','b','c','d']del li[0]li#=> ['b', 'c', 'd']"
},
{
"code": null,
"e": 19166,
"s": 19106,
"text": "pop() removes an element by index and returns that element."
},
{
"code": null,
"e": 19226,
"s": 19166,
"text": "li = ['a','b','c','d']li.pop(2)#=> 'c'li#=> ['a', 'b', 'd']"
},
{
"code": null,
"e": 19331,
"s": 19226,
"text": "Below we’ll create dictionary with letters of the alphabet as keys, and index in the alphabet as values."
},
{
"code": null,
"e": 19592,
"s": 19331,
"text": "# creating a list of lettersimport stringlist(string.ascii_lowercase)alphabet = list(string.ascii_lowercase)# list comprehensiond = {val:idx for idx,val in enumerate(alphabet)} d#=> {'a': 0,#=> 'b': 1,#=> 'c': 2,#=> ...#=> 'x': 23,#=> 'y': 24,#=> 'z': 25}"
},
{
"code": null,
"e": 19663,
"s": 19592,
"text": "Python provides 3 words to handle exceptions, try, except and finally."
},
{
"code": null,
"e": 19691,
"s": 19663,
"text": "The syntax looks like this."
},
{
"code": null,
"e": 19788,
"s": 19691,
"text": "try: # try to do thisexcept: # if try block fails then do thisfinally: # always do this"
},
{
"code": null,
"e": 19961,
"s": 19788,
"text": "In the simplistic example below, the try block fails because we cannot add integers with strings. The except block sets val = 10 and then the finally block prints complete."
},
{
"code": null,
"e": 20063,
"s": 19961,
"text": "try: val = 1 + 'A'except: val = 10finally: print('complete') print(val)#=> complete#=> 10"
},
{
"code": null,
"e": 20193,
"s": 20063,
"text": "You never know what questions will come up in interviews and the best way to prepare is to have a lot of experience writing code."
},
{
"code": null,
"e": 20337,
"s": 20193,
"text": "That said, this list should cover most anything you’ll be asked python-wise for a data scientist or junior/intermediate python developer roles."
},
{
"code": null,
"e": 20398,
"s": 20337,
"text": "I hope this was as helpful for you as writing it was for me."
}
] |
Find all divisors of a natural number in java
|
Following is the Java program which prints all the divisors of a given number.
import java.util.Scanner;
public class DivisorsOfNaturalNumber {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter required number :");
int num = sc.nextInt();
for(int i = 1; i<num; i++) {
if(num % i == 0) {
System.out.println(" "+i);
}
}
}
}
Enter required number :
200
1
2
4
5
8
10
20
25
40
50
100
|
[
{
"code": null,
"e": 1141,
"s": 1062,
"text": "Following is the Java program which prints all the divisors of a given number."
},
{
"code": null,
"e": 1511,
"s": 1141,
"text": "import java.util.Scanner;\n\npublic class DivisorsOfNaturalNumber {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter required number :\");\n int num = sc.nextInt();\n \n for(int i = 1; i<num; i++) {\n if(num % i == 0) {\n System.out.println(\" \"+i);\n }\n }\n }\n}"
},
{
"code": null,
"e": 1568,
"s": 1511,
"text": "Enter required number :\n200\n1\n2\n4\n5\n8\n10\n20\n25\n40\n50\n100"
}
] |
Time Series Forecasting using TensorFlow and Deep Hybrid Learning | by Aditya Bhattacharya | Towards Data Science
|
In my previous TDS article I described about the Machine Learning variant of Deep Hybrid Learning and how easily it can be applied for image data. If you are someone who is new to the concept of Deep Hybrid Learning, I would highly recommend you to have a look at the session recording of my past session at GIDS AI/ML 2020 conference. The recording video can also be directly accessed from my youtube channel.
In this article, we will see how Deep Hybrid Learning can be applied for time series data and whether it is as effective as it is with image data. But before we begin, in case if you are very new to time series data, I would recommend looking at my previous posts related to time series data analysis:
Time Series Anomaly DetectionTime Series SegmentationPreparing time series data from SQLTime Series 101 with R and Python
Time Series Anomaly Detection
Time Series Segmentation
Preparing time series data from SQL
Time Series 101 with R and Python
If you are new to TensorFlow and wondering how to apply TensorFlow for time series forecasting, this article from my website can be really helpful. The article does give very detailed code walkthrough of using TensorFlow for time series prediction. In this article also, I will take a similar approach of providing a very detailed approach for using Deep Hybrid Learning for Time Series Forecasting in 5 simple steps.
For this post, I am going to use the same Sunspot Data from Kaggle like my previous article. As mentioned there, the data can be easily downloaded from my GitHub project TimeSeries-Using-TensorFlow. I will encourage everyone to use google colab notebooks where the modules required are already installed and the infrastructure is ready for use. Now, let’s get started!
The data can be downloaded using a simple command in google colab –
!wget — no-check-certificate https://raw.githubusercontent.com/adib0073/TimeSeries-Using-TensorFlow/main/Data/Sunspots.csv -O /tmp/sunspots.csv
Once the download is complete, we can use pandas to load the data into dataframes.
# Loading the data as a pandas dataframe df = pd.read_csv(‘/tmp/sunspots.csv’, index_col=0) df.head()
We can take a glance at the data, which looks like this:
Now, ideally we should do an extensive Exploratory Data Analysis (EDA) to understand the trend, seasonality of the data. But for this case, to keep things simple, we will do a visual inspection for the data.
In this step we have to transform the loaded data and process it so that it can be passed as an input to the Deep Hybrid Learning model after which we can start the training process. We can consider time series forecasting as a sequential machine learning regression problem, and the time series data is converted into a set of feature values and the corresponding true or target value. Since regression is a supervised learning problem, we need the target value, in which the lagged time series data becomes the feature values like this:
We will follow a window or buffer approach in which we would have to consider an appropriate window size. Then we would move the window from left to right of the sequence or the series data. We will consider the value immediately to right of the window frame as target or the true value. So, each time-step we will shift or move the window so as to get a new row of features values and target value pairs. In this way we form the training data and training labels. In a similar way, we form the test and the validation dataset, which is typically required for a machine learning prediction model. Also, remember that for a predictive model, having a wider observation window and a narrow prediction window can give better results. Next, for the train-test-validation split ratio we will have to figure that out based on the size of the data. For this example I have used a split ratio of 0.8 and based on the seasonality of the data, we have taken a window size of 60. But these variables are all hyper-parameters, which requires some tuning to get the best possible results.
The code for the same is as follows:
# Convert the data values to numpy for better and faster processing time_index = np.array(df['Date']) data = np.array(df['Monthly Mean Total Sunspot Number']) # Certain Hyper-parameters to tune SPLIT_RATIO = 0.8 WINDOW_SIZE = 60 BATCH_SIZE = 32 SHUFFLE_BUFFER = 1000 # Dividing into train-test split split_index = int(SPLIT_RATIO * data.shape[0]) # Train-Test Split train_data = data[:split_index] train_time = time_index[:split_index] test_data = data[split_index:] test_time = time_index[split_index:]
Next, we will prepare a data generator that prepares the training and testing data for us.
def ts_data_generator(data, window_size, batch_size, shuffle_buffer): ''' Utility function for time series data generation in batches ''' ts_data = tf.data.Dataset.from_tensor_slices(data) ts_data = ts_data.window(window_size + 1, shift=1, drop_remainder=True) ts_data = ts_data.flat_map(lambda window: window.batch(window_size + 1)) ts_data = ts_data.shuffle(shuffle_buffer).map(lambda window: (window[:-1], window[-1])) ts_data = ts_data.batch(batch_size).prefetch(1) return ts_data# Expanding data into tensorstensor_train_data = tf.expand_dims(train_data, axis=-1)tensor_test_data = tf.expand_dims(test_data, axis=-1)tensor_train_dataset = ts_data_generator(tensor_train_data, WINDOW_SIZE, BATCH_SIZE, SHUFFLE_BUFFER)tensor_test_dataset = ts_data_generator(tensor_test_data, WINDOW_SIZE, BATCH_SIZE, SHUFFLE_BUFFER)
Now, we have our processed data ready for feeding this into our model.
We will use a simple version of a Deep Hybrid Learning architecture for this problem. As discussed we will use the Deep Learning variant with Late Fusion technique. The model architecture looks like this:
Here we have used a combination model of 1D CNN for extracting the initial sequential features and then combined with 2 LSTM layers for the feature extraction part and finally passed the same into tradional DNN Fully Connected Layers to produce the final output.
The code for the model architecture looks like this:
# DHL Fusion model of 1D CNN and LSTM model = tf.keras.models.Sequential([tf.keras.layers.Conv1D(filters=32, kernel_size=5,strides=1, padding="causal",activation="relu", input_shape=[None, 1]),tf.keras.layers.LSTM(64, return_sequences=True), tf.keras.layers.LSTM(64, return_sequences=True), tf.keras.layers.Dense(30, activation="relu"), tf.keras.layers.Dense(10, activation="relu"), tf.keras.layers.Dense(1)])
Next we would need to choose other hyper-parameters like learning rate, optimizer and loss function. I am not covering the intuition behind selection of these values in this post so as to keep it simple. But feel free to comment or drop me a note in this if you are curious to find out more about this.
optimizer = tf.keras.optimizers.SGD(lr=1e-4, momentum=0.9)model.compile(loss=tf.keras.losses.Huber(), optimizer=optimizer, metrics=["mae"])history = model.fit(tensor_train_dataset, epochs=200, validation_data=tensor_test_dataset)
Next we would see how to evaluate our model. But first, after the training process, it is always a better idea to plot the model loss curves to see whether the model is actually learning.
From the model loss curves, we do see clear presence of over-fitting. At the end of the article I will give some hint of how to handle this to make the model better, but we can see the model loss is decreasing with more training time, which is a good indication that the model is learning.
Now, for the model evaluation we would need to pick a metric. In a future article, I will include about various model evaluation metrics for time series data. But for this case, we will use MAE as the metric.
def model_forecast(model, data, window_size): ds = tf.data.Dataset.from_tensor_slices(data) ds = ds.window(window_size, shift=1, drop_remainder=True) ds = ds.flat_map(lambda w: w.batch(window_size)) ds = ds.batch(32).prefetch(1) forecast = model.predict(ds) return forecastrnn_forecast = model_forecast(model, data[..., np.newaxis], WINDOW_SIZE) rnn_forecast = rnn_forecast[split_index - WINDOW_SIZE:-1, -1, 0]# Overall Errorerror = tf.keras.metrics.mean_absolute_error(test_data, rnn_forecast).numpy()print(error)
The MAE value that we got is roughly around 40. Which is not bad, but a little high for this case. And the reason why the model error is more is because of the initial over-fitting that we saw.
As a final step, let’s visualize the results that we are getting over the test data and let’s inspect if at all the model is close for predicting good results.
From the first plot, we can see that the predicted values does follow a similar seasonal pattern and trend as the actual values, but the peaks are not as high as the actual ones. Also, since time series forecast should be ranged prediction not a single point estimate, we will use the error rate to form the confidence interval or the confidence band. We can see the the error bands are wide, which means the model is not very much confident and might have some prediction error.
The code for visualization is as follows:
plt.figure(figsize=(15, 6)) plt.plot(list(range(split_index,len(data))), test_data, label = 'Test Data') plt.plot(list(range(split_index,len(data))), rnn_forecast, label = 'Predictions') plt.legend() plt.show() plt.figure(figsize=(15, 6)) # Plotting with Confidence Intervals plt.plot(list(range(split_index,len(data))), rnn_forecast, label = 'Predictions', color = 'k', linestyle = '--')plt.fill_between(range(split_index,len(data)), rnn_forecast - error, rnn_forecast + error, alpha = 0.5, color = 'orange') plt.legend() plt.show()
And thus we do have a Deep Hybrid Learning model for time series forecasting and we have used TensorFlow for forming the model and implementing the flow.
But if you are wondering how can the result be improved, I have the following recommendations for you:
Change the window size (either increase or decrease)Use more training data (so as to solve the over-fitting problem)Use more model layers or more hidden unitsUse a different loss function and learning rateWe saw that the loss curve is not smooth. It usually happens if the batch size is small, so try with a bigger batch size.
Change the window size (either increase or decrease)
Use more training data (so as to solve the over-fitting problem)
Use more model layers or more hidden units
Use a different loss function and learning rate
We saw that the loss curve is not smooth. It usually happens if the batch size is small, so try with a bigger batch size.
Also sometimes, a simpler model may give better result. In my post Time Series Forecasting using Deep Learning with TensorFlow I got much better results just by using a simple Deep Neural Network. Now, unlike with image data, we saw that with time series data, Deep Hybrid Learner was not significantly better than a conventional Deep Learning, Machine Learning or Statistical methods. But, yes after doing thorough hyper parameter tuning, I am sure the results would be much better!
Thus, this brings us to the end of this article. The full working code and notebook can be obtained from here. Keep following me: https://medium.com/@adib0073 and my website: https://www.aditya-bhattacharya.net/ for more! Please feel free to reach for any query or comment!
**Update**: I am working on a book on applied computer vision in python and looking for contributors who can contribute in writing or reviewing content and code. Mostly I am interested to take in Graduate students and help them become an Applied Computer Vision expert by writing a book and maintaining an open source project! Please take a look at this article of mine to know more: Link. If you want to take a look at the early efforts of the initiative, please take a look my detailed hands-on workshop on applied computer vision in youtube. If you are interested to be a part of this please feel free to reach out through any mode of communication mentioned here: https://aditya-bhattacharya.net/contact-me/ with your updated resume.
|
[
{
"code": null,
"e": 583,
"s": 172,
"text": "In my previous TDS article I described about the Machine Learning variant of Deep Hybrid Learning and how easily it can be applied for image data. If you are someone who is new to the concept of Deep Hybrid Learning, I would highly recommend you to have a look at the session recording of my past session at GIDS AI/ML 2020 conference. The recording video can also be directly accessed from my youtube channel."
},
{
"code": null,
"e": 885,
"s": 583,
"text": "In this article, we will see how Deep Hybrid Learning can be applied for time series data and whether it is as effective as it is with image data. But before we begin, in case if you are very new to time series data, I would recommend looking at my previous posts related to time series data analysis:"
},
{
"code": null,
"e": 1007,
"s": 885,
"text": "Time Series Anomaly DetectionTime Series SegmentationPreparing time series data from SQLTime Series 101 with R and Python"
},
{
"code": null,
"e": 1037,
"s": 1007,
"text": "Time Series Anomaly Detection"
},
{
"code": null,
"e": 1062,
"s": 1037,
"text": "Time Series Segmentation"
},
{
"code": null,
"e": 1098,
"s": 1062,
"text": "Preparing time series data from SQL"
},
{
"code": null,
"e": 1132,
"s": 1098,
"text": "Time Series 101 with R and Python"
},
{
"code": null,
"e": 1550,
"s": 1132,
"text": "If you are new to TensorFlow and wondering how to apply TensorFlow for time series forecasting, this article from my website can be really helpful. The article does give very detailed code walkthrough of using TensorFlow for time series prediction. In this article also, I will take a similar approach of providing a very detailed approach for using Deep Hybrid Learning for Time Series Forecasting in 5 simple steps."
},
{
"code": null,
"e": 1919,
"s": 1550,
"text": "For this post, I am going to use the same Sunspot Data from Kaggle like my previous article. As mentioned there, the data can be easily downloaded from my GitHub project TimeSeries-Using-TensorFlow. I will encourage everyone to use google colab notebooks where the modules required are already installed and the infrastructure is ready for use. Now, let’s get started!"
},
{
"code": null,
"e": 1987,
"s": 1919,
"text": "The data can be downloaded using a simple command in google colab –"
},
{
"code": null,
"e": 2131,
"s": 1987,
"text": "!wget — no-check-certificate https://raw.githubusercontent.com/adib0073/TimeSeries-Using-TensorFlow/main/Data/Sunspots.csv -O /tmp/sunspots.csv"
},
{
"code": null,
"e": 2214,
"s": 2131,
"text": "Once the download is complete, we can use pandas to load the data into dataframes."
},
{
"code": null,
"e": 2316,
"s": 2214,
"text": "# Loading the data as a pandas dataframe df = pd.read_csv(‘/tmp/sunspots.csv’, index_col=0) df.head()"
},
{
"code": null,
"e": 2373,
"s": 2316,
"text": "We can take a glance at the data, which looks like this:"
},
{
"code": null,
"e": 2581,
"s": 2373,
"text": "Now, ideally we should do an extensive Exploratory Data Analysis (EDA) to understand the trend, seasonality of the data. But for this case, to keep things simple, we will do a visual inspection for the data."
},
{
"code": null,
"e": 3120,
"s": 2581,
"text": "In this step we have to transform the loaded data and process it so that it can be passed as an input to the Deep Hybrid Learning model after which we can start the training process. We can consider time series forecasting as a sequential machine learning regression problem, and the time series data is converted into a set of feature values and the corresponding true or target value. Since regression is a supervised learning problem, we need the target value, in which the lagged time series data becomes the feature values like this:"
},
{
"code": null,
"e": 4196,
"s": 3120,
"text": "We will follow a window or buffer approach in which we would have to consider an appropriate window size. Then we would move the window from left to right of the sequence or the series data. We will consider the value immediately to right of the window frame as target or the true value. So, each time-step we will shift or move the window so as to get a new row of features values and target value pairs. In this way we form the training data and training labels. In a similar way, we form the test and the validation dataset, which is typically required for a machine learning prediction model. Also, remember that for a predictive model, having a wider observation window and a narrow prediction window can give better results. Next, for the train-test-validation split ratio we will have to figure that out based on the size of the data. For this example I have used a split ratio of 0.8 and based on the seasonality of the data, we have taken a window size of 60. But these variables are all hyper-parameters, which requires some tuning to get the best possible results."
},
{
"code": null,
"e": 4233,
"s": 4196,
"text": "The code for the same is as follows:"
},
{
"code": null,
"e": 4743,
"s": 4233,
"text": "# Convert the data values to numpy for better and faster processing time_index = np.array(df['Date']) data = np.array(df['Monthly Mean Total Sunspot Number']) # Certain Hyper-parameters to tune SPLIT_RATIO = 0.8 WINDOW_SIZE = 60 BATCH_SIZE = 32 SHUFFLE_BUFFER = 1000 # Dividing into train-test split split_index = int(SPLIT_RATIO * data.shape[0]) # Train-Test Split train_data = data[:split_index] train_time = time_index[:split_index] test_data = data[split_index:] test_time = time_index[split_index:]"
},
{
"code": null,
"e": 4834,
"s": 4743,
"text": "Next, we will prepare a data generator that prepares the training and testing data for us."
},
{
"code": null,
"e": 5663,
"s": 4834,
"text": "def ts_data_generator(data, window_size, batch_size, shuffle_buffer): ''' Utility function for time series data generation in batches ''' ts_data = tf.data.Dataset.from_tensor_slices(data) ts_data = ts_data.window(window_size + 1, shift=1, drop_remainder=True) ts_data = ts_data.flat_map(lambda window: window.batch(window_size + 1)) ts_data = ts_data.shuffle(shuffle_buffer).map(lambda window: (window[:-1], window[-1])) ts_data = ts_data.batch(batch_size).prefetch(1) return ts_data# Expanding data into tensorstensor_train_data = tf.expand_dims(train_data, axis=-1)tensor_test_data = tf.expand_dims(test_data, axis=-1)tensor_train_dataset = ts_data_generator(tensor_train_data, WINDOW_SIZE, BATCH_SIZE, SHUFFLE_BUFFER)tensor_test_dataset = ts_data_generator(tensor_test_data, WINDOW_SIZE, BATCH_SIZE, SHUFFLE_BUFFER)"
},
{
"code": null,
"e": 5734,
"s": 5663,
"text": "Now, we have our processed data ready for feeding this into our model."
},
{
"code": null,
"e": 5939,
"s": 5734,
"text": "We will use a simple version of a Deep Hybrid Learning architecture for this problem. As discussed we will use the Deep Learning variant with Late Fusion technique. The model architecture looks like this:"
},
{
"code": null,
"e": 6202,
"s": 5939,
"text": "Here we have used a combination model of 1D CNN for extracting the initial sequential features and then combined with 2 LSTM layers for the feature extraction part and finally passed the same into tradional DNN Fully Connected Layers to produce the final output."
},
{
"code": null,
"e": 6255,
"s": 6202,
"text": "The code for the model architecture looks like this:"
},
{
"code": null,
"e": 6695,
"s": 6255,
"text": "# DHL Fusion model of 1D CNN and LSTM model = tf.keras.models.Sequential([tf.keras.layers.Conv1D(filters=32, kernel_size=5,strides=1, padding=\"causal\",activation=\"relu\", input_shape=[None, 1]),tf.keras.layers.LSTM(64, return_sequences=True), tf.keras.layers.LSTM(64, return_sequences=True), tf.keras.layers.Dense(30, activation=\"relu\"), tf.keras.layers.Dense(10, activation=\"relu\"), tf.keras.layers.Dense(1)])"
},
{
"code": null,
"e": 6998,
"s": 6695,
"text": "Next we would need to choose other hyper-parameters like learning rate, optimizer and loss function. I am not covering the intuition behind selection of these values in this post so as to keep it simple. But feel free to comment or drop me a note in this if you are curious to find out more about this."
},
{
"code": null,
"e": 7254,
"s": 6998,
"text": "optimizer = tf.keras.optimizers.SGD(lr=1e-4, momentum=0.9)model.compile(loss=tf.keras.losses.Huber(), optimizer=optimizer, metrics=[\"mae\"])history = model.fit(tensor_train_dataset, epochs=200, validation_data=tensor_test_dataset)"
},
{
"code": null,
"e": 7442,
"s": 7254,
"text": "Next we would see how to evaluate our model. But first, after the training process, it is always a better idea to plot the model loss curves to see whether the model is actually learning."
},
{
"code": null,
"e": 7732,
"s": 7442,
"text": "From the model loss curves, we do see clear presence of over-fitting. At the end of the article I will give some hint of how to handle this to make the model better, but we can see the model loss is decreasing with more training time, which is a good indication that the model is learning."
},
{
"code": null,
"e": 7941,
"s": 7732,
"text": "Now, for the model evaluation we would need to pick a metric. In a future article, I will include about various model evaluation metrics for time series data. But for this case, we will use MAE as the metric."
},
{
"code": null,
"e": 8474,
"s": 7941,
"text": "def model_forecast(model, data, window_size): ds = tf.data.Dataset.from_tensor_slices(data) ds = ds.window(window_size, shift=1, drop_remainder=True) ds = ds.flat_map(lambda w: w.batch(window_size)) ds = ds.batch(32).prefetch(1) forecast = model.predict(ds) return forecastrnn_forecast = model_forecast(model, data[..., np.newaxis], WINDOW_SIZE) rnn_forecast = rnn_forecast[split_index - WINDOW_SIZE:-1, -1, 0]# Overall Errorerror = tf.keras.metrics.mean_absolute_error(test_data, rnn_forecast).numpy()print(error)"
},
{
"code": null,
"e": 8668,
"s": 8474,
"text": "The MAE value that we got is roughly around 40. Which is not bad, but a little high for this case. And the reason why the model error is more is because of the initial over-fitting that we saw."
},
{
"code": null,
"e": 8828,
"s": 8668,
"text": "As a final step, let’s visualize the results that we are getting over the test data and let’s inspect if at all the model is close for predicting good results."
},
{
"code": null,
"e": 9308,
"s": 8828,
"text": "From the first plot, we can see that the predicted values does follow a similar seasonal pattern and trend as the actual values, but the peaks are not as high as the actual ones. Also, since time series forecast should be ranged prediction not a single point estimate, we will use the error rate to form the confidence interval or the confidence band. We can see the the error bands are wide, which means the model is not very much confident and might have some prediction error."
},
{
"code": null,
"e": 9350,
"s": 9308,
"text": "The code for visualization is as follows:"
},
{
"code": null,
"e": 9886,
"s": 9350,
"text": "plt.figure(figsize=(15, 6)) plt.plot(list(range(split_index,len(data))), test_data, label = 'Test Data') plt.plot(list(range(split_index,len(data))), rnn_forecast, label = 'Predictions') plt.legend() plt.show() plt.figure(figsize=(15, 6)) # Plotting with Confidence Intervals plt.plot(list(range(split_index,len(data))), rnn_forecast, label = 'Predictions', color = 'k', linestyle = '--')plt.fill_between(range(split_index,len(data)), rnn_forecast - error, rnn_forecast + error, alpha = 0.5, color = 'orange') plt.legend() plt.show()"
},
{
"code": null,
"e": 10040,
"s": 9886,
"text": "And thus we do have a Deep Hybrid Learning model for time series forecasting and we have used TensorFlow for forming the model and implementing the flow."
},
{
"code": null,
"e": 10143,
"s": 10040,
"text": "But if you are wondering how can the result be improved, I have the following recommendations for you:"
},
{
"code": null,
"e": 10470,
"s": 10143,
"text": "Change the window size (either increase or decrease)Use more training data (so as to solve the over-fitting problem)Use more model layers or more hidden unitsUse a different loss function and learning rateWe saw that the loss curve is not smooth. It usually happens if the batch size is small, so try with a bigger batch size."
},
{
"code": null,
"e": 10523,
"s": 10470,
"text": "Change the window size (either increase or decrease)"
},
{
"code": null,
"e": 10588,
"s": 10523,
"text": "Use more training data (so as to solve the over-fitting problem)"
},
{
"code": null,
"e": 10631,
"s": 10588,
"text": "Use more model layers or more hidden units"
},
{
"code": null,
"e": 10679,
"s": 10631,
"text": "Use a different loss function and learning rate"
},
{
"code": null,
"e": 10801,
"s": 10679,
"text": "We saw that the loss curve is not smooth. It usually happens if the batch size is small, so try with a bigger batch size."
},
{
"code": null,
"e": 11285,
"s": 10801,
"text": "Also sometimes, a simpler model may give better result. In my post Time Series Forecasting using Deep Learning with TensorFlow I got much better results just by using a simple Deep Neural Network. Now, unlike with image data, we saw that with time series data, Deep Hybrid Learner was not significantly better than a conventional Deep Learning, Machine Learning or Statistical methods. But, yes after doing thorough hyper parameter tuning, I am sure the results would be much better!"
},
{
"code": null,
"e": 11559,
"s": 11285,
"text": "Thus, this brings us to the end of this article. The full working code and notebook can be obtained from here. Keep following me: https://medium.com/@adib0073 and my website: https://www.aditya-bhattacharya.net/ for more! Please feel free to reach for any query or comment!"
}
] |
PDFBox - Adding Multiple Lines
|
In the example provided in the previous chapter we discussed how to add text to a page in a PDF but through this program, you can only add the text that would fit in a single line. If you try to add more content, all the text that exceeds the line space will not be displayed.
For example, if you execute the above program in the previous chapter by passing the following string only a part of it will be displayed.
String text = "This is an example of adding text to a page in the pdf document. we can
add as many lines as we want like this using the showText() method of the
ContentStream class";
Replace the string text of the example in the previous chapter with the above mentioned string and execute it. Upon execution, you will receive the following output.
If you observe the output carefully, you can notice that only a part of the string is displayed.
In order to add multiple lines to a PDF you need to set the leading using the setLeading() method and shift to new line using newline() method after finishing each line.
Following are the steps to create an empty document and add contents to a page in it.
You can load an existing document using the load() method of the PDDocument class. Therefore, instantiate this class and load the required document as shown below.
File file = new File("Path of the document");
PDDocument doc = PDDocument.load(file);
You can get the required page in a document using the getPage() method. Retrieve the object of the required page by passing its index to this method as shown below.
PDPage page = doc.getPage(1);
You can insert various kinds of data elements using the object of the class named PDPageContentStream. You need to pass the document object and the page object to the constructor of this class therefore, instantiate this class by passing these two objects created in the previous steps as shown below.
PDPageContentStream contentStream = new PDPageContentStream(doc, page);
While inserting text in a PDF document, you can specify the start and end points of the text using the beginText() and endText() methods of the PDPageContentStream class as shown below.
contentStream.beginText();
.............................
code to add text content
.............................
contentStream.endText();
Therefore, begin the text using the beginText() method as shown below.
contentStream.beginText();
Using the newLineAtOffset() method, you can set the position on the content stream in the page.
//Setting the position for the line
contentStream.newLineAtOffset(25, 700);
You can set the font of the text to the required style using the setFont() method of the PDPageContentStream class as shown below to this method you need to pass the type and size of the font.
contentStream.setFont( font_type, font_size );
You can set the text leading using the setLeading() method as shown below.
contentStream.setLeading(14.5f);
You can insert multiple strings using the ShowText() method of the PDPageContentStream class, by dividing each of them using the newline() method as shown below.
contentStream. ShowText(text1);
contentStream.newLine();
contentStream. ShowText(text2);
After inserting the text, you need to end the text using the endText() method of the PDPageContentStream class as shown below.
contentStream.endText();
Close the PDPageContentStream object using the close() method as shown below.
contentstream.close();
After adding the required content, save the PDF document using the save() method of the PDDocument class as shown in the following code block.
doc.save("Path");
Finally, close the document using the close() method of the PDDocument class as shown below.
doc.close();
This example demonstrates how to add multiple lines in a PDF using PDFBox. Save this program in a file with name AddMultipleLines.java.
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
public class AddMultipleLines {
public static void main(String args[]) throws IOException {
//Loading an existing document
File file = new File("C:/PdfBox_Examples/my_pdf.pdf");
PDDocument doc = document.load(file);
//Creating a PDF Document
PDPage page = doc.getPage(1);
PDPageContentStream contentStream = new PDPageContentStream(doc, page);
//Begin the Content stream
contentStream.beginText();
//Setting the font to the Content stream
contentStream.setFont( PDType1Font.TIMES_ROMAN, 16 );
//Setting the leading
contentStream.setLeading(14.5f);
//Setting the position for the line
contentStream.newLineAtOffset(25, 725);
String text1 = "This is an example of adding text to a page in the pdf document.
we can add as many lines";
String text2 = "as we want like this using the ShowText() method of the
ContentStream class";
//Adding text in the form of string
contentStream. ShowText(text1);
contentStream.newLine();
contentStream. ShowText(text2);
//Ending the content stream
contentStream.endText();
System.out.println("Content added");
//Closing the content stream
contentStream.close();
//Saving the document
doc.save(new File("C:/PdfBox_Examples/new.pdf"));
//Closing the document
doc.close();
}
}
Compile and execute the saved Java file from the command prompt using the following commands.
javac AddMultipleLines.java
java AddMultipleLines
Upon execution, the above program adds the given text to the document and displays the following message.
Content added
If you verify the PDF Document new.pdf in the specified path, you can observe that the given content is added to the document in multiple lines as shown below.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2304,
"s": 2027,
"text": "In the example provided in the previous chapter we discussed how to add text to a page in a PDF but through this program, you can only add the text that would fit in a single line. If you try to add more content, all the text that exceeds the line space will not be displayed."
},
{
"code": null,
"e": 2443,
"s": 2304,
"text": "For example, if you execute the above program in the previous chapter by passing the following string only a part of it will be displayed."
},
{
"code": null,
"e": 2634,
"s": 2443,
"text": "String text = \"This is an example of adding text to a page in the pdf document. we can\n add as many lines as we want like this using the showText() method of the \n ContentStream class\";\n"
},
{
"code": null,
"e": 2800,
"s": 2634,
"text": "Replace the string text of the example in the previous chapter with the above mentioned string and execute it. Upon execution, you will receive the following output."
},
{
"code": null,
"e": 2897,
"s": 2800,
"text": "If you observe the output carefully, you can notice that only a part of the string is displayed."
},
{
"code": null,
"e": 3067,
"s": 2897,
"text": "In order to add multiple lines to a PDF you need to set the leading using the setLeading() method and shift to new line using newline() method after finishing each line."
},
{
"code": null,
"e": 3153,
"s": 3067,
"text": "Following are the steps to create an empty document and add contents to a page in it."
},
{
"code": null,
"e": 3317,
"s": 3153,
"text": "You can load an existing document using the load() method of the PDDocument class. Therefore, instantiate this class and load the required document as shown below."
},
{
"code": null,
"e": 3405,
"s": 3317,
"text": "File file = new File(\"Path of the document\"); \nPDDocument doc = PDDocument.load(file);\n"
},
{
"code": null,
"e": 3570,
"s": 3405,
"text": "You can get the required page in a document using the getPage() method. Retrieve the object of the required page by passing its index to this method as shown below."
},
{
"code": null,
"e": 3601,
"s": 3570,
"text": "PDPage page = doc.getPage(1);\n"
},
{
"code": null,
"e": 3903,
"s": 3601,
"text": "You can insert various kinds of data elements using the object of the class named PDPageContentStream. You need to pass the document object and the page object to the constructor of this class therefore, instantiate this class by passing these two objects created in the previous steps as shown below."
},
{
"code": null,
"e": 3976,
"s": 3903,
"text": "PDPageContentStream contentStream = new PDPageContentStream(doc, page);\n"
},
{
"code": null,
"e": 4162,
"s": 3976,
"text": "While inserting text in a PDF document, you can specify the start and end points of the text using the beginText() and endText() methods of the PDPageContentStream class as shown below."
},
{
"code": null,
"e": 4305,
"s": 4162,
"text": "contentStream.beginText(); \n............................. \ncode to add text content \n............................. \ncontentStream.endText(); \n"
},
{
"code": null,
"e": 4376,
"s": 4305,
"text": "Therefore, begin the text using the beginText() method as shown below."
},
{
"code": null,
"e": 4404,
"s": 4376,
"text": "contentStream.beginText();\n"
},
{
"code": null,
"e": 4500,
"s": 4404,
"text": "Using the newLineAtOffset() method, you can set the position on the content stream in the page."
},
{
"code": null,
"e": 4578,
"s": 4500,
"text": "//Setting the position for the line \ncontentStream.newLineAtOffset(25, 700);\n"
},
{
"code": null,
"e": 4771,
"s": 4578,
"text": "You can set the font of the text to the required style using the setFont() method of the PDPageContentStream class as shown below to this method you need to pass the type and size of the font."
},
{
"code": null,
"e": 4819,
"s": 4771,
"text": "contentStream.setFont( font_type, font_size );\n"
},
{
"code": null,
"e": 4894,
"s": 4819,
"text": "You can set the text leading using the setLeading() method as shown below."
},
{
"code": null,
"e": 4928,
"s": 4894,
"text": "contentStream.setLeading(14.5f);\n"
},
{
"code": null,
"e": 5090,
"s": 4928,
"text": "You can insert multiple strings using the ShowText() method of the PDPageContentStream class, by dividing each of them using the newline() method as shown below."
},
{
"code": null,
"e": 5182,
"s": 5090,
"text": "contentStream. ShowText(text1); \ncontentStream.newLine(); \ncontentStream. ShowText(text2);\n"
},
{
"code": null,
"e": 5309,
"s": 5182,
"text": "After inserting the text, you need to end the text using the endText() method of the PDPageContentStream class as shown below."
},
{
"code": null,
"e": 5335,
"s": 5309,
"text": "contentStream.endText();\n"
},
{
"code": null,
"e": 5413,
"s": 5335,
"text": "Close the PDPageContentStream object using the close() method as shown below."
},
{
"code": null,
"e": 5437,
"s": 5413,
"text": "contentstream.close();\n"
},
{
"code": null,
"e": 5580,
"s": 5437,
"text": "After adding the required content, save the PDF document using the save() method of the PDDocument class as shown in the following code block."
},
{
"code": null,
"e": 5599,
"s": 5580,
"text": "doc.save(\"Path\");\n"
},
{
"code": null,
"e": 5692,
"s": 5599,
"text": "Finally, close the document using the close() method of the PDDocument class as shown below."
},
{
"code": null,
"e": 5706,
"s": 5692,
"text": "doc.close();\n"
},
{
"code": null,
"e": 5842,
"s": 5706,
"text": "This example demonstrates how to add multiple lines in a PDF using PDFBox. Save this program in a file with name AddMultipleLines.java."
},
{
"code": null,
"e": 7553,
"s": 5842,
"text": "import java.io.File;\nimport java.io.IOException;\n\nimport org.apache.pdfbox.pdmodel.PDDocument;\nimport org.apache.pdfbox.pdmodel.PDPage;\nimport org.apache.pdfbox.pdmodel.PDPageContentStream;\nimport org.apache.pdfbox.pdmodel.font.PDType1Font;\n\npublic class AddMultipleLines {\n public static void main(String args[]) throws IOException {\n\n //Loading an existing document\n File file = new File(\"C:/PdfBox_Examples/my_pdf.pdf\");\n PDDocument doc = document.load(file);\n \n //Creating a PDF Document\n PDPage page = doc.getPage(1); \n \n PDPageContentStream contentStream = new PDPageContentStream(doc, page); \n \n //Begin the Content stream \n contentStream.beginText(); \n \n //Setting the font to the Content stream\n contentStream.setFont( PDType1Font.TIMES_ROMAN, 16 );\n \n //Setting the leading\n contentStream.setLeading(14.5f);\n\n //Setting the position for the line\n contentStream.newLineAtOffset(25, 725);\n\n String text1 = \"This is an example of adding text to a page in the pdf document.\n we can add as many lines\";\n String text2 = \"as we want like this using the ShowText() method of the\n ContentStream class\";\n\n //Adding text in the form of string\n contentStream. ShowText(text1);\n contentStream.newLine();\n contentStream. ShowText(text2);\n //Ending the content stream\n contentStream.endText();\n\n System.out.println(\"Content added\");\n\n //Closing the content stream\n contentStream.close();\n\n //Saving the document\n doc.save(new File(\"C:/PdfBox_Examples/new.pdf\"));\n \n //Closing the document\n doc.close();\n }\n}"
},
{
"code": null,
"e": 7647,
"s": 7553,
"text": "Compile and execute the saved Java file from the command prompt using the following commands."
},
{
"code": null,
"e": 7699,
"s": 7647,
"text": "javac AddMultipleLines.java \njava AddMultipleLines\n"
},
{
"code": null,
"e": 7805,
"s": 7699,
"text": "Upon execution, the above program adds the given text to the document and displays the following message."
},
{
"code": null,
"e": 7820,
"s": 7805,
"text": "Content added\n"
},
{
"code": null,
"e": 7980,
"s": 7820,
"text": "If you verify the PDF Document new.pdf in the specified path, you can observe that the given content is added to the document in multiple lines as shown below."
},
{
"code": null,
"e": 7987,
"s": 7980,
"text": " Print"
},
{
"code": null,
"e": 7998,
"s": 7987,
"text": " Add Notes"
}
] |
Emulating a PID Controller with Long Short-term Memory: Part 1 | by Nicholas Lewis | Towards Data Science
|
Do you ever just get really excited about an idea? Maybe it’s a new DIY project you’re tackling, or a cool assignment at work. Maybe you’re crazy like me and want to hike the Pacific Crest Trail (as I’m moving to Seattle soon, so I can’t help but get excited about the idea of flying down to San Diego and walking home). Well, this project is one of those types of ideas for me, and I hope you enjoy the ride!
Before I get started, though, I want to warn you that this is quite an extensive project, and so I’m breaking it up into parts. They will be as follows:
Using the Temperature Control Lab to create Proportional-Integral-Derivative controller data (this article)Training a Long Short-term Memory neural network in Keras to emulate a PID controllerControlling the Temperature Control Lab with an LSTMPractical applications of temperature control using LSTM controller instead of PID controller
Using the Temperature Control Lab to create Proportional-Integral-Derivative controller data (this article)
Training a Long Short-term Memory neural network in Keras to emulate a PID controller
Controlling the Temperature Control Lab with an LSTM
Practical applications of temperature control using LSTM controller instead of PID controller
While working on a project for work one day, I came across a paper that introduced a novel idea. Some researchers had the idea to emulate the behavior of a model predictive control (MPC) strategy using a neural network. The idea was that some MPC problems are extremely computationally expensive, but the behavior is predictable; if we could emulate that behavior by training a deep neural network, we could, in theory, replace the computationally expensive MPC with a much faster machine learning model. The only computationally expensive part of the process would be the model training.
The really neat part of this is that I test the idea here at my desk. The Temperature Control Lab is perfectly designed to prototype this kind of problem. I introduced the TCLab and some basic anomaly detection you can do with machine learning in an earlier post. If you’re new to the TCLab, you can check out my article, or look at the abundant resources at APMonitor.com.
So here’s what I decided to try: I wanted to tune a Proportional-Integral-Derivative (PID) controller so I could set a temperature on the TCLab and the controller would adjust the heater until it hit that setpoint. Then, I wanted to see if I could emulate this behavior with a Long Short-term Memory neural network. If this prototype worked, it would open the doors for not only improving computational speed, but also applications such as anomaly detection.
This series is about the machine learning, so if you’re not familiar with PID controllers or control theory, that’s perfectly fine; we’ll just hit a few highlights so you understand the context. There are some amazing resources at APMonitor.com to help you understand PID controllers and how to tune them. These controllers are ubiquitous in engineering industry, and so the potential applications for this are numerous.
Control systems are everywhere. Think about your thermostat: all you have to do is plug in the temperature, and somehow it knows when to turn the heat on and off to keep your house at that temperature (except, of course, for the room that’s always an ice box...). How does it do that? Control systems can be broken down into three parts: a sensor (something that reads the temperature in the house), an actuator (the A/C or furnace that turns on cold or hot air), and a controller (the computer in your thermostat that is the brains behind the operation). The sensor data feeds into the controller, which then tells the actuator what to do.
PID controllers are ubiquitous for a reason: they’re straightforward and extremely effective, especially when paired with a first order plus dead time (FOPDT) model. In the case of our TCLab, it takes the difference between the temperature setpoint and temperature sensor (represented as e(t) in the equation below) as an input, and outputs a heater value (labeled output, or OP, below) that will allow the temperature to approach the setpoint. As the name suggests, there is a proportional, integral, and derivative portion to this.
K_c, τ_I, and τ_D are called the tuning constants, and determine how the controller behaves. You can generate a step response for your TCLab, and then obtain tuning parameters for a PID controller graphically. For my TCLab, some effective tuning parameters were K_c = 6.0, τ_i =75.0, and τ_d = 0.0. Yours will likely be different since each TCLab behaves slightly differently. Let’s take a look at the code now for the PID controller. I put it in the function pid(sp,pv,pv_last,ierr,dt) .
The first part is to load your tuning parameters and other constants:
# PID ParametersKc = 6.0tauI = 75.0 # sectauD = 0.0 # sec# PID coefficients in terms of tuning parametersKP = KcKI = Kc / tauIKD = Kc * tauD# OPbias for controller (initial heater)op0 = 0# upper and lower bounds on heater levelophi = 100oplo = 0
Then we want to calculate the error between the setpoint (sp) and temperature (also referred to as process variable, pv):
# calculate the errorerror = sp - pv
The integral portion is calculated numerically, adding whatever the previous error was to the current time step error:
# calculate the integral errorierr = ierr + KI * error * dt
And finally, the derivative portion of the controller (also calculated numerically) looks like this:
# calculate the measurement derivativedpv = (pv - pv_last) / dt
Putting it all together now, we can calculate the PID output (op):
# calculate the PID outputP = KP * errorI = ierrD = -KD * dpvop = op0 + P + I + D
And finally, just to make sure we account for the heater limit between 0 and 100, we add an anti-reset windup condition:
# implement anti-reset windupif op < oplo or op > ophi: I = I - KI * error * dt # clip output op = max(oplo,min(ophi,op))
That’s not so bad! If nothing else, you learned how to program a PID controller function, which is extremely useful for industrial controllers.
Now we need to actually run the PID controller on the TCLab. We’ll set up several arrays to store data as we go, and run the controller for 90 minutes to make sure we have plenty of data. We’ll change the temperature setpoint intermittently so we have a good mix of steady-state and transient behavior. Here’s what my setup looks like:
##### Set up run parameters ###### Run time in minutesrun_time = 90.0# Number of cyclesloops = int(60.0*run_time)# arrays for storing dataT1 = np.zeros(loops) # measured T (degC)error_sp = np.zeros(loops) # Setpoint errorQ1 = np.zeros(loops) # Heater valuestm = np.zeros(loops) # Time# Temperature set point (degC)with tclab.TCLab() as lab: Tsp1 = np.ones(loops) * lab.T1# vary temperature setpointend = 30 # leave 1st 30 seconds of temp setpoint as room tempwhile end <= loops: start = end # keep new temp set point value for anywhere from 4 to 10 min end += random.randint(240,600) Tsp1[start:end] = random.randint(30,70)
It never hurts to plot what you expect should happen. Over the course of 90 minutes, we intend for the PID controller to set the heater such that the temperature follows this profile:
We’re all set! I went into more details of how to set up a run on the TCLab in another article I wrote, but this application is slightly more advanced. Most notably, we call our pid(sp,pv,pv_last,ierr,dt) function at each time step to return the heater output so that we stay at the right temperature. We’re updating this every second; the PID isn’t too computationally expensive, so it can easily solve within that time.
# Run testwith tclab.TCLab() as lab: # Find current T1, T2 print('Temperature 1: {0:0.2f} °C'.format(lab.T1)) print('Temperature 2: {0:0.2f} °C'.format(lab.T2)) # Integral error ierr = 0.0 # Integral absolute error iae = 0.0 start_time = time.time() prev_time = start_time for i in range(loops): # Delay 1 second if time.time() > prev_time + 1.0: print('Exceeded cycle time by ', time.time()-prev_time-1.0) else: while time.time() < prev_time + 1.0: pass # Record time and change in time t = time.time() dt = t - prev_time prev_time = t tm[i] = t - start_time # Read temperatures in Kelvin T1[i] = lab.T1 # Integral absolute error iae += np.abs(Tsp1[i]-T1[i]) # Calculate PID output [Q1[i],P,ierr,D] = pid(Tsp1[i],T1[i],T1[i-1],ierr,dt) # Write heater output (0-100) lab.Q1(Q1[i])
Let’s take a look at how the controller did:
Pretty neat! We want the red line, which is the temperature sensor, to follow the black line, which is the temperature setpoint. The blue shows how the heater adjusted so that the sensor would match the setpoint. We could always tune the PID parameters for different performance, but we want to get to the machine learning part, so for this exercise, this is perfect. And I don’t know about you, but we haven’t even started the machine learning, but just programming our own controller at our desk is already exciting!
First things first, you can download the code for this from Github. This exercise depends a lot on the TCLab, but I’m hoping in the future to add some alternative notebooks with raw data so that you can run the code without one.
How neat is it that we can program a device to control the temperature? There are so many applications — think of your thermostat, or oven, or even a fancy barbeque grill. Not to mention the industrial applications of reactor temperature or feed stream temperature. What other applications can you think of for this type of controller?
Thanks for bearing with me through this introductory article, especially if you’ve never seen a controller. I know I promised some machine learning applications, and that’s exactly what we’re working up to. We’ll dive into that first thing in the next section (coming October 2020). If anything, though, I feel that it’s important to understand the background behind machine learning applications. Not only does it make them relevant to our work or daily lives, but it also opens up the door for greater insights. I’m happy to hear what ideas this might open up for you!
|
[
{
"code": null,
"e": 582,
"s": 172,
"text": "Do you ever just get really excited about an idea? Maybe it’s a new DIY project you’re tackling, or a cool assignment at work. Maybe you’re crazy like me and want to hike the Pacific Crest Trail (as I’m moving to Seattle soon, so I can’t help but get excited about the idea of flying down to San Diego and walking home). Well, this project is one of those types of ideas for me, and I hope you enjoy the ride!"
},
{
"code": null,
"e": 735,
"s": 582,
"text": "Before I get started, though, I want to warn you that this is quite an extensive project, and so I’m breaking it up into parts. They will be as follows:"
},
{
"code": null,
"e": 1073,
"s": 735,
"text": "Using the Temperature Control Lab to create Proportional-Integral-Derivative controller data (this article)Training a Long Short-term Memory neural network in Keras to emulate a PID controllerControlling the Temperature Control Lab with an LSTMPractical applications of temperature control using LSTM controller instead of PID controller"
},
{
"code": null,
"e": 1181,
"s": 1073,
"text": "Using the Temperature Control Lab to create Proportional-Integral-Derivative controller data (this article)"
},
{
"code": null,
"e": 1267,
"s": 1181,
"text": "Training a Long Short-term Memory neural network in Keras to emulate a PID controller"
},
{
"code": null,
"e": 1320,
"s": 1267,
"text": "Controlling the Temperature Control Lab with an LSTM"
},
{
"code": null,
"e": 1414,
"s": 1320,
"text": "Practical applications of temperature control using LSTM controller instead of PID controller"
},
{
"code": null,
"e": 2003,
"s": 1414,
"text": "While working on a project for work one day, I came across a paper that introduced a novel idea. Some researchers had the idea to emulate the behavior of a model predictive control (MPC) strategy using a neural network. The idea was that some MPC problems are extremely computationally expensive, but the behavior is predictable; if we could emulate that behavior by training a deep neural network, we could, in theory, replace the computationally expensive MPC with a much faster machine learning model. The only computationally expensive part of the process would be the model training."
},
{
"code": null,
"e": 2377,
"s": 2003,
"text": "The really neat part of this is that I test the idea here at my desk. The Temperature Control Lab is perfectly designed to prototype this kind of problem. I introduced the TCLab and some basic anomaly detection you can do with machine learning in an earlier post. If you’re new to the TCLab, you can check out my article, or look at the abundant resources at APMonitor.com."
},
{
"code": null,
"e": 2836,
"s": 2377,
"text": "So here’s what I decided to try: I wanted to tune a Proportional-Integral-Derivative (PID) controller so I could set a temperature on the TCLab and the controller would adjust the heater until it hit that setpoint. Then, I wanted to see if I could emulate this behavior with a Long Short-term Memory neural network. If this prototype worked, it would open the doors for not only improving computational speed, but also applications such as anomaly detection."
},
{
"code": null,
"e": 3257,
"s": 2836,
"text": "This series is about the machine learning, so if you’re not familiar with PID controllers or control theory, that’s perfectly fine; we’ll just hit a few highlights so you understand the context. There are some amazing resources at APMonitor.com to help you understand PID controllers and how to tune them. These controllers are ubiquitous in engineering industry, and so the potential applications for this are numerous."
},
{
"code": null,
"e": 3898,
"s": 3257,
"text": "Control systems are everywhere. Think about your thermostat: all you have to do is plug in the temperature, and somehow it knows when to turn the heat on and off to keep your house at that temperature (except, of course, for the room that’s always an ice box...). How does it do that? Control systems can be broken down into three parts: a sensor (something that reads the temperature in the house), an actuator (the A/C or furnace that turns on cold or hot air), and a controller (the computer in your thermostat that is the brains behind the operation). The sensor data feeds into the controller, which then tells the actuator what to do."
},
{
"code": null,
"e": 4432,
"s": 3898,
"text": "PID controllers are ubiquitous for a reason: they’re straightforward and extremely effective, especially when paired with a first order plus dead time (FOPDT) model. In the case of our TCLab, it takes the difference between the temperature setpoint and temperature sensor (represented as e(t) in the equation below) as an input, and outputs a heater value (labeled output, or OP, below) that will allow the temperature to approach the setpoint. As the name suggests, there is a proportional, integral, and derivative portion to this."
},
{
"code": null,
"e": 4921,
"s": 4432,
"text": "K_c, τ_I, and τ_D are called the tuning constants, and determine how the controller behaves. You can generate a step response for your TCLab, and then obtain tuning parameters for a PID controller graphically. For my TCLab, some effective tuning parameters were K_c = 6.0, τ_i =75.0, and τ_d = 0.0. Yours will likely be different since each TCLab behaves slightly differently. Let’s take a look at the code now for the PID controller. I put it in the function pid(sp,pv,pv_last,ierr,dt) ."
},
{
"code": null,
"e": 4991,
"s": 4921,
"text": "The first part is to load your tuning parameters and other constants:"
},
{
"code": null,
"e": 5240,
"s": 4991,
"text": "# PID ParametersKc = 6.0tauI = 75.0 # sectauD = 0.0 # sec# PID coefficients in terms of tuning parametersKP = KcKI = Kc / tauIKD = Kc * tauD# OPbias for controller (initial heater)op0 = 0# upper and lower bounds on heater levelophi = 100oplo = 0"
},
{
"code": null,
"e": 5362,
"s": 5240,
"text": "Then we want to calculate the error between the setpoint (sp) and temperature (also referred to as process variable, pv):"
},
{
"code": null,
"e": 5399,
"s": 5362,
"text": "# calculate the errorerror = sp - pv"
},
{
"code": null,
"e": 5518,
"s": 5399,
"text": "The integral portion is calculated numerically, adding whatever the previous error was to the current time step error:"
},
{
"code": null,
"e": 5578,
"s": 5518,
"text": "# calculate the integral errorierr = ierr + KI * error * dt"
},
{
"code": null,
"e": 5679,
"s": 5578,
"text": "And finally, the derivative portion of the controller (also calculated numerically) looks like this:"
},
{
"code": null,
"e": 5743,
"s": 5679,
"text": "# calculate the measurement derivativedpv = (pv - pv_last) / dt"
},
{
"code": null,
"e": 5810,
"s": 5743,
"text": "Putting it all together now, we can calculate the PID output (op):"
},
{
"code": null,
"e": 5892,
"s": 5810,
"text": "# calculate the PID outputP = KP * errorI = ierrD = -KD * dpvop = op0 + P + I + D"
},
{
"code": null,
"e": 6013,
"s": 5892,
"text": "And finally, just to make sure we account for the heater limit between 0 and 100, we add an anti-reset windup condition:"
},
{
"code": null,
"e": 6144,
"s": 6013,
"text": "# implement anti-reset windupif op < oplo or op > ophi: I = I - KI * error * dt # clip output op = max(oplo,min(ophi,op))"
},
{
"code": null,
"e": 6288,
"s": 6144,
"text": "That’s not so bad! If nothing else, you learned how to program a PID controller function, which is extremely useful for industrial controllers."
},
{
"code": null,
"e": 6624,
"s": 6288,
"text": "Now we need to actually run the PID controller on the TCLab. We’ll set up several arrays to store data as we go, and run the controller for 90 minutes to make sure we have plenty of data. We’ll change the temperature setpoint intermittently so we have a good mix of steady-state and transient behavior. Here’s what my setup looks like:"
},
{
"code": null,
"e": 7264,
"s": 6624,
"text": "##### Set up run parameters ###### Run time in minutesrun_time = 90.0# Number of cyclesloops = int(60.0*run_time)# arrays for storing dataT1 = np.zeros(loops) # measured T (degC)error_sp = np.zeros(loops) # Setpoint errorQ1 = np.zeros(loops) # Heater valuestm = np.zeros(loops) # Time# Temperature set point (degC)with tclab.TCLab() as lab: Tsp1 = np.ones(loops) * lab.T1# vary temperature setpointend = 30 # leave 1st 30 seconds of temp setpoint as room tempwhile end <= loops: start = end # keep new temp set point value for anywhere from 4 to 10 min end += random.randint(240,600) Tsp1[start:end] = random.randint(30,70)"
},
{
"code": null,
"e": 7448,
"s": 7264,
"text": "It never hurts to plot what you expect should happen. Over the course of 90 minutes, we intend for the PID controller to set the heater such that the temperature follows this profile:"
},
{
"code": null,
"e": 7870,
"s": 7448,
"text": "We’re all set! I went into more details of how to set up a run on the TCLab in another article I wrote, but this application is slightly more advanced. Most notably, we call our pid(sp,pv,pv_last,ierr,dt) function at each time step to return the heater output so that we stay at the right temperature. We’re updating this every second; the PID isn’t too computationally expensive, so it can easily solve within that time."
},
{
"code": null,
"e": 8857,
"s": 7870,
"text": "# Run testwith tclab.TCLab() as lab: # Find current T1, T2 print('Temperature 1: {0:0.2f} °C'.format(lab.T1)) print('Temperature 2: {0:0.2f} °C'.format(lab.T2)) # Integral error ierr = 0.0 # Integral absolute error iae = 0.0 start_time = time.time() prev_time = start_time for i in range(loops): # Delay 1 second if time.time() > prev_time + 1.0: print('Exceeded cycle time by ', time.time()-prev_time-1.0) else: while time.time() < prev_time + 1.0: pass # Record time and change in time t = time.time() dt = t - prev_time prev_time = t tm[i] = t - start_time # Read temperatures in Kelvin T1[i] = lab.T1 # Integral absolute error iae += np.abs(Tsp1[i]-T1[i]) # Calculate PID output [Q1[i],P,ierr,D] = pid(Tsp1[i],T1[i],T1[i-1],ierr,dt) # Write heater output (0-100) lab.Q1(Q1[i])"
},
{
"code": null,
"e": 8902,
"s": 8857,
"text": "Let’s take a look at how the controller did:"
},
{
"code": null,
"e": 9421,
"s": 8902,
"text": "Pretty neat! We want the red line, which is the temperature sensor, to follow the black line, which is the temperature setpoint. The blue shows how the heater adjusted so that the sensor would match the setpoint. We could always tune the PID parameters for different performance, but we want to get to the machine learning part, so for this exercise, this is perfect. And I don’t know about you, but we haven’t even started the machine learning, but just programming our own controller at our desk is already exciting!"
},
{
"code": null,
"e": 9650,
"s": 9421,
"text": "First things first, you can download the code for this from Github. This exercise depends a lot on the TCLab, but I’m hoping in the future to add some alternative notebooks with raw data so that you can run the code without one."
},
{
"code": null,
"e": 9986,
"s": 9650,
"text": "How neat is it that we can program a device to control the temperature? There are so many applications — think of your thermostat, or oven, or even a fancy barbeque grill. Not to mention the industrial applications of reactor temperature or feed stream temperature. What other applications can you think of for this type of controller?"
}
] |
Javascript Program For Sorting An Array Of 0s, 1s and 2s - GeeksforGeeks
|
16 Dec, 2021
Given an array A[] consisting 0s, 1s and 2s. The task is to write a function that sorts the given array. The functions should put all 0s first, then all 1s and all 2s in last.Examples:
Input: {0, 1, 2, 0, 1, 2}
Output: {0, 0, 1, 1, 2, 2}
Input: {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}
Output: {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2}
A simple solution is discussed in this(Sort an array of 0s, 1s and 2s (Simple Counting)) post.Method 1:
Approach:The problem is similar to our old post Segregate 0s and 1s in an array, and both of these problems are variation of famous Dutch national flag problem.The problem was posed with three colours, here `0′, `1′ and `2′. The array is divided into four sections:
a[1..Lo-1] zeroes (red)a[Lo..Mid-1] ones (white)a[Mid..Hi] unknowna[Hi+1..N] twos (blue)If the ith element is 0 then swap the element to the low range, thus shrinking the unknown range.Similarly, if the element is 1 then keep it as it is but shrink the unknown range.If the element is 2 then swap it with an element in high range.Algorithm: Keep three indices low = 1, mid = 1 and high = N and there are four ranges, 1 to low (the range containing 0), low to mid (the range containing 1), mid to high (the range containing unknown elements) and high to N (the range containing 2).Traverse the array from start to end and mid is less than high. (Loop counter is i)If the element is 0 then swap the element with the element at index low and update low = low + 1 and mid = mid + 1If the element is 1 then update mid = mid + 1If the element is 2 then swap the element with the element at index high and update high = high – 1 and update i = i – 1. As the swapped element is not processedPrint the output array.Dry Run: Part way through the process, some red, white and blue elements are known and are in the “right” place. The section of unknown elements, a[Mid..Hi], is shrunk by examining a[Mid]:Examine a[Mid]. There are three possibilities: a[Mid] is (0) red, (1) white or (2) blue. Case (0) a[Mid] is red, swap a[Lo] and a[Mid]; Lo++; Mid++ Case (1) a[Mid] is white, Mid++Case (2) a[Mid] is blue, swap a[Mid] and a[Hi]; Hi–Continue until Mid>Hi.Implementation:JavascriptJavascript<script>// Javascript program to sort an // array of 0, 1 and 2 // Sort the input array, the array is // assumed to have values in {0, 1, 2} function sort012(a, arr_size){ let lo = 0; let hi = arr_size - 1; let mid = 0; let temp = 0; while (mid <= hi) { if(a[mid] == 0) { temp = a[lo]; a[lo] = a[mid]; a[mid] = temp; lo++; mid++; } else if(a[mid] == 1) { mid++; } else { temp = a[mid]; a[mid] = a[hi]; a[hi] = temp; hi--; } }} /* Utility function to print array arr[] */function printArray(arr, arr_size){ let i; for (i = 0; i < arr_size; i++) { document.write(arr[i] + " "); } document.write("<br>");} // Driver codelet arr= [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 ];let arr_size = arr.length;sort012(arr, arr_size);document.write("Array after seggregation <br>")printArray(arr, arr_size); // This code is contributed by rag2127</script>Output: array after segregation
0 0 0 0 0 1 1 1 1 1 2 2 Complexity Analysis: Time Complexity: O(n). Only one traversal of the array is needed.Space Complexity: O(1). No extra space is required.Method 2:Approach: Count the number of 0s, 1s and 2s in the given array. Then store all the 0s in the beginning followed by all the 1s then all the 2s.Algorithm: Keep three counter c0 to count 0s, c1 to count 1s and c2 to count 2sTraverse through the array and increase the count of c0 if the element is 0,increase the count of c1 if the element is 1 and increase the count of c2 if the element is 2Now again traverse the array and replace first c0 elements with 0, next c1 elements with 1 and next c2 elements with 2.Implementation:JavascriptJavascript<script>// Javascript implementation of the // approach // Utility function to print the // contents of an arrayfunction printArr( arr, n){ for (let i = 0; i < n; i++) document.write(arr[i] + " ");} // Function to sort the array of 0s, // 1s and 2sfunction sortArr( arr, n){ let i, cnt0 = 0, cnt1 = 0, cnt2 = 0; // Count the number of 0s, 1s and // 2s in the array for (i = 0; i < n; i++) { switch (arr[i]) { case 0: cnt0++; break; case 1: cnt1++; break; case 2: cnt2++; break; } } // Update the array i = 0; // Store all the 0s in the // beginning while (cnt0 > 0) { arr[i++] = 0; cnt0--; } // Then all the 1s while (cnt1 > 0) { arr[i++] = 1; cnt1--; } // Finally all the 2s while (cnt2 > 0) { arr[i++] = 2; cnt2--; } // Print the sorted array printArr(arr, n);} // Driver codelet arr = [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1]; let n = arr.length; // Function callingsortArr(arr, n);// This code is contributed by jana_sayantan.</script>Output:0 0 0 0 0 1 1 1 1 1 2 2Complexity Analysis:Time Complexity: O(n). Only two traversals of the array is needed.Space Complexity: O(1). As no extra space is required.Please refer complete article on Sort an array of 0s, 1s and 2s for more details!My Personal Notes
arrow_drop_upSave
a[1..Lo-1] zeroes (red)
a[Lo..Mid-1] ones (white)
a[Mid..Hi] unknown
a[Hi+1..N] twos (blue)
If the ith element is 0 then swap the element to the low range, thus shrinking the unknown range.
Similarly, if the element is 1 then keep it as it is but shrink the unknown range.
If the element is 2 then swap it with an element in high range.Algorithm: Keep three indices low = 1, mid = 1 and high = N and there are four ranges, 1 to low (the range containing 0), low to mid (the range containing 1), mid to high (the range containing unknown elements) and high to N (the range containing 2).Traverse the array from start to end and mid is less than high. (Loop counter is i)If the element is 0 then swap the element with the element at index low and update low = low + 1 and mid = mid + 1If the element is 1 then update mid = mid + 1If the element is 2 then swap the element with the element at index high and update high = high – 1 and update i = i – 1. As the swapped element is not processedPrint the output array.Dry Run: Part way through the process, some red, white and blue elements are known and are in the “right” place. The section of unknown elements, a[Mid..Hi], is shrunk by examining a[Mid]:Examine a[Mid]. There are three possibilities: a[Mid] is (0) red, (1) white or (2) blue. Case (0) a[Mid] is red, swap a[Lo] and a[Mid]; Lo++; Mid++ Case (1) a[Mid] is white, Mid++Case (2) a[Mid] is blue, swap a[Mid] and a[Hi]; Hi–Continue until Mid>Hi.Implementation:JavascriptJavascript<script>// Javascript program to sort an // array of 0, 1 and 2 // Sort the input array, the array is // assumed to have values in {0, 1, 2} function sort012(a, arr_size){ let lo = 0; let hi = arr_size - 1; let mid = 0; let temp = 0; while (mid <= hi) { if(a[mid] == 0) { temp = a[lo]; a[lo] = a[mid]; a[mid] = temp; lo++; mid++; } else if(a[mid] == 1) { mid++; } else { temp = a[mid]; a[mid] = a[hi]; a[hi] = temp; hi--; } }} /* Utility function to print array arr[] */function printArray(arr, arr_size){ let i; for (i = 0; i < arr_size; i++) { document.write(arr[i] + " "); } document.write("<br>");} // Driver codelet arr= [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 ];let arr_size = arr.length;sort012(arr, arr_size);document.write("Array after seggregation <br>")printArray(arr, arr_size); // This code is contributed by rag2127</script>Output: array after segregation
0 0 0 0 0 1 1 1 1 1 2 2 Complexity Analysis: Time Complexity: O(n). Only one traversal of the array is needed.Space Complexity: O(1). No extra space is required.Method 2:Approach: Count the number of 0s, 1s and 2s in the given array. Then store all the 0s in the beginning followed by all the 1s then all the 2s.Algorithm: Keep three counter c0 to count 0s, c1 to count 1s and c2 to count 2sTraverse through the array and increase the count of c0 if the element is 0,increase the count of c1 if the element is 1 and increase the count of c2 if the element is 2Now again traverse the array and replace first c0 elements with 0, next c1 elements with 1 and next c2 elements with 2.Implementation:JavascriptJavascript<script>// Javascript implementation of the // approach // Utility function to print the // contents of an arrayfunction printArr( arr, n){ for (let i = 0; i < n; i++) document.write(arr[i] + " ");} // Function to sort the array of 0s, // 1s and 2sfunction sortArr( arr, n){ let i, cnt0 = 0, cnt1 = 0, cnt2 = 0; // Count the number of 0s, 1s and // 2s in the array for (i = 0; i < n; i++) { switch (arr[i]) { case 0: cnt0++; break; case 1: cnt1++; break; case 2: cnt2++; break; } } // Update the array i = 0; // Store all the 0s in the // beginning while (cnt0 > 0) { arr[i++] = 0; cnt0--; } // Then all the 1s while (cnt1 > 0) { arr[i++] = 1; cnt1--; } // Finally all the 2s while (cnt2 > 0) { arr[i++] = 2; cnt2--; } // Print the sorted array printArr(arr, n);} // Driver codelet arr = [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1]; let n = arr.length; // Function callingsortArr(arr, n);// This code is contributed by jana_sayantan.</script>Output:0 0 0 0 0 1 1 1 1 1 2 2Complexity Analysis:Time Complexity: O(n). Only two traversals of the array is needed.Space Complexity: O(1). As no extra space is required.Please refer complete article on Sort an array of 0s, 1s and 2s for more details!My Personal Notes
arrow_drop_upSave
Algorithm:
Keep three indices low = 1, mid = 1 and high = N and there are four ranges, 1 to low (the range containing 0), low to mid (the range containing 1), mid to high (the range containing unknown elements) and high to N (the range containing 2).Traverse the array from start to end and mid is less than high. (Loop counter is i)If the element is 0 then swap the element with the element at index low and update low = low + 1 and mid = mid + 1If the element is 1 then update mid = mid + 1If the element is 2 then swap the element with the element at index high and update high = high – 1 and update i = i – 1. As the swapped element is not processedPrint the output array.Dry Run: Part way through the process, some red, white and blue elements are known and are in the “right” place. The section of unknown elements, a[Mid..Hi], is shrunk by examining a[Mid]:Examine a[Mid]. There are three possibilities: a[Mid] is (0) red, (1) white or (2) blue. Case (0) a[Mid] is red, swap a[Lo] and a[Mid]; Lo++; Mid++ Case (1) a[Mid] is white, Mid++Case (2) a[Mid] is blue, swap a[Mid] and a[Hi]; Hi–Continue until Mid>Hi.Implementation:JavascriptJavascript<script>// Javascript program to sort an // array of 0, 1 and 2 // Sort the input array, the array is // assumed to have values in {0, 1, 2} function sort012(a, arr_size){ let lo = 0; let hi = arr_size - 1; let mid = 0; let temp = 0; while (mid <= hi) { if(a[mid] == 0) { temp = a[lo]; a[lo] = a[mid]; a[mid] = temp; lo++; mid++; } else if(a[mid] == 1) { mid++; } else { temp = a[mid]; a[mid] = a[hi]; a[hi] = temp; hi--; } }} /* Utility function to print array arr[] */function printArray(arr, arr_size){ let i; for (i = 0; i < arr_size; i++) { document.write(arr[i] + " "); } document.write("<br>");} // Driver codelet arr= [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 ];let arr_size = arr.length;sort012(arr, arr_size);document.write("Array after seggregation <br>")printArray(arr, arr_size); // This code is contributed by rag2127</script>Output: array after segregation
0 0 0 0 0 1 1 1 1 1 2 2 Complexity Analysis: Time Complexity: O(n). Only one traversal of the array is needed.Space Complexity: O(1). No extra space is required.Method 2:Approach: Count the number of 0s, 1s and 2s in the given array. Then store all the 0s in the beginning followed by all the 1s then all the 2s.Algorithm: Keep three counter c0 to count 0s, c1 to count 1s and c2 to count 2sTraverse through the array and increase the count of c0 if the element is 0,increase the count of c1 if the element is 1 and increase the count of c2 if the element is 2Now again traverse the array and replace first c0 elements with 0, next c1 elements with 1 and next c2 elements with 2.Implementation:JavascriptJavascript<script>// Javascript implementation of the // approach // Utility function to print the // contents of an arrayfunction printArr( arr, n){ for (let i = 0; i < n; i++) document.write(arr[i] + " ");} // Function to sort the array of 0s, // 1s and 2sfunction sortArr( arr, n){ let i, cnt0 = 0, cnt1 = 0, cnt2 = 0; // Count the number of 0s, 1s and // 2s in the array for (i = 0; i < n; i++) { switch (arr[i]) { case 0: cnt0++; break; case 1: cnt1++; break; case 2: cnt2++; break; } } // Update the array i = 0; // Store all the 0s in the // beginning while (cnt0 > 0) { arr[i++] = 0; cnt0--; } // Then all the 1s while (cnt1 > 0) { arr[i++] = 1; cnt1--; } // Finally all the 2s while (cnt2 > 0) { arr[i++] = 2; cnt2--; } // Print the sorted array printArr(arr, n);} // Driver codelet arr = [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1]; let n = arr.length; // Function callingsortArr(arr, n);// This code is contributed by jana_sayantan.</script>Output:0 0 0 0 0 1 1 1 1 1 2 2Complexity Analysis:Time Complexity: O(n). Only two traversals of the array is needed.Space Complexity: O(1). As no extra space is required.Please refer complete article on Sort an array of 0s, 1s and 2s for more details!My Personal Notes
arrow_drop_upSave
Keep three indices low = 1, mid = 1 and high = N and there are four ranges, 1 to low (the range containing 0), low to mid (the range containing 1), mid to high (the range containing unknown elements) and high to N (the range containing 2).
Traverse the array from start to end and mid is less than high. (Loop counter is i)
If the element is 0 then swap the element with the element at index low and update low = low + 1 and mid = mid + 1
If the element is 1 then update mid = mid + 1
If the element is 2 then swap the element with the element at index high and update high = high – 1 and update i = i – 1. As the swapped element is not processed
Print the output array.Dry Run: Part way through the process, some red, white and blue elements are known and are in the “right” place. The section of unknown elements, a[Mid..Hi], is shrunk by examining a[Mid]:Examine a[Mid]. There are three possibilities: a[Mid] is (0) red, (1) white or (2) blue. Case (0) a[Mid] is red, swap a[Lo] and a[Mid]; Lo++; Mid++ Case (1) a[Mid] is white, Mid++Case (2) a[Mid] is blue, swap a[Mid] and a[Hi]; Hi–Continue until Mid>Hi.Implementation:JavascriptJavascript<script>// Javascript program to sort an // array of 0, 1 and 2 // Sort the input array, the array is // assumed to have values in {0, 1, 2} function sort012(a, arr_size){ let lo = 0; let hi = arr_size - 1; let mid = 0; let temp = 0; while (mid <= hi) { if(a[mid] == 0) { temp = a[lo]; a[lo] = a[mid]; a[mid] = temp; lo++; mid++; } else if(a[mid] == 1) { mid++; } else { temp = a[mid]; a[mid] = a[hi]; a[hi] = temp; hi--; } }} /* Utility function to print array arr[] */function printArray(arr, arr_size){ let i; for (i = 0; i < arr_size; i++) { document.write(arr[i] + " "); } document.write("<br>");} // Driver codelet arr= [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 ];let arr_size = arr.length;sort012(arr, arr_size);document.write("Array after seggregation <br>")printArray(arr, arr_size); // This code is contributed by rag2127</script>Output: array after segregation
0 0 0 0 0 1 1 1 1 1 2 2 Complexity Analysis: Time Complexity: O(n). Only one traversal of the array is needed.Space Complexity: O(1). No extra space is required.Method 2:Approach: Count the number of 0s, 1s and 2s in the given array. Then store all the 0s in the beginning followed by all the 1s then all the 2s.Algorithm: Keep three counter c0 to count 0s, c1 to count 1s and c2 to count 2sTraverse through the array and increase the count of c0 if the element is 0,increase the count of c1 if the element is 1 and increase the count of c2 if the element is 2Now again traverse the array and replace first c0 elements with 0, next c1 elements with 1 and next c2 elements with 2.Implementation:JavascriptJavascript<script>// Javascript implementation of the // approach // Utility function to print the // contents of an arrayfunction printArr( arr, n){ for (let i = 0; i < n; i++) document.write(arr[i] + " ");} // Function to sort the array of 0s, // 1s and 2sfunction sortArr( arr, n){ let i, cnt0 = 0, cnt1 = 0, cnt2 = 0; // Count the number of 0s, 1s and // 2s in the array for (i = 0; i < n; i++) { switch (arr[i]) { case 0: cnt0++; break; case 1: cnt1++; break; case 2: cnt2++; break; } } // Update the array i = 0; // Store all the 0s in the // beginning while (cnt0 > 0) { arr[i++] = 0; cnt0--; } // Then all the 1s while (cnt1 > 0) { arr[i++] = 1; cnt1--; } // Finally all the 2s while (cnt2 > 0) { arr[i++] = 2; cnt2--; } // Print the sorted array printArr(arr, n);} // Driver codelet arr = [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1]; let n = arr.length; // Function callingsortArr(arr, n);// This code is contributed by jana_sayantan.</script>Output:0 0 0 0 0 1 1 1 1 1 2 2Complexity Analysis:Time Complexity: O(n). Only two traversals of the array is needed.Space Complexity: O(1). As no extra space is required.Please refer complete article on Sort an array of 0s, 1s and 2s for more details!My Personal Notes
arrow_drop_upSave
Dry Run: Part way through the process, some red, white and blue elements are known and are in the “right” place. The section of unknown elements, a[Mid..Hi], is shrunk by examining a[Mid]:
Examine a[Mid]. There are three possibilities: a[Mid] is (0) red, (1) white or (2) blue. Case (0) a[Mid] is red, swap a[Lo] and a[Mid]; Lo++; Mid++
Case (1) a[Mid] is white, Mid++
Case (2) a[Mid] is blue, swap a[Mid] and a[Hi]; Hi–
Continue until Mid>Hi.
Implementation:
Javascript
<script>// Javascript program to sort an // array of 0, 1 and 2 // Sort the input array, the array is // assumed to have values in {0, 1, 2} function sort012(a, arr_size){ let lo = 0; let hi = arr_size - 1; let mid = 0; let temp = 0; while (mid <= hi) { if(a[mid] == 0) { temp = a[lo]; a[lo] = a[mid]; a[mid] = temp; lo++; mid++; } else if(a[mid] == 1) { mid++; } else { temp = a[mid]; a[mid] = a[hi]; a[hi] = temp; hi--; } }} /* Utility function to print array arr[] */function printArray(arr, arr_size){ let i; for (i = 0; i < arr_size; i++) { document.write(arr[i] + " "); } document.write("<br>");} // Driver codelet arr= [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 ];let arr_size = arr.length;sort012(arr, arr_size);document.write("Array after seggregation <br>")printArray(arr, arr_size); // This code is contributed by rag2127</script>
Output:
array after segregation
0 0 0 0 0 1 1 1 1 1 2 2
Complexity Analysis:
Time Complexity: O(n). Only one traversal of the array is needed.
Space Complexity: O(1). No extra space is required.Method 2:Approach: Count the number of 0s, 1s and 2s in the given array. Then store all the 0s in the beginning followed by all the 1s then all the 2s.Algorithm: Keep three counter c0 to count 0s, c1 to count 1s and c2 to count 2sTraverse through the array and increase the count of c0 if the element is 0,increase the count of c1 if the element is 1 and increase the count of c2 if the element is 2Now again traverse the array and replace first c0 elements with 0, next c1 elements with 1 and next c2 elements with 2.Implementation:JavascriptJavascript<script>// Javascript implementation of the // approach // Utility function to print the // contents of an arrayfunction printArr( arr, n){ for (let i = 0; i < n; i++) document.write(arr[i] + " ");} // Function to sort the array of 0s, // 1s and 2sfunction sortArr( arr, n){ let i, cnt0 = 0, cnt1 = 0, cnt2 = 0; // Count the number of 0s, 1s and // 2s in the array for (i = 0; i < n; i++) { switch (arr[i]) { case 0: cnt0++; break; case 1: cnt1++; break; case 2: cnt2++; break; } } // Update the array i = 0; // Store all the 0s in the // beginning while (cnt0 > 0) { arr[i++] = 0; cnt0--; } // Then all the 1s while (cnt1 > 0) { arr[i++] = 1; cnt1--; } // Finally all the 2s while (cnt2 > 0) { arr[i++] = 2; cnt2--; } // Print the sorted array printArr(arr, n);} // Driver codelet arr = [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1]; let n = arr.length; // Function callingsortArr(arr, n);// This code is contributed by jana_sayantan.</script>Output:0 0 0 0 0 1 1 1 1 1 2 2Complexity Analysis:Time Complexity: O(n). Only two traversals of the array is needed.Space Complexity: O(1). As no extra space is required.Please refer complete article on Sort an array of 0s, 1s and 2s for more details!My Personal Notes
arrow_drop_upSave
Method 2:
Approach: Count the number of 0s, 1s and 2s in the given array. Then store all the 0s in the beginning followed by all the 1s then all the 2s.
Algorithm:
Keep three counter c0 to count 0s, c1 to count 1s and c2 to count 2sTraverse through the array and increase the count of c0 if the element is 0,increase the count of c1 if the element is 1 and increase the count of c2 if the element is 2Now again traverse the array and replace first c0 elements with 0, next c1 elements with 1 and next c2 elements with 2.
Keep three counter c0 to count 0s, c1 to count 1s and c2 to count 2s
Traverse through the array and increase the count of c0 if the element is 0,increase the count of c1 if the element is 1 and increase the count of c2 if the element is 2
Now again traverse the array and replace first c0 elements with 0, next c1 elements with 1 and next c2 elements with 2.
Implementation:
Javascript
<script>// Javascript implementation of the // approach // Utility function to print the // contents of an arrayfunction printArr( arr, n){ for (let i = 0; i < n; i++) document.write(arr[i] + " ");} // Function to sort the array of 0s, // 1s and 2sfunction sortArr( arr, n){ let i, cnt0 = 0, cnt1 = 0, cnt2 = 0; // Count the number of 0s, 1s and // 2s in the array for (i = 0; i < n; i++) { switch (arr[i]) { case 0: cnt0++; break; case 1: cnt1++; break; case 2: cnt2++; break; } } // Update the array i = 0; // Store all the 0s in the // beginning while (cnt0 > 0) { arr[i++] = 0; cnt0--; } // Then all the 1s while (cnt1 > 0) { arr[i++] = 1; cnt1--; } // Finally all the 2s while (cnt2 > 0) { arr[i++] = 2; cnt2--; } // Print the sorted array printArr(arr, n);} // Driver codelet arr = [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1]; let n = arr.length; // Function callingsortArr(arr, n);// This code is contributed by jana_sayantan.</script>
Output:
0 0 0 0 0 1 1 1 1 1 2 2
Complexity Analysis:
Time Complexity: O(n). Only two traversals of the array is needed.
Space Complexity: O(1). As no extra space is required.
Please refer complete article on Sort an array of 0s, 1s and 2s for more details!
Adobe
Amazon
Hike
MakeMyTrip
MAQ Software
Microsoft
Morgan Stanley
Ola Cabs
Paytm
Qualcomm
SAP Labs
Snapdeal
Walmart
Yatra.com
Arrays
Sorting
Paytm
Morgan Stanley
Amazon
Microsoft
Snapdeal
Hike
MakeMyTrip
Ola Cabs
Walmart
MAQ Software
Adobe
Yatra.com
SAP Labs
Qualcomm
Arrays
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Next Greater Element
Window Sliding Technique
Count pairs with given sum
Program to find sum of elements in a given array
Reversal algorithm for array rotation
|
[
{
"code": null,
"e": 24405,
"s": 24377,
"text": "\n16 Dec, 2021"
},
{
"code": null,
"e": 24590,
"s": 24405,
"text": "Given an array A[] consisting 0s, 1s and 2s. The task is to write a function that sorts the given array. The functions should put all 0s first, then all 1s and all 2s in last.Examples:"
},
{
"code": null,
"e": 24733,
"s": 24590,
"text": "Input: {0, 1, 2, 0, 1, 2}\nOutput: {0, 0, 1, 1, 2, 2}\n\nInput: {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}\nOutput: {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2}"
},
{
"code": null,
"e": 24837,
"s": 24733,
"text": "A simple solution is discussed in this(Sort an array of 0s, 1s and 2s (Simple Counting)) post.Method 1:"
},
{
"code": null,
"e": 25104,
"s": 24837,
"text": "Approach:The problem is similar to our old post Segregate 0s and 1s in an array, and both of these problems are variation of famous Dutch national flag problem.The problem was posed with three colours, here `0′, `1′ and `2′. The array is divided into four sections: "
},
{
"code": null,
"e": 29934,
"s": 25104,
"text": "a[1..Lo-1] zeroes (red)a[Lo..Mid-1] ones (white)a[Mid..Hi] unknowna[Hi+1..N] twos (blue)If the ith element is 0 then swap the element to the low range, thus shrinking the unknown range.Similarly, if the element is 1 then keep it as it is but shrink the unknown range.If the element is 2 then swap it with an element in high range.Algorithm: Keep three indices low = 1, mid = 1 and high = N and there are four ranges, 1 to low (the range containing 0), low to mid (the range containing 1), mid to high (the range containing unknown elements) and high to N (the range containing 2).Traverse the array from start to end and mid is less than high. (Loop counter is i)If the element is 0 then swap the element with the element at index low and update low = low + 1 and mid = mid + 1If the element is 1 then update mid = mid + 1If the element is 2 then swap the element with the element at index high and update high = high – 1 and update i = i – 1. As the swapped element is not processedPrint the output array.Dry Run: Part way through the process, some red, white and blue elements are known and are in the “right” place. The section of unknown elements, a[Mid..Hi], is shrunk by examining a[Mid]:Examine a[Mid]. There are three possibilities: a[Mid] is (0) red, (1) white or (2) blue. Case (0) a[Mid] is red, swap a[Lo] and a[Mid]; Lo++; Mid++ Case (1) a[Mid] is white, Mid++Case (2) a[Mid] is blue, swap a[Mid] and a[Hi]; Hi–Continue until Mid>Hi.Implementation:JavascriptJavascript<script>// Javascript program to sort an // array of 0, 1 and 2 // Sort the input array, the array is // assumed to have values in {0, 1, 2} function sort012(a, arr_size){ let lo = 0; let hi = arr_size - 1; let mid = 0; let temp = 0; while (mid <= hi) { if(a[mid] == 0) { temp = a[lo]; a[lo] = a[mid]; a[mid] = temp; lo++; mid++; } else if(a[mid] == 1) { mid++; } else { temp = a[mid]; a[mid] = a[hi]; a[hi] = temp; hi--; } }} /* Utility function to print array arr[] */function printArray(arr, arr_size){ let i; for (i = 0; i < arr_size; i++) { document.write(arr[i] + \" \"); } document.write(\"<br>\");} // Driver codelet arr= [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 ];let arr_size = arr.length;sort012(arr, arr_size);document.write(\"Array after seggregation <br>\")printArray(arr, arr_size); // This code is contributed by rag2127</script>Output: array after segregation\n 0 0 0 0 0 1 1 1 1 1 2 2 Complexity Analysis: Time Complexity: O(n). Only one traversal of the array is needed.Space Complexity: O(1). No extra space is required.Method 2:Approach: Count the number of 0s, 1s and 2s in the given array. Then store all the 0s in the beginning followed by all the 1s then all the 2s.Algorithm: Keep three counter c0 to count 0s, c1 to count 1s and c2 to count 2sTraverse through the array and increase the count of c0 if the element is 0,increase the count of c1 if the element is 1 and increase the count of c2 if the element is 2Now again traverse the array and replace first c0 elements with 0, next c1 elements with 1 and next c2 elements with 2.Implementation:JavascriptJavascript<script>// Javascript implementation of the // approach // Utility function to print the // contents of an arrayfunction printArr( arr, n){ for (let i = 0; i < n; i++) document.write(arr[i] + \" \");} // Function to sort the array of 0s, // 1s and 2sfunction sortArr( arr, n){ let i, cnt0 = 0, cnt1 = 0, cnt2 = 0; // Count the number of 0s, 1s and // 2s in the array for (i = 0; i < n; i++) { switch (arr[i]) { case 0: cnt0++; break; case 1: cnt1++; break; case 2: cnt2++; break; } } // Update the array i = 0; // Store all the 0s in the // beginning while (cnt0 > 0) { arr[i++] = 0; cnt0--; } // Then all the 1s while (cnt1 > 0) { arr[i++] = 1; cnt1--; } // Finally all the 2s while (cnt2 > 0) { arr[i++] = 2; cnt2--; } // Print the sorted array printArr(arr, n);} // Driver codelet arr = [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1]; let n = arr.length; // Function callingsortArr(arr, n);// This code is contributed by jana_sayantan.</script>Output:0 0 0 0 0 1 1 1 1 1 2 2Complexity Analysis:Time Complexity: O(n). Only two traversals of the array is needed.Space Complexity: O(1). As no extra space is required.Please refer complete article on Sort an array of 0s, 1s and 2s for more details!My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 29958,
"s": 29934,
"text": "a[1..Lo-1] zeroes (red)"
},
{
"code": null,
"e": 29984,
"s": 29958,
"text": "a[Lo..Mid-1] ones (white)"
},
{
"code": null,
"e": 30003,
"s": 29984,
"text": "a[Mid..Hi] unknown"
},
{
"code": null,
"e": 30026,
"s": 30003,
"text": "a[Hi+1..N] twos (blue)"
},
{
"code": null,
"e": 30124,
"s": 30026,
"text": "If the ith element is 0 then swap the element to the low range, thus shrinking the unknown range."
},
{
"code": null,
"e": 30207,
"s": 30124,
"text": "Similarly, if the element is 1 then keep it as it is but shrink the unknown range."
},
{
"code": null,
"e": 34770,
"s": 30207,
"text": "If the element is 2 then swap it with an element in high range.Algorithm: Keep three indices low = 1, mid = 1 and high = N and there are four ranges, 1 to low (the range containing 0), low to mid (the range containing 1), mid to high (the range containing unknown elements) and high to N (the range containing 2).Traverse the array from start to end and mid is less than high. (Loop counter is i)If the element is 0 then swap the element with the element at index low and update low = low + 1 and mid = mid + 1If the element is 1 then update mid = mid + 1If the element is 2 then swap the element with the element at index high and update high = high – 1 and update i = i – 1. As the swapped element is not processedPrint the output array.Dry Run: Part way through the process, some red, white and blue elements are known and are in the “right” place. The section of unknown elements, a[Mid..Hi], is shrunk by examining a[Mid]:Examine a[Mid]. There are three possibilities: a[Mid] is (0) red, (1) white or (2) blue. Case (0) a[Mid] is red, swap a[Lo] and a[Mid]; Lo++; Mid++ Case (1) a[Mid] is white, Mid++Case (2) a[Mid] is blue, swap a[Mid] and a[Hi]; Hi–Continue until Mid>Hi.Implementation:JavascriptJavascript<script>// Javascript program to sort an // array of 0, 1 and 2 // Sort the input array, the array is // assumed to have values in {0, 1, 2} function sort012(a, arr_size){ let lo = 0; let hi = arr_size - 1; let mid = 0; let temp = 0; while (mid <= hi) { if(a[mid] == 0) { temp = a[lo]; a[lo] = a[mid]; a[mid] = temp; lo++; mid++; } else if(a[mid] == 1) { mid++; } else { temp = a[mid]; a[mid] = a[hi]; a[hi] = temp; hi--; } }} /* Utility function to print array arr[] */function printArray(arr, arr_size){ let i; for (i = 0; i < arr_size; i++) { document.write(arr[i] + \" \"); } document.write(\"<br>\");} // Driver codelet arr= [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 ];let arr_size = arr.length;sort012(arr, arr_size);document.write(\"Array after seggregation <br>\")printArray(arr, arr_size); // This code is contributed by rag2127</script>Output: array after segregation\n 0 0 0 0 0 1 1 1 1 1 2 2 Complexity Analysis: Time Complexity: O(n). Only one traversal of the array is needed.Space Complexity: O(1). No extra space is required.Method 2:Approach: Count the number of 0s, 1s and 2s in the given array. Then store all the 0s in the beginning followed by all the 1s then all the 2s.Algorithm: Keep three counter c0 to count 0s, c1 to count 1s and c2 to count 2sTraverse through the array and increase the count of c0 if the element is 0,increase the count of c1 if the element is 1 and increase the count of c2 if the element is 2Now again traverse the array and replace first c0 elements with 0, next c1 elements with 1 and next c2 elements with 2.Implementation:JavascriptJavascript<script>// Javascript implementation of the // approach // Utility function to print the // contents of an arrayfunction printArr( arr, n){ for (let i = 0; i < n; i++) document.write(arr[i] + \" \");} // Function to sort the array of 0s, // 1s and 2sfunction sortArr( arr, n){ let i, cnt0 = 0, cnt1 = 0, cnt2 = 0; // Count the number of 0s, 1s and // 2s in the array for (i = 0; i < n; i++) { switch (arr[i]) { case 0: cnt0++; break; case 1: cnt1++; break; case 2: cnt2++; break; } } // Update the array i = 0; // Store all the 0s in the // beginning while (cnt0 > 0) { arr[i++] = 0; cnt0--; } // Then all the 1s while (cnt1 > 0) { arr[i++] = 1; cnt1--; } // Finally all the 2s while (cnt2 > 0) { arr[i++] = 2; cnt2--; } // Print the sorted array printArr(arr, n);} // Driver codelet arr = [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1]; let n = arr.length; // Function callingsortArr(arr, n);// This code is contributed by jana_sayantan.</script>Output:0 0 0 0 0 1 1 1 1 1 2 2Complexity Analysis:Time Complexity: O(n). Only two traversals of the array is needed.Space Complexity: O(1). As no extra space is required.Please refer complete article on Sort an array of 0s, 1s and 2s for more details!My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 34782,
"s": 34770,
"text": "Algorithm: "
},
{
"code": null,
"e": 39271,
"s": 34782,
"text": "Keep three indices low = 1, mid = 1 and high = N and there are four ranges, 1 to low (the range containing 0), low to mid (the range containing 1), mid to high (the range containing unknown elements) and high to N (the range containing 2).Traverse the array from start to end and mid is less than high. (Loop counter is i)If the element is 0 then swap the element with the element at index low and update low = low + 1 and mid = mid + 1If the element is 1 then update mid = mid + 1If the element is 2 then swap the element with the element at index high and update high = high – 1 and update i = i – 1. As the swapped element is not processedPrint the output array.Dry Run: Part way through the process, some red, white and blue elements are known and are in the “right” place. The section of unknown elements, a[Mid..Hi], is shrunk by examining a[Mid]:Examine a[Mid]. There are three possibilities: a[Mid] is (0) red, (1) white or (2) blue. Case (0) a[Mid] is red, swap a[Lo] and a[Mid]; Lo++; Mid++ Case (1) a[Mid] is white, Mid++Case (2) a[Mid] is blue, swap a[Mid] and a[Hi]; Hi–Continue until Mid>Hi.Implementation:JavascriptJavascript<script>// Javascript program to sort an // array of 0, 1 and 2 // Sort the input array, the array is // assumed to have values in {0, 1, 2} function sort012(a, arr_size){ let lo = 0; let hi = arr_size - 1; let mid = 0; let temp = 0; while (mid <= hi) { if(a[mid] == 0) { temp = a[lo]; a[lo] = a[mid]; a[mid] = temp; lo++; mid++; } else if(a[mid] == 1) { mid++; } else { temp = a[mid]; a[mid] = a[hi]; a[hi] = temp; hi--; } }} /* Utility function to print array arr[] */function printArray(arr, arr_size){ let i; for (i = 0; i < arr_size; i++) { document.write(arr[i] + \" \"); } document.write(\"<br>\");} // Driver codelet arr= [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 ];let arr_size = arr.length;sort012(arr, arr_size);document.write(\"Array after seggregation <br>\")printArray(arr, arr_size); // This code is contributed by rag2127</script>Output: array after segregation\n 0 0 0 0 0 1 1 1 1 1 2 2 Complexity Analysis: Time Complexity: O(n). Only one traversal of the array is needed.Space Complexity: O(1). No extra space is required.Method 2:Approach: Count the number of 0s, 1s and 2s in the given array. Then store all the 0s in the beginning followed by all the 1s then all the 2s.Algorithm: Keep three counter c0 to count 0s, c1 to count 1s and c2 to count 2sTraverse through the array and increase the count of c0 if the element is 0,increase the count of c1 if the element is 1 and increase the count of c2 if the element is 2Now again traverse the array and replace first c0 elements with 0, next c1 elements with 1 and next c2 elements with 2.Implementation:JavascriptJavascript<script>// Javascript implementation of the // approach // Utility function to print the // contents of an arrayfunction printArr( arr, n){ for (let i = 0; i < n; i++) document.write(arr[i] + \" \");} // Function to sort the array of 0s, // 1s and 2sfunction sortArr( arr, n){ let i, cnt0 = 0, cnt1 = 0, cnt2 = 0; // Count the number of 0s, 1s and // 2s in the array for (i = 0; i < n; i++) { switch (arr[i]) { case 0: cnt0++; break; case 1: cnt1++; break; case 2: cnt2++; break; } } // Update the array i = 0; // Store all the 0s in the // beginning while (cnt0 > 0) { arr[i++] = 0; cnt0--; } // Then all the 1s while (cnt1 > 0) { arr[i++] = 1; cnt1--; } // Finally all the 2s while (cnt2 > 0) { arr[i++] = 2; cnt2--; } // Print the sorted array printArr(arr, n);} // Driver codelet arr = [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1]; let n = arr.length; // Function callingsortArr(arr, n);// This code is contributed by jana_sayantan.</script>Output:0 0 0 0 0 1 1 1 1 1 2 2Complexity Analysis:Time Complexity: O(n). Only two traversals of the array is needed.Space Complexity: O(1). As no extra space is required.Please refer complete article on Sort an array of 0s, 1s and 2s for more details!My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 39511,
"s": 39271,
"text": "Keep three indices low = 1, mid = 1 and high = N and there are four ranges, 1 to low (the range containing 0), low to mid (the range containing 1), mid to high (the range containing unknown elements) and high to N (the range containing 2)."
},
{
"code": null,
"e": 39595,
"s": 39511,
"text": "Traverse the array from start to end and mid is less than high. (Loop counter is i)"
},
{
"code": null,
"e": 39710,
"s": 39595,
"text": "If the element is 0 then swap the element with the element at index low and update low = low + 1 and mid = mid + 1"
},
{
"code": null,
"e": 39756,
"s": 39710,
"text": "If the element is 1 then update mid = mid + 1"
},
{
"code": null,
"e": 39918,
"s": 39756,
"text": "If the element is 2 then swap the element with the element at index high and update high = high – 1 and update i = i – 1. As the swapped element is not processed"
},
{
"code": null,
"e": 43765,
"s": 39918,
"text": "Print the output array.Dry Run: Part way through the process, some red, white and blue elements are known and are in the “right” place. The section of unknown elements, a[Mid..Hi], is shrunk by examining a[Mid]:Examine a[Mid]. There are three possibilities: a[Mid] is (0) red, (1) white or (2) blue. Case (0) a[Mid] is red, swap a[Lo] and a[Mid]; Lo++; Mid++ Case (1) a[Mid] is white, Mid++Case (2) a[Mid] is blue, swap a[Mid] and a[Hi]; Hi–Continue until Mid>Hi.Implementation:JavascriptJavascript<script>// Javascript program to sort an // array of 0, 1 and 2 // Sort the input array, the array is // assumed to have values in {0, 1, 2} function sort012(a, arr_size){ let lo = 0; let hi = arr_size - 1; let mid = 0; let temp = 0; while (mid <= hi) { if(a[mid] == 0) { temp = a[lo]; a[lo] = a[mid]; a[mid] = temp; lo++; mid++; } else if(a[mid] == 1) { mid++; } else { temp = a[mid]; a[mid] = a[hi]; a[hi] = temp; hi--; } }} /* Utility function to print array arr[] */function printArray(arr, arr_size){ let i; for (i = 0; i < arr_size; i++) { document.write(arr[i] + \" \"); } document.write(\"<br>\");} // Driver codelet arr= [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 ];let arr_size = arr.length;sort012(arr, arr_size);document.write(\"Array after seggregation <br>\")printArray(arr, arr_size); // This code is contributed by rag2127</script>Output: array after segregation\n 0 0 0 0 0 1 1 1 1 1 2 2 Complexity Analysis: Time Complexity: O(n). Only one traversal of the array is needed.Space Complexity: O(1). No extra space is required.Method 2:Approach: Count the number of 0s, 1s and 2s in the given array. Then store all the 0s in the beginning followed by all the 1s then all the 2s.Algorithm: Keep three counter c0 to count 0s, c1 to count 1s and c2 to count 2sTraverse through the array and increase the count of c0 if the element is 0,increase the count of c1 if the element is 1 and increase the count of c2 if the element is 2Now again traverse the array and replace first c0 elements with 0, next c1 elements with 1 and next c2 elements with 2.Implementation:JavascriptJavascript<script>// Javascript implementation of the // approach // Utility function to print the // contents of an arrayfunction printArr( arr, n){ for (let i = 0; i < n; i++) document.write(arr[i] + \" \");} // Function to sort the array of 0s, // 1s and 2sfunction sortArr( arr, n){ let i, cnt0 = 0, cnt1 = 0, cnt2 = 0; // Count the number of 0s, 1s and // 2s in the array for (i = 0; i < n; i++) { switch (arr[i]) { case 0: cnt0++; break; case 1: cnt1++; break; case 2: cnt2++; break; } } // Update the array i = 0; // Store all the 0s in the // beginning while (cnt0 > 0) { arr[i++] = 0; cnt0--; } // Then all the 1s while (cnt1 > 0) { arr[i++] = 1; cnt1--; } // Finally all the 2s while (cnt2 > 0) { arr[i++] = 2; cnt2--; } // Print the sorted array printArr(arr, n);} // Driver codelet arr = [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1]; let n = arr.length; // Function callingsortArr(arr, n);// This code is contributed by jana_sayantan.</script>Output:0 0 0 0 0 1 1 1 1 1 2 2Complexity Analysis:Time Complexity: O(n). Only two traversals of the array is needed.Space Complexity: O(1). As no extra space is required.Please refer complete article on Sort an array of 0s, 1s and 2s for more details!My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 43954,
"s": 43765,
"text": "Dry Run: Part way through the process, some red, white and blue elements are known and are in the “right” place. The section of unknown elements, a[Mid..Hi], is shrunk by examining a[Mid]:"
},
{
"code": null,
"e": 44103,
"s": 43954,
"text": "Examine a[Mid]. There are three possibilities: a[Mid] is (0) red, (1) white or (2) blue. Case (0) a[Mid] is red, swap a[Lo] and a[Mid]; Lo++; Mid++ "
},
{
"code": null,
"e": 44135,
"s": 44103,
"text": "Case (1) a[Mid] is white, Mid++"
},
{
"code": null,
"e": 44187,
"s": 44135,
"text": "Case (2) a[Mid] is blue, swap a[Mid] and a[Hi]; Hi–"
},
{
"code": null,
"e": 44210,
"s": 44187,
"text": "Continue until Mid>Hi."
},
{
"code": null,
"e": 44226,
"s": 44210,
"text": "Implementation:"
},
{
"code": null,
"e": 44237,
"s": 44226,
"text": "Javascript"
},
{
"code": "<script>// Javascript program to sort an // array of 0, 1 and 2 // Sort the input array, the array is // assumed to have values in {0, 1, 2} function sort012(a, arr_size){ let lo = 0; let hi = arr_size - 1; let mid = 0; let temp = 0; while (mid <= hi) { if(a[mid] == 0) { temp = a[lo]; a[lo] = a[mid]; a[mid] = temp; lo++; mid++; } else if(a[mid] == 1) { mid++; } else { temp = a[mid]; a[mid] = a[hi]; a[hi] = temp; hi--; } }} /* Utility function to print array arr[] */function printArray(arr, arr_size){ let i; for (i = 0; i < arr_size; i++) { document.write(arr[i] + \" \"); } document.write(\"<br>\");} // Driver codelet arr= [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 ];let arr_size = arr.length;sort012(arr, arr_size);document.write(\"Array after seggregation <br>\")printArray(arr, arr_size); // This code is contributed by rag2127</script>",
"e": 45327,
"s": 44237,
"text": null
},
{
"code": null,
"e": 45336,
"s": 45327,
"text": "Output: "
},
{
"code": null,
"e": 45386,
"s": 45336,
"text": "array after segregation\n 0 0 0 0 0 1 1 1 1 1 2 2 "
},
{
"code": null,
"e": 45408,
"s": 45386,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 45474,
"s": 45408,
"text": "Time Complexity: O(n). Only one traversal of the array is needed."
},
{
"code": null,
"e": 47591,
"s": 45474,
"text": "Space Complexity: O(1). No extra space is required.Method 2:Approach: Count the number of 0s, 1s and 2s in the given array. Then store all the 0s in the beginning followed by all the 1s then all the 2s.Algorithm: Keep three counter c0 to count 0s, c1 to count 1s and c2 to count 2sTraverse through the array and increase the count of c0 if the element is 0,increase the count of c1 if the element is 1 and increase the count of c2 if the element is 2Now again traverse the array and replace first c0 elements with 0, next c1 elements with 1 and next c2 elements with 2.Implementation:JavascriptJavascript<script>// Javascript implementation of the // approach // Utility function to print the // contents of an arrayfunction printArr( arr, n){ for (let i = 0; i < n; i++) document.write(arr[i] + \" \");} // Function to sort the array of 0s, // 1s and 2sfunction sortArr( arr, n){ let i, cnt0 = 0, cnt1 = 0, cnt2 = 0; // Count the number of 0s, 1s and // 2s in the array for (i = 0; i < n; i++) { switch (arr[i]) { case 0: cnt0++; break; case 1: cnt1++; break; case 2: cnt2++; break; } } // Update the array i = 0; // Store all the 0s in the // beginning while (cnt0 > 0) { arr[i++] = 0; cnt0--; } // Then all the 1s while (cnt1 > 0) { arr[i++] = 1; cnt1--; } // Finally all the 2s while (cnt2 > 0) { arr[i++] = 2; cnt2--; } // Print the sorted array printArr(arr, n);} // Driver codelet arr = [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1]; let n = arr.length; // Function callingsortArr(arr, n);// This code is contributed by jana_sayantan.</script>Output:0 0 0 0 0 1 1 1 1 1 2 2Complexity Analysis:Time Complexity: O(n). Only two traversals of the array is needed.Space Complexity: O(1). As no extra space is required.Please refer complete article on Sort an array of 0s, 1s and 2s for more details!My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 47601,
"s": 47591,
"text": "Method 2:"
},
{
"code": null,
"e": 47744,
"s": 47601,
"text": "Approach: Count the number of 0s, 1s and 2s in the given array. Then store all the 0s in the beginning followed by all the 1s then all the 2s."
},
{
"code": null,
"e": 47756,
"s": 47744,
"text": "Algorithm: "
},
{
"code": null,
"e": 48113,
"s": 47756,
"text": "Keep three counter c0 to count 0s, c1 to count 1s and c2 to count 2sTraverse through the array and increase the count of c0 if the element is 0,increase the count of c1 if the element is 1 and increase the count of c2 if the element is 2Now again traverse the array and replace first c0 elements with 0, next c1 elements with 1 and next c2 elements with 2."
},
{
"code": null,
"e": 48182,
"s": 48113,
"text": "Keep three counter c0 to count 0s, c1 to count 1s and c2 to count 2s"
},
{
"code": null,
"e": 48352,
"s": 48182,
"text": "Traverse through the array and increase the count of c0 if the element is 0,increase the count of c1 if the element is 1 and increase the count of c2 if the element is 2"
},
{
"code": null,
"e": 48472,
"s": 48352,
"text": "Now again traverse the array and replace first c0 elements with 0, next c1 elements with 1 and next c2 elements with 2."
},
{
"code": null,
"e": 48488,
"s": 48472,
"text": "Implementation:"
},
{
"code": null,
"e": 48499,
"s": 48488,
"text": "Javascript"
},
{
"code": "<script>// Javascript implementation of the // approach // Utility function to print the // contents of an arrayfunction printArr( arr, n){ for (let i = 0; i < n; i++) document.write(arr[i] + \" \");} // Function to sort the array of 0s, // 1s and 2sfunction sortArr( arr, n){ let i, cnt0 = 0, cnt1 = 0, cnt2 = 0; // Count the number of 0s, 1s and // 2s in the array for (i = 0; i < n; i++) { switch (arr[i]) { case 0: cnt0++; break; case 1: cnt1++; break; case 2: cnt2++; break; } } // Update the array i = 0; // Store all the 0s in the // beginning while (cnt0 > 0) { arr[i++] = 0; cnt0--; } // Then all the 1s while (cnt1 > 0) { arr[i++] = 1; cnt1--; } // Finally all the 2s while (cnt2 > 0) { arr[i++] = 2; cnt2--; } // Print the sorted array printArr(arr, n);} // Driver codelet arr = [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1]; let n = arr.length; // Function callingsortArr(arr, n);// This code is contributed by jana_sayantan.</script>",
"e": 49726,
"s": 48499,
"text": null
},
{
"code": null,
"e": 49734,
"s": 49726,
"text": "Output:"
},
{
"code": null,
"e": 49758,
"s": 49734,
"text": "0 0 0 0 0 1 1 1 1 1 2 2"
},
{
"code": null,
"e": 49779,
"s": 49758,
"text": "Complexity Analysis:"
},
{
"code": null,
"e": 49846,
"s": 49779,
"text": "Time Complexity: O(n). Only two traversals of the array is needed."
},
{
"code": null,
"e": 49901,
"s": 49846,
"text": "Space Complexity: O(1). As no extra space is required."
},
{
"code": null,
"e": 49983,
"s": 49901,
"text": "Please refer complete article on Sort an array of 0s, 1s and 2s for more details!"
},
{
"code": null,
"e": 49989,
"s": 49983,
"text": "Adobe"
},
{
"code": null,
"e": 49996,
"s": 49989,
"text": "Amazon"
},
{
"code": null,
"e": 50001,
"s": 49996,
"text": "Hike"
},
{
"code": null,
"e": 50012,
"s": 50001,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 50025,
"s": 50012,
"text": "MAQ Software"
},
{
"code": null,
"e": 50035,
"s": 50025,
"text": "Microsoft"
},
{
"code": null,
"e": 50050,
"s": 50035,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 50059,
"s": 50050,
"text": "Ola Cabs"
},
{
"code": null,
"e": 50065,
"s": 50059,
"text": "Paytm"
},
{
"code": null,
"e": 50074,
"s": 50065,
"text": "Qualcomm"
},
{
"code": null,
"e": 50083,
"s": 50074,
"text": "SAP Labs"
},
{
"code": null,
"e": 50092,
"s": 50083,
"text": "Snapdeal"
},
{
"code": null,
"e": 50100,
"s": 50092,
"text": "Walmart"
},
{
"code": null,
"e": 50110,
"s": 50100,
"text": "Yatra.com"
},
{
"code": null,
"e": 50117,
"s": 50110,
"text": "Arrays"
},
{
"code": null,
"e": 50125,
"s": 50117,
"text": "Sorting"
},
{
"code": null,
"e": 50131,
"s": 50125,
"text": "Paytm"
},
{
"code": null,
"e": 50146,
"s": 50131,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 50153,
"s": 50146,
"text": "Amazon"
},
{
"code": null,
"e": 50163,
"s": 50153,
"text": "Microsoft"
},
{
"code": null,
"e": 50172,
"s": 50163,
"text": "Snapdeal"
},
{
"code": null,
"e": 50177,
"s": 50172,
"text": "Hike"
},
{
"code": null,
"e": 50188,
"s": 50177,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 50197,
"s": 50188,
"text": "Ola Cabs"
},
{
"code": null,
"e": 50205,
"s": 50197,
"text": "Walmart"
},
{
"code": null,
"e": 50218,
"s": 50205,
"text": "MAQ Software"
},
{
"code": null,
"e": 50224,
"s": 50218,
"text": "Adobe"
},
{
"code": null,
"e": 50234,
"s": 50224,
"text": "Yatra.com"
},
{
"code": null,
"e": 50243,
"s": 50234,
"text": "SAP Labs"
},
{
"code": null,
"e": 50252,
"s": 50243,
"text": "Qualcomm"
},
{
"code": null,
"e": 50259,
"s": 50252,
"text": "Arrays"
},
{
"code": null,
"e": 50267,
"s": 50259,
"text": "Sorting"
},
{
"code": null,
"e": 50365,
"s": 50267,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 50374,
"s": 50365,
"text": "Comments"
},
{
"code": null,
"e": 50387,
"s": 50374,
"text": "Old Comments"
},
{
"code": null,
"e": 50408,
"s": 50387,
"text": "Next Greater Element"
},
{
"code": null,
"e": 50433,
"s": 50408,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 50460,
"s": 50433,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 50509,
"s": 50460,
"text": "Program to find sum of elements in a given array"
}
] |
Shell Scripting - Set Command - GeeksforGeeks
|
04 Jan, 2022
In this article, we will see the SET command in bash scripting.
Set command: It is used to set or unset specific flags and settings( determines the behavior of the script and helps in executing the tasks without any issue.) inside the shell environment. It can be used to change or display the shell attributes and parameters.
set -options arguments
The set command supports the following options:
It places all assignment arguments in the environment variable of a command.
Exception: It excludes all arguments that precede the command name.
It disables the processing of the ‘$ENV’ file and also imports the shell functions.
Turned on: when the real and effective user ids do not match.
For a demonstration of the use of the set command, let’s use some set command.
This option prints the commands in the sequence as they got executed or is mainly used to do some script debugging..
Code:
set -x
echo Hello
echo Romy
Output:
bar
hello
Romy
+ echo bar
+ echo hello
+ echo Romy
We can see the commands getting printed after the command execution with the ‘+’ sign.
It terminates the execution when the error occurs.
Code:(without set -e)
echo Hello
foo
echo Romy
Output:
Hello
Romy
main.sh: line 14: foo: command not found
‘foo’ is a non-existent command but bash still executed the third line after encountering the error at the second line. We can use the set command to stop termination.
Code:(with set -e)
set -e
echo Hello
foo
echo Romy
Output:
Hello
main.sh: line 15: foo: command not found
We can see that the third line is not getting printed as the execution got terminated after the second line.
Set -e command does not work with piped commands.
Example:
set -e
foo | echo " This is the piped command"
echo "executed"
Output:
This is the piped command
executed
main.sh: line 3: foo: command not found
We can see that third line is getting executed, instead of terminating the execution after the second line.
To overcome this problem, we have to use ‘set -eo pipefail’
Example:
set -eo pipefail
foo | echo " This is the piped command"
echo "executed"
Output:
This is the piped command
main.sh: line 13: foo: command not found
It can be used to assign values to positional parameters. Position of the value referenced as ${N} where N denotes the position of the parameter.
The $1 is the first positional parameter after the command. The $2 value is the second parameter, and so on.
Example:
set apple mango orange guava
echo $1
echo $2
echo $3
echo $4
Output:
apple
mango
orange
guava
In order to unset the positional parameter, run the set command followed by two hyphens(set –).
Example:
set apple mango orange guava
set --
echo $1
echo $2
echo "Hello"
Output:
Hello
We can see that nothing is getting printed corresponding to the first two commands to print positional parameters.
Picked
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
scp command in Linux with Examples
nohup Command in Linux with Examples
mv command in Linux with examples
Thread functions in C/C++
Docker - COPY Instruction
chown command in Linux with Examples
nslookup command in Linux with Examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
uniq Command in LINUX with examples
|
[
{
"code": null,
"e": 24040,
"s": 24012,
"text": "\n04 Jan, 2022"
},
{
"code": null,
"e": 24104,
"s": 24040,
"text": "In this article, we will see the SET command in bash scripting."
},
{
"code": null,
"e": 24368,
"s": 24104,
"text": "Set command: It is used to set or unset specific flags and settings( determines the behavior of the script and helps in executing the tasks without any issue.) inside the shell environment. It can be used to change or display the shell attributes and parameters. "
},
{
"code": null,
"e": 24391,
"s": 24368,
"text": "set -options arguments"
},
{
"code": null,
"e": 24439,
"s": 24391,
"text": "The set command supports the following options:"
},
{
"code": null,
"e": 24516,
"s": 24439,
"text": "It places all assignment arguments in the environment variable of a command."
},
{
"code": null,
"e": 24584,
"s": 24516,
"text": "Exception: It excludes all arguments that precede the command name."
},
{
"code": null,
"e": 24668,
"s": 24584,
"text": "It disables the processing of the ‘$ENV’ file and also imports the shell functions."
},
{
"code": null,
"e": 24731,
"s": 24668,
"text": "Turned on: when the real and effective user ids do not match."
},
{
"code": null,
"e": 24810,
"s": 24731,
"text": "For a demonstration of the use of the set command, let’s use some set command."
},
{
"code": null,
"e": 24927,
"s": 24810,
"text": "This option prints the commands in the sequence as they got executed or is mainly used to do some script debugging.."
},
{
"code": null,
"e": 24933,
"s": 24927,
"text": "Code:"
},
{
"code": null,
"e": 24961,
"s": 24933,
"text": "set -x\necho Hello\necho Romy"
},
{
"code": null,
"e": 24969,
"s": 24961,
"text": "Output:"
},
{
"code": null,
"e": 25020,
"s": 24969,
"text": "bar\nhello\nRomy\n+ echo bar\n+ echo hello\n+ echo Romy"
},
{
"code": null,
"e": 25107,
"s": 25020,
"text": "We can see the commands getting printed after the command execution with the ‘+’ sign."
},
{
"code": null,
"e": 25158,
"s": 25107,
"text": "It terminates the execution when the error occurs."
},
{
"code": null,
"e": 25180,
"s": 25158,
"text": "Code:(without set -e)"
},
{
"code": null,
"e": 25205,
"s": 25180,
"text": "echo Hello\nfoo\necho Romy"
},
{
"code": null,
"e": 25213,
"s": 25205,
"text": "Output:"
},
{
"code": null,
"e": 25265,
"s": 25213,
"text": "Hello\nRomy\nmain.sh: line 14: foo: command not found"
},
{
"code": null,
"e": 25433,
"s": 25265,
"text": "‘foo’ is a non-existent command but bash still executed the third line after encountering the error at the second line. We can use the set command to stop termination."
},
{
"code": null,
"e": 25452,
"s": 25433,
"text": "Code:(with set -e)"
},
{
"code": null,
"e": 25484,
"s": 25452,
"text": "set -e\necho Hello\nfoo\necho Romy"
},
{
"code": null,
"e": 25492,
"s": 25484,
"text": "Output:"
},
{
"code": null,
"e": 25539,
"s": 25492,
"text": "Hello\nmain.sh: line 15: foo: command not found"
},
{
"code": null,
"e": 25648,
"s": 25539,
"text": "We can see that the third line is not getting printed as the execution got terminated after the second line."
},
{
"code": null,
"e": 25698,
"s": 25648,
"text": "Set -e command does not work with piped commands."
},
{
"code": null,
"e": 25707,
"s": 25698,
"text": "Example:"
},
{
"code": null,
"e": 25770,
"s": 25707,
"text": "set -e\nfoo | echo \" This is the piped command\"\necho \"executed\""
},
{
"code": null,
"e": 25778,
"s": 25770,
"text": "Output:"
},
{
"code": null,
"e": 25854,
"s": 25778,
"text": " This is the piped command\nexecuted\nmain.sh: line 3: foo: command not found"
},
{
"code": null,
"e": 25962,
"s": 25854,
"text": "We can see that third line is getting executed, instead of terminating the execution after the second line."
},
{
"code": null,
"e": 26022,
"s": 25962,
"text": "To overcome this problem, we have to use ‘set -eo pipefail’"
},
{
"code": null,
"e": 26031,
"s": 26022,
"text": "Example:"
},
{
"code": null,
"e": 26106,
"s": 26031,
"text": "set -eo pipefail\n\nfoo | echo \" This is the piped command\"\n\necho \"executed\""
},
{
"code": null,
"e": 26114,
"s": 26106,
"text": "Output:"
},
{
"code": null,
"e": 26182,
"s": 26114,
"text": " This is the piped command\nmain.sh: line 13: foo: command not found"
},
{
"code": null,
"e": 26328,
"s": 26182,
"text": "It can be used to assign values to positional parameters. Position of the value referenced as ${N} where N denotes the position of the parameter."
},
{
"code": null,
"e": 26437,
"s": 26328,
"text": "The $1 is the first positional parameter after the command. The $2 value is the second parameter, and so on."
},
{
"code": null,
"e": 26446,
"s": 26437,
"text": "Example:"
},
{
"code": null,
"e": 26507,
"s": 26446,
"text": "set apple mango orange guava\necho $1\necho $2\necho $3\necho $4"
},
{
"code": null,
"e": 26515,
"s": 26507,
"text": "Output:"
},
{
"code": null,
"e": 26540,
"s": 26515,
"text": "apple\nmango\norange\nguava"
},
{
"code": null,
"e": 26636,
"s": 26540,
"text": "In order to unset the positional parameter, run the set command followed by two hyphens(set –)."
},
{
"code": null,
"e": 26645,
"s": 26636,
"text": "Example:"
},
{
"code": null,
"e": 26712,
"s": 26645,
"text": "set apple mango orange guava\n\nset --\necho $1\necho $2\n\necho \"Hello\""
},
{
"code": null,
"e": 26720,
"s": 26712,
"text": "Output:"
},
{
"code": null,
"e": 26726,
"s": 26720,
"text": "Hello"
},
{
"code": null,
"e": 26841,
"s": 26726,
"text": "We can see that nothing is getting printed corresponding to the first two commands to print positional parameters."
},
{
"code": null,
"e": 26848,
"s": 26841,
"text": "Picked"
},
{
"code": null,
"e": 26861,
"s": 26848,
"text": "Shell Script"
},
{
"code": null,
"e": 26872,
"s": 26861,
"text": "Linux-Unix"
},
{
"code": null,
"e": 26970,
"s": 26872,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26979,
"s": 26970,
"text": "Comments"
},
{
"code": null,
"e": 26992,
"s": 26979,
"text": "Old Comments"
},
{
"code": null,
"e": 27027,
"s": 26992,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 27064,
"s": 27027,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 27098,
"s": 27064,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 27124,
"s": 27098,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 27150,
"s": 27124,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 27187,
"s": 27150,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 27227,
"s": 27187,
"text": "nslookup command in Linux with Examples"
},
{
"code": null,
"e": 27256,
"s": 27227,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 27298,
"s": 27256,
"text": "Named Pipe or FIFO with example C program"
}
] |
How to convert numeric columns to factor using dplyr package in R?
|
If we have a numeric column in an R data frame and the unique number of values in the column is low that means the numerical column can be treated as a factor. Therefore, we can convert numeric columns to factor. To do this using dplyr package, we can use mutate_if function of dplyr package.
Loading dplyr package and converting numerical columns in BOD data set (available in base R) to factor columns −
library(dplyr)
str(BOD)
'data.frame': 6 obs. of 2 variables:
$ Time : num 1 2 3 4 5 7
$ demand: num 8.3 10.3 19 16 15.6 19.8
- attr(*, "reference")= chr "A1.4, p. 270"
BOD%>%mutate_if(is.numeric,as.factor)
Time demand
1 1 8.3
2 2 10.3
3 3 19
4 4 16
5 5 15.6
6 7 19.8
Converting numerical columns in Formaldehyde data set (available in base R) to factor columns −
str(Formaldehyde)
'data.frame': 6 obs. of 2 variables:
$ carb : num 0.1 0.3 0.5 0.6 0.7 0.9
$ optden: num 0.086 0.269 0.446 0.538 0.626 0.782
Formaldehyde%>%mutate_if(is.numeric,as.factor)
carb optden
1 0.1 0.086
2 0.3 0.269
3 0.5 0.446
4 0.6 0.538
5 0.7 0.626
6 0.9 0.782
Converting numerical columns in InsectSprays data set (available in base R) to factor columns −
str(InsectSprays)
'data.frame': 72 obs. of 2 variables:
$ count: num 10 7 20 14 14 12 10 23 17 20 ...
$ spray: Factor w/ 6 levels "A","B","C","D",..: 1 1 1 1 1 1 1 1 1 1 ...
InsectSprays%>%mutate_if(is.numeric,as.factor)
count spray
1 10 A
2 7 A
3 20 A
4 14 A
5 14 A
6 12 A
7 10 A
8 23 A
9 17 A
10 20 A
11 14 A
12 13 A
13 11 B
14 17 B
15 21 B
16 11 B
17 16 B
18 14 B
19 17 B
20 17 B
21 19 B
22 21 B
23 7 B
24 13 B
25 0 C
26 1 C
27 7 C
28 2 C
29 3 C
30 1 C
31 2 C
32 1 C
33 3 C
34 0 C
35 1 C
36 4 C
37 3 D
38 5 D
39 12 D
40 6 D
41 4 D
42 3 D
43 5 D
44 5 D
45 5 D
46 5 D
47 2 D
48 4 D
49 3 E
50 5 E
51 3 E
52 5 E
53 3 E
54 6 E
55 1 E
56 1 E
57 3 E
58 2 E
59 6 E
60 4 E
61 11 F
62 9 F
63 15 F
64 22 F
65 15 F
66 16 F
67 13 F
68 10 F
69 26 F
70 26 F
71 24 F
72 13 F
|
[
{
"code": null,
"e": 1355,
"s": 1062,
"text": "If we have a numeric column in an R data frame and the unique number of values in the column is low that means the numerical column can be treated as a factor. Therefore, we can convert numeric columns to factor. To do this using dplyr package, we can use mutate_if function of dplyr package."
},
{
"code": null,
"e": 1468,
"s": 1355,
"text": "Loading dplyr package and converting numerical columns in BOD data set (available in base R) to factor columns −"
},
{
"code": null,
"e": 1674,
"s": 1468,
"text": "library(dplyr)\nstr(BOD)\n'data.frame': 6 obs. of 2 variables:\n$ Time : num 1 2 3 4 5 7\n$ demand: num 8.3 10.3 19 16 15.6 19.8\n- attr(*, \"reference\")= chr \"A1.4, p. 270\"\nBOD%>%mutate_if(is.numeric,as.factor)"
},
{
"code": null,
"e": 1755,
"s": 1674,
"text": " Time demand\n1 1 8.3\n2 2 10.3\n3 3 19\n4 4 16\n5 5 15.6\n6 7 19.8"
},
{
"code": null,
"e": 1851,
"s": 1755,
"text": "Converting numerical columns in Formaldehyde data set (available in base R) to factor columns −"
},
{
"code": null,
"e": 2040,
"s": 1851,
"text": "str(Formaldehyde)\n'data.frame': 6 obs. of 2 variables:\n$ carb : num 0.1 0.3 0.5 0.6 0.7 0.9\n$ optden: num 0.086 0.269 0.446 0.538 0.626 0.782\nFormaldehyde%>%mutate_if(is.numeric,as.factor)"
},
{
"code": null,
"e": 2146,
"s": 2040,
"text": " carb optden\n1 0.1 0.086\n2 0.3 0.269\n3 0.5 0.446\n4 0.6 0.538\n5 0.7 0.626\n6 0.9 0.782"
},
{
"code": null,
"e": 2242,
"s": 2146,
"text": "Converting numerical columns in InsectSprays data set (available in base R) to factor columns −"
},
{
"code": null,
"e": 2463,
"s": 2242,
"text": "str(InsectSprays)\n'data.frame': 72 obs. of 2 variables:\n$ count: num 10 7 20 14 14 12 10 23 17 20 ...\n$ spray: Factor w/ 6 levels \"A\",\"B\",\"C\",\"D\",..: 1 1 1 1 1 1 1 1 1 1 ...\nInsectSprays%>%mutate_if(is.numeric,as.factor)"
},
{
"code": null,
"e": 3270,
"s": 2463,
"text": " count spray\n1 10 A\n2 7 A\n3 20 A\n4 14 A\n5 14 A\n6 12 A\n7 10 A\n8 23 A\n9 17 A\n10 20 A\n11 14 A\n12 13 A\n13 11 B\n14 17 B\n15 21 B\n16 11 B\n17 16 B\n18 14 B\n19 17 B\n20 17 B\n21 19 B\n22 21 B\n23 7 B\n24 13 B\n25 0 C\n26 1 C\n27 7 C\n28 2 C\n29 3 C\n30 1 C\n31 2 C\n32 1 C\n33 3 C\n34 0 C\n35 1 C\n36 4 C\n37 3 D\n38 5 D\n39 12 D\n40 6 D\n41 4 D\n42 3 D\n43 5 D\n44 5 D\n45 5 D\n46 5 D\n47 2 D\n48 4 D\n49 3 E\n50 5 E\n51 3 E\n52 5 E\n53 3 E\n54 6 E\n55 1 E\n56 1 E\n57 3 E\n58 2 E\n59 6 E\n60 4 E\n61 11 F\n62 9 F\n63 15 F\n64 22 F\n65 15 F\n66 16 F\n67 13 F\n68 10 F\n69 26 F\n70 26 F\n71 24 F\n72 13 F"
}
] |
Seaborn - Facet Grid
|
A useful approach to explore medium-dimensional data, is by drawing multiple instances of the same plot on different subsets of your dataset.
This technique is commonly called as “lattice”, or “trellis” plotting, and it is related to the idea of “small multiples”.
To use these features, your data has to be in a Pandas DataFrame.
In the previous chapter, we have seen the FacetGrid example where FacetGrid class helps in visualizing distribution of one variable as well as the relationship between multiple variables separately within subsets of your dataset using multiple panels.
A FacetGrid can be drawn with up to three dimensions − row, col, and hue. The first two have obvious correspondence with the resulting array of axes; think of the hue variable as a third dimension along a depth axis, where different levels are plotted with different colors.
FacetGrid object takes a dataframe as input and the names of the variables that will form the row, column, or hue dimensions of the grid.
The variables should be categorical and the data at each level of the variable will be used for a facet along that axis.
import pandas as pd
import seaborn as sb
from matplotlib import pyplot as plt
df = sb.load_dataset('tips')
g = sb.FacetGrid(df, col = "time")
plt.show()
In the above example, we have just initialized the facetgrid object which doesn’t draw anything on them.
The main approach for visualizing data on this grid is with the FacetGrid.map() method. Let us look at the distribution of tips in each of these subsets, using a histogram.
import pandas as pd
import seaborn as sb
from matplotlib import pyplot as plt
df = sb.load_dataset('tips')
g = sb.FacetGrid(df, col = "time")
g.map(plt.hist, "tip")
plt.show()
The number of plots is more than one because of the parameter col. We discussed about col parameter in our previous chapters.
To make a relational plot, pass the multiple variable names.
import pandas as pd
import seaborn as sb
from matplotlib import pyplot as plt
df = sb.load_dataset('tips')
g = sb.FacetGrid(df, col = "sex", hue = "smoker")
g.map(plt.scatter, "total_bill", "tip")
plt.show()
11 Lectures
4 hours
DATAhill Solutions Srinivas Reddy
11 Lectures
2.5 hours
DATAhill Solutions Srinivas Reddy
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2181,
"s": 2039,
"text": "A useful approach to explore medium-dimensional data, is by drawing multiple instances of the same plot on different subsets of your dataset."
},
{
"code": null,
"e": 2304,
"s": 2181,
"text": "This technique is commonly called as “lattice”, or “trellis” plotting, and it is related to the idea of “small multiples”."
},
{
"code": null,
"e": 2370,
"s": 2304,
"text": "To use these features, your data has to be in a Pandas DataFrame."
},
{
"code": null,
"e": 2622,
"s": 2370,
"text": "In the previous chapter, we have seen the FacetGrid example where FacetGrid class helps in visualizing distribution of one variable as well as the relationship between multiple variables separately within subsets of your dataset using multiple panels."
},
{
"code": null,
"e": 2897,
"s": 2622,
"text": "A FacetGrid can be drawn with up to three dimensions − row, col, and hue. The first two have obvious correspondence with the resulting array of axes; think of the hue variable as a third dimension along a depth axis, where different levels are plotted with different colors."
},
{
"code": null,
"e": 3035,
"s": 2897,
"text": "FacetGrid object takes a dataframe as input and the names of the variables that will form the row, column, or hue dimensions of the grid."
},
{
"code": null,
"e": 3156,
"s": 3035,
"text": "The variables should be categorical and the data at each level of the variable will be used for a facet along that axis."
},
{
"code": null,
"e": 3310,
"s": 3156,
"text": "import pandas as pd\nimport seaborn as sb\nfrom matplotlib import pyplot as plt\ndf = sb.load_dataset('tips')\ng = sb.FacetGrid(df, col = \"time\")\nplt.show()\n"
},
{
"code": null,
"e": 3415,
"s": 3310,
"text": "In the above example, we have just initialized the facetgrid object which doesn’t draw anything on them."
},
{
"code": null,
"e": 3588,
"s": 3415,
"text": "The main approach for visualizing data on this grid is with the FacetGrid.map() method. Let us look at the distribution of tips in each of these subsets, using a histogram."
},
{
"code": null,
"e": 3765,
"s": 3588,
"text": "import pandas as pd\nimport seaborn as sb\nfrom matplotlib import pyplot as plt\ndf = sb.load_dataset('tips')\ng = sb.FacetGrid(df, col = \"time\")\ng.map(plt.hist, \"tip\")\nplt.show()\n"
},
{
"code": null,
"e": 3891,
"s": 3765,
"text": "The number of plots is more than one because of the parameter col. We discussed about col parameter in our previous chapters."
},
{
"code": null,
"e": 3952,
"s": 3891,
"text": "To make a relational plot, pass the multiple variable names."
},
{
"code": null,
"e": 4161,
"s": 3952,
"text": "import pandas as pd\nimport seaborn as sb\nfrom matplotlib import pyplot as plt\ndf = sb.load_dataset('tips')\ng = sb.FacetGrid(df, col = \"sex\", hue = \"smoker\")\ng.map(plt.scatter, \"total_bill\", \"tip\")\nplt.show()\n"
},
{
"code": null,
"e": 4194,
"s": 4161,
"text": "\n 11 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4229,
"s": 4194,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 4264,
"s": 4229,
"text": "\n 11 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4299,
"s": 4264,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 4306,
"s": 4299,
"text": " Print"
},
{
"code": null,
"e": 4317,
"s": 4306,
"text": " Add Notes"
}
] |
Batch Script - Writing to Files
|
Content writing to files is also done with the help of the redirection filter >. This filter can be used to redirect any output to a file. Following is a simple example of how to create a file using the redirection command to write data to files.
@echo off
dir C:\>C:\new.txt
The above code snippet first uses the DIR command to get the directory listing of the entire C:\ . It then takes that output and with the help of the redirection command sends it to the file new.txt.
If you open up the file new.txt on your C drive, you will get the contents of your C drive in this file. Following is a sample output.
Volume in drive C is Windows8_OS
Volume Serial Number is E41C-6F43
Directory of C:\
12/22/2015 09:02 PM <DIR> 01 - Music
06/14/2015 10:31 AM <DIR> 02 - Videos
09/12/2015 06:23 AM <DIR> 03 - Pictures
12/17/2015 12:19 AM <DIR> 04 - Software
12/15/2015 11:06 PM <DIR> 05 - Studies
12/20/2014 09:09 AM <DIR> 06 - Future
12/20/2014 09:07 AM <DIR> 07 - Fitness
09/19/2015 09:56 AM <DIR> 08 - Tracking
10/19/2015 10:28 PM <DIR> 09 – Misc
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2416,
"s": 2169,
"text": "Content writing to files is also done with the help of the redirection filter >. This filter can be used to redirect any output to a file. Following is a simple example of how to create a file using the redirection command to write data to files."
},
{
"code": null,
"e": 2445,
"s": 2416,
"text": "@echo off\ndir C:\\>C:\\new.txt"
},
{
"code": null,
"e": 2645,
"s": 2445,
"text": "The above code snippet first uses the DIR command to get the directory listing of the entire C:\\ . It then takes that output and with the help of the redirection command sends it to the file new.txt."
},
{
"code": null,
"e": 2780,
"s": 2645,
"text": "If you open up the file new.txt on your C drive, you will get the contents of your C drive in this file. Following is a sample output."
},
{
"code": null,
"e": 3286,
"s": 2780,
"text": "Volume in drive C is Windows8_OS\nVolume Serial Number is E41C-6F43\n\nDirectory of C:\\\n\n12/22/2015 09:02 PM <DIR> 01 - Music\n06/14/2015 10:31 AM <DIR> 02 - Videos\n09/12/2015 06:23 AM <DIR> 03 - Pictures\n12/17/2015 12:19 AM <DIR> 04 - Software\n12/15/2015 11:06 PM <DIR> 05 - Studies\n12/20/2014 09:09 AM <DIR> 06 - Future\n12/20/2014 09:07 AM <DIR> 07 - Fitness\n09/19/2015 09:56 AM <DIR> 08 - Tracking\n10/19/2015 10:28 PM <DIR> 09 – Misc\n"
},
{
"code": null,
"e": 3293,
"s": 3286,
"text": " Print"
},
{
"code": null,
"e": 3304,
"s": 3293,
"text": " Add Notes"
}
] |
Get the list of all the public methods in Java
|
A list of all the public methods of a class or interface that is represented by an object are provided using the method java.lang.Class.getMethods(). The public methods include that are declared by the class or interface and also those that are inherited by the class or interface.
Also, the getMethods() method returns a zero length array if the class or interface has no public methods or if a primitive type, array class or void is represented in the Class object.
A program that demonstrates this is given as follows −
Live Demo
import java.lang.reflect.Method;
public class Main {
public static void main(String[] argv) throws Exception {
Class c = java.lang.Thread.class;
Method[] methods = c.getMethods();
System.out.println("The public methods of the java.lang.Thread class are:\n");
for (int i = 0; i < methods.length; i++) {
System.out.println(methods[i]);
}
}
}
The public methods of the java.lang.Thread class are:
public void java.lang.Thread.run()
public java.lang.String java.lang.Thread.toString()
public boolean java.lang.Thread.isInterrupted()
public static native java.lang.Thread java.lang.Thread.currentThread()
public final java.lang.String java.lang.Thread.getName()
public synchronized void java.lang.Thread.start()
public final synchronized void java.lang.Thread.join(long,int) throws java.lang.InterruptedException
public final synchronized void java.lang.Thread.join(long) throws java.lang.InterruptedException
public final void java.lang.Thread.join() throws java.lang.InterruptedException
public final java.lang.ThreadGroup java.lang.Thread.getThreadGroup()
public java.lang.StackTraceElement[] java.lang.Thread.getStackTrace()
public static native boolean java.lang.Thread.holdsLock(java.lang.Object)
public final void java.lang.Thread.checkAccess()
public static void java.lang.Thread.dumpStack()
public static native void java.lang.Thread.yield()
public final void java.lang.Thread.setPriority(int)
public final void java.lang.Thread.setDaemon(boolean)
public static native void java.lang.Thread.sleep(long) throws java.lang.InterruptedException
public static void java.lang.Thread.sleep(long,int) throws java.lang.InterruptedException
public final synchronized void java.lang.Thread.stop(java.lang.Throwable)
public final void java.lang.Thread.stop()
public void java.lang.Thread.interrupt()
public static boolean java.lang.Thread.interrupted()
public void java.lang.Thread.destroy()
public final native boolean java.lang.Thread.isAlive()
public final void java.lang.Thread.suspend()
public final void java.lang.Thread.resume()
public final int java.lang.Thread.getPriority()
public final synchronized void java.lang.Thread.setName(java.lang.String)
public static int java.lang.Thread.activeCount()
public static int java.lang.Thread.enumerate(java.lang.Thread[])
public native int java.lang.Thread.countStackFrames()
public final boolean java.lang.Thread.isDaemon()
public java.lang.ClassLoader java.lang.Thread.getContextClassLoader()
public void java.lang.Thread.setContextClassLoader(java.lang.ClassLoader)
public static java.util.Map java.lang.Thread.getAllStackTraces()
public long java.lang.Thread.getId()
public java.lang.Thread$State java.lang.Thread.getState()
public static void java.lang.Thread.setDefaultUncaughtExceptionHandler(java.lang.Thread$UncaughtExceptionHandler)
public static java.lang.Thread$UncaughtExceptionHandler java.lang.Thread.getDefaultUncaughtExceptionHandler()
public java.lang.Thread$UncaughtExceptionHandler java.lang.Thread.getUncaughtExceptionHandler()
public void java.lang.Thread.setUncaughtExceptionHandler(java.lang.Thread$UncaughtExceptionHandler)
public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
public final void java.lang.Object.wait() throws java.lang.InterruptedException
public boolean java.lang.Object.equals(java.lang.Object)
public native int java.lang.Object.hashCode()
public final native java.lang.Class java.lang.Object.getClass()
public final native void java.lang.Object.notify()
public final native void java.lang.Object.notifyAll()
|
[
{
"code": null,
"e": 1344,
"s": 1062,
"text": "A list of all the public methods of a class or interface that is represented by an object are provided using the method java.lang.Class.getMethods(). The public methods include that are declared by the class or interface and also those that are inherited by the class or interface."
},
{
"code": null,
"e": 1530,
"s": 1344,
"text": "Also, the getMethods() method returns a zero length array if the class or interface has no public methods or if a primitive type, array class or void is represented in the Class object."
},
{
"code": null,
"e": 1585,
"s": 1530,
"text": "A program that demonstrates this is given as follows −"
},
{
"code": null,
"e": 1596,
"s": 1585,
"text": " Live Demo"
},
{
"code": null,
"e": 1981,
"s": 1596,
"text": "import java.lang.reflect.Method;\npublic class Main {\n public static void main(String[] argv) throws Exception {\n Class c = java.lang.Thread.class;\n Method[] methods = c.getMethods();\n System.out.println(\"The public methods of the java.lang.Thread class are:\\n\");\n for (int i = 0; i < methods.length; i++) {\n System.out.println(methods[i]);\n }\n }\n}"
},
{
"code": null,
"e": 5264,
"s": 1981,
"text": "The public methods of the java.lang.Thread class are:\n\npublic void java.lang.Thread.run()\npublic java.lang.String java.lang.Thread.toString()\npublic boolean java.lang.Thread.isInterrupted()\npublic static native java.lang.Thread java.lang.Thread.currentThread()\npublic final java.lang.String java.lang.Thread.getName()\npublic synchronized void java.lang.Thread.start()\npublic final synchronized void java.lang.Thread.join(long,int) throws java.lang.InterruptedException\npublic final synchronized void java.lang.Thread.join(long) throws java.lang.InterruptedException\npublic final void java.lang.Thread.join() throws java.lang.InterruptedException\npublic final java.lang.ThreadGroup java.lang.Thread.getThreadGroup()\npublic java.lang.StackTraceElement[] java.lang.Thread.getStackTrace()\npublic static native boolean java.lang.Thread.holdsLock(java.lang.Object)\npublic final void java.lang.Thread.checkAccess()\npublic static void java.lang.Thread.dumpStack()\npublic static native void java.lang.Thread.yield()\npublic final void java.lang.Thread.setPriority(int)\npublic final void java.lang.Thread.setDaemon(boolean)\npublic static native void java.lang.Thread.sleep(long) throws java.lang.InterruptedException\npublic static void java.lang.Thread.sleep(long,int) throws java.lang.InterruptedException\npublic final synchronized void java.lang.Thread.stop(java.lang.Throwable)\npublic final void java.lang.Thread.stop()\npublic void java.lang.Thread.interrupt()\npublic static boolean java.lang.Thread.interrupted()\npublic void java.lang.Thread.destroy()\npublic final native boolean java.lang.Thread.isAlive()\npublic final void java.lang.Thread.suspend()\npublic final void java.lang.Thread.resume()\npublic final int java.lang.Thread.getPriority()\npublic final synchronized void java.lang.Thread.setName(java.lang.String)\npublic static int java.lang.Thread.activeCount()\npublic static int java.lang.Thread.enumerate(java.lang.Thread[])\npublic native int java.lang.Thread.countStackFrames()\npublic final boolean java.lang.Thread.isDaemon()\npublic java.lang.ClassLoader java.lang.Thread.getContextClassLoader()\npublic void java.lang.Thread.setContextClassLoader(java.lang.ClassLoader)\npublic static java.util.Map java.lang.Thread.getAllStackTraces()\npublic long java.lang.Thread.getId()\npublic java.lang.Thread$State java.lang.Thread.getState()\npublic static void java.lang.Thread.setDefaultUncaughtExceptionHandler(java.lang.Thread$UncaughtExceptionHandler)\npublic static java.lang.Thread$UncaughtExceptionHandler java.lang.Thread.getDefaultUncaughtExceptionHandler()\npublic java.lang.Thread$UncaughtExceptionHandler java.lang.Thread.getUncaughtExceptionHandler()\npublic void java.lang.Thread.setUncaughtExceptionHandler(java.lang.Thread$UncaughtExceptionHandler)\npublic final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException\npublic final native void java.lang.Object.wait(long) throws java.lang.InterruptedException\npublic final void java.lang.Object.wait() throws java.lang.InterruptedException\npublic boolean java.lang.Object.equals(java.lang.Object)\npublic native int java.lang.Object.hashCode()\npublic final native java.lang.Class java.lang.Object.getClass()\npublic final native void java.lang.Object.notify()\npublic final native void java.lang.Object.notifyAll()"
}
] |
Merge k sorted arrays in Java
|
We are given an ‘n’ number of arrays, let's say we take three arrays i.e. arr1[], arr2[] and arr3[] of integer type. The task is to merge all the given integer arrays in such a manner that the resultant array is sorted in the runtime only.
Input −
Int
a[]={21,22,23,24};
int b[ ] ={28,31,35}
Output −int resultant[ ]={21,22,23,24,28,31,35}.
Explanation − The array elements are compared before they are added and added according to their suitable position in the resultant array.
Input −
int
a[]={1,3,5,7,9,11,13};
int b[ ] ={14,16,18}
int c[ ] ={19,20,21,22}
Output − int resultant[ ]={1,3,5,7,9,11,13,14,16,18,19,20,21,22}.
Explanation −The array elements are compared before they are added and added according to their suitable position in the resultant array.
Input three integer arrays let’s say, arr1[], arr2[] and arr3[] and a resultant array as result[] and set it to the call to a method as mergeSortedArray(new int[][] { arr1, arr2, arr3 })
Input three integer arrays let’s say, arr1[], arr2[] and arr3[] and a resultant array as result[] and set it to the call to a method as mergeSortedArray(new int[][] { arr1, arr2, arr3 })
Inside the method mergeSortedArray(new int[][] { arr1, arr2, arr3 })Create a variable as a queue of type priority queue and a variable as
total and set it to 0.Start loop FOR from i to 0 till length of an array and add element
from bucket of an array to the variable declared as queue and set
total to total + arr[i].length.Set m to 0 and declare result[] integer array.Start while queue.isEmpty() = false then set ArrayBucket ac to
queue.poll(), result[m++] to ac.arr[ac.index] and check IF ac.index
less than ac.arr.length - 1 then set queue.add(new
ArrayBucket(ac.arr, ac.index + 1))Return result
Inside the method mergeSortedArray(new int[][] { arr1, arr2, arr3 })
Create a variable as a queue of type priority queue and a variable as
total and set it to 0.
Create a variable as a queue of type priority queue and a variable as
total and set it to 0.
Start loop FOR from i to 0 till length of an array and add element
from bucket of an array to the variable declared as queue and set
total to total + arr[i].length.
Start loop FOR from i to 0 till length of an array and add element
from bucket of an array to the variable declared as queue and set
total to total + arr[i].length.
Set m to 0 and declare result[] integer array.
Set m to 0 and declare result[] integer array.
Start while queue.isEmpty() = false then set ArrayBucket ac to
queue.poll(), result[m++] to ac.arr[ac.index] and check IF ac.index
less than ac.arr.length - 1 then set queue.add(new
ArrayBucket(ac.arr, ac.index + 1))
Start while queue.isEmpty() = false then set ArrayBucket ac to
queue.poll(), result[m++] to ac.arr[ac.index] and check IF ac.index
less than ac.arr.length - 1 then set queue.add(new
ArrayBucket(ac.arr, ac.index + 1))
Return result
Return result
import java.util.Arrays;
import java.util.PriorityQueue;
class ArrayBucket implements Comparable<ArrayBucket>{
int[] arr;
int index;
public ArrayBucket(int[] arr, int index){
this.arr = arr;
this.index = index;
}
@Override
public int compareTo(ArrayBucket o){
return this.arr[this.index] - o.arr[o.index];
}
}
public class testClass{
public static int[] mergeSortedArray(int[][] arr){
PriorityQueue<ArrayBucket> queue = new
PriorityQueue<ArrayBucket>();
int total = 0;
for (int i = 0; i < arr.length; i++){
queue.add(new ArrayBucket(arr[i], 0));
total = total + arr[i].length;
}
int m = 0;
int result[] = new int[total];
while (!queue.isEmpty()){
ArrayBucket ac = queue.poll();
result[m++] = ac.arr[ac.index];
if (ac.index < ac.arr.length - 1){
queue.add(new ArrayBucket(ac.arr, ac.index + 1));
}
}
return result;
}
public static void main(String[] args){
int[] arr1 = { 1, 3, 5, 7 };
int[] arr2 = { 2, 4, 6, 8 };
int[] arr3 = { 0, 9, 10, 11 };
int[] result = mergeSortedArray(new int[][] { arr1, arr2, arr3 });
System.out.println("The final merged sorted array is :- "+Arrays.toString(result));
}
}
If we run the above code it will generate the following Output
The final merged sorted array is :-[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
|
[
{
"code": null,
"e": 1302,
"s": 1062,
"text": "We are given an ‘n’ number of arrays, let's say we take three arrays i.e. arr1[], arr2[] and arr3[] of integer type. The task is to merge all the given integer arrays in such a manner that the resultant array is sorted in the runtime only."
},
{
"code": null,
"e": 1310,
"s": 1302,
"text": "Input −"
},
{
"code": null,
"e": 1314,
"s": 1310,
"text": "Int"
},
{
"code": null,
"e": 1333,
"s": 1314,
"text": "a[]={21,22,23,24};"
},
{
"code": null,
"e": 1354,
"s": 1333,
"text": "int b[ ] ={28,31,35}"
},
{
"code": null,
"e": 1403,
"s": 1354,
"text": "Output −int resultant[ ]={21,22,23,24,28,31,35}."
},
{
"code": null,
"e": 1542,
"s": 1403,
"text": "Explanation − The array elements are compared before they are added and added according to their suitable position in the resultant array."
},
{
"code": null,
"e": 1550,
"s": 1542,
"text": "Input −"
},
{
"code": null,
"e": 1554,
"s": 1550,
"text": "int"
},
{
"code": null,
"e": 1577,
"s": 1554,
"text": "a[]={1,3,5,7,9,11,13};"
},
{
"code": null,
"e": 1598,
"s": 1577,
"text": "int b[ ] ={14,16,18}"
},
{
"code": null,
"e": 1622,
"s": 1598,
"text": "int c[ ] ={19,20,21,22}"
},
{
"code": null,
"e": 1688,
"s": 1622,
"text": "Output − int resultant[ ]={1,3,5,7,9,11,13,14,16,18,19,20,21,22}."
},
{
"code": null,
"e": 1826,
"s": 1688,
"text": "Explanation −The array elements are compared before they are added and added according to their suitable position in the resultant array."
},
{
"code": null,
"e": 2013,
"s": 1826,
"text": "Input three integer arrays let’s say, arr1[], arr2[] and arr3[] and a resultant array as result[] and set it to the call to a method as mergeSortedArray(new int[][] { arr1, arr2, arr3 })"
},
{
"code": null,
"e": 2200,
"s": 2013,
"text": "Input three integer arrays let’s say, arr1[], arr2[] and arr3[] and a resultant array as result[] and set it to the call to a method as mergeSortedArray(new int[][] { arr1, arr2, arr3 })"
},
{
"code": null,
"e": 2800,
"s": 2200,
"text": "Inside the method mergeSortedArray(new int[][] { arr1, arr2, arr3 })Create a variable as a queue of type priority queue and a variable as\ntotal and set it to 0.Start loop FOR from i to 0 till length of an array and add element\nfrom bucket of an array to the variable declared as queue and set\ntotal to total + arr[i].length.Set m to 0 and declare result[] integer array.Start while queue.isEmpty() = false then set ArrayBucket ac to\nqueue.poll(), result[m++] to ac.arr[ac.index] and check IF ac.index\nless than ac.arr.length - 1 then set queue.add(new\nArrayBucket(ac.arr, ac.index + 1))Return result"
},
{
"code": null,
"e": 2869,
"s": 2800,
"text": "Inside the method mergeSortedArray(new int[][] { arr1, arr2, arr3 })"
},
{
"code": null,
"e": 2962,
"s": 2869,
"text": "Create a variable as a queue of type priority queue and a variable as\ntotal and set it to 0."
},
{
"code": null,
"e": 3055,
"s": 2962,
"text": "Create a variable as a queue of type priority queue and a variable as\ntotal and set it to 0."
},
{
"code": null,
"e": 3220,
"s": 3055,
"text": "Start loop FOR from i to 0 till length of an array and add element\nfrom bucket of an array to the variable declared as queue and set\ntotal to total + arr[i].length."
},
{
"code": null,
"e": 3385,
"s": 3220,
"text": "Start loop FOR from i to 0 till length of an array and add element\nfrom bucket of an array to the variable declared as queue and set\ntotal to total + arr[i].length."
},
{
"code": null,
"e": 3432,
"s": 3385,
"text": "Set m to 0 and declare result[] integer array."
},
{
"code": null,
"e": 3479,
"s": 3432,
"text": "Set m to 0 and declare result[] integer array."
},
{
"code": null,
"e": 3696,
"s": 3479,
"text": "Start while queue.isEmpty() = false then set ArrayBucket ac to\nqueue.poll(), result[m++] to ac.arr[ac.index] and check IF ac.index\nless than ac.arr.length - 1 then set queue.add(new\nArrayBucket(ac.arr, ac.index + 1))"
},
{
"code": null,
"e": 3913,
"s": 3696,
"text": "Start while queue.isEmpty() = false then set ArrayBucket ac to\nqueue.poll(), result[m++] to ac.arr[ac.index] and check IF ac.index\nless than ac.arr.length - 1 then set queue.add(new\nArrayBucket(ac.arr, ac.index + 1))"
},
{
"code": null,
"e": 3927,
"s": 3913,
"text": "Return result"
},
{
"code": null,
"e": 3941,
"s": 3927,
"text": "Return result"
},
{
"code": null,
"e": 5248,
"s": 3941,
"text": "import java.util.Arrays;\nimport java.util.PriorityQueue;\nclass ArrayBucket implements Comparable<ArrayBucket>{\n int[] arr;\n int index;\n public ArrayBucket(int[] arr, int index){\n this.arr = arr;\n this.index = index;\n }\n @Override\n public int compareTo(ArrayBucket o){\n return this.arr[this.index] - o.arr[o.index];\n }\n}\npublic class testClass{\n public static int[] mergeSortedArray(int[][] arr){\n PriorityQueue<ArrayBucket> queue = new\n PriorityQueue<ArrayBucket>();\n int total = 0;\n for (int i = 0; i < arr.length; i++){\n queue.add(new ArrayBucket(arr[i], 0));\n total = total + arr[i].length;\n }\n int m = 0;\n int result[] = new int[total];\n while (!queue.isEmpty()){\n ArrayBucket ac = queue.poll();\n result[m++] = ac.arr[ac.index];\n if (ac.index < ac.arr.length - 1){\n queue.add(new ArrayBucket(ac.arr, ac.index + 1));\n }\n }\n return result;\n }\n public static void main(String[] args){\n int[] arr1 = { 1, 3, 5, 7 };\n int[] arr2 = { 2, 4, 6, 8 };\n int[] arr3 = { 0, 9, 10, 11 };\n int[] result = mergeSortedArray(new int[][] { arr1, arr2, arr3 });\n System.out.println(\"The final merged sorted array is :- \"+Arrays.toString(result));\n }\n}"
},
{
"code": null,
"e": 5311,
"s": 5248,
"text": "If we run the above code it will generate the following Output"
},
{
"code": null,
"e": 5385,
"s": 5311,
"text": "The final merged sorted array is :-[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]"
}
] |
Angular 6 - Services
|
In this chapter, we will discuss the services in Angular 6.
We might come across a situation where we need some code to be used everywhere on the page. It can be for data connection that needs to be shared across components, etc. Services help us achieve that. With services, we can access methods and properties across other components in the entire project.
To create a service, we need to make use of the command line. The command for the same is −
C:\projectA6\Angular6App>ng g service myservice
CREATE src/app/myservice.service.spec.ts (392 bytes)
CREATE src/app/myservice.service.ts (138 bytes)
The files are created in the app folder as follows −
Following are the files created at the bottom - myservice.service.specs.ts and myservice.service.ts.
import { Injectable } from '@angular/core';
@Injectable()
export class MyserviceService {
constructor() { }
}
Here, the Injectable module is imported from the @angular/core. It contains the @Injectable method and a class called MyserviceService. We will create our service function in this class.
Before creating a new service, we need to include the service created in the main parent app.module.ts.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule} from '@angular/router';
import { AppComponent } from './app.component';
import { MyserviceService } from './myservice.service';
import { NewCmpComponent } from './new-cmp/new-cmp.component';
import { ChangeTextDirective } from './change-text.directive';
import { SqrtPipe } from './app.sqrt';
@NgModule({
declarations: [
SqrtPipe,
AppComponent,
NewCmpComponent,
ChangeTextDirective
],
imports: [
BrowserModule,
RouterModule.forRoot([
{
path: 'new-cmp',
component: NewCmpComponent
}
])
],
providers: [MyserviceService],
bootstrap: [AppComponent]
})
export class AppModule { }
We have imported the Service with the class name and the same class is used in the providers. Let us now switch back to the service class and create a service function.
In the service class, we will create a function which will display today�s date. We can use the same function in the main parent component app.component.ts and also in the new component new-cmp.component.ts that we created in the previous chapter.
Let us now see how the function looks in the service and how to use it in components.
import { Injectable } from '@angular/core';
@Injectable()
export class MyserviceService {
constructor() { }
showTodayDate() {
let ndate = new Date();
return ndate;
}
}
In the above service file, we have created a function showTodayDate. Now we will return the new Date () created. Let us see how we can access this function in the component class.
import { Component } from '@angular/core';
import { MyserviceService } from './myservice.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 6 Project!';
todaydate;
constructor(private myservice: MyserviceService) {}
ngOnInit() {
this.todaydate = this.myservice.showTodayDate();
}
}
The ngOnInit function gets called by default in any component created. The date is fetched from the service as shown above. To fetch more details of the service, we need to first include the service in the component ts file.
We will display the date in the .html file as shown below −
{{todaydate}}
<app-new-cmp></app-new-cmp>
// data to be displayed to user from the new component class.
Let us now see how to use the service in the new component created.
import { Component, OnInit } from '@angular/core';
import { MyserviceService } from './../myservice.service';
@Component({
selector: 'app-new-cmp',
templateUrl: './new-cmp.component.html',
styleUrls: ['./new-cmp.component.css']
})
export class NewCmpComponent implements OnInit {
todaydate;
newcomponent = "Entered in new component created";
constructor(private myservice: MyserviceService) {}
ngOnInit() {
this.todaydate = this.myservice.showTodayDate();
}
}
In the new component that we have created, we need to first import the service that we want and access the methods and properties of the same. Please see the code highlighted. The todaydate is displayed in the component html as follows −
<p>
{{newcomponent}}
</p>
<p>
Today's Date : {{todaydate}}
</p>
The selector of the new component is used in the app.component.html file. The contents from the above html file will be displayed in the browser as shown below −
If you change the property of the service in any component, the same is changed in other components too. Let us now see how this works.
We will define one variable in the service and use it in the parent and the new component. We will again change the property in the parent component and will see if the same is changed in the new component or not.
In myservice.service.ts, we have created a property and used the same in other parent and new component.
import { Injectable } from '@angular/core';
@Injectable()
export class MyserviceService {
serviceproperty = "Service Created";
constructor() { }
showTodayDate() {
let ndate = new Date();
return ndate;
}
}
Let us now use the serviceproperty variable in other components. In app.component.ts, we are accessing the variable as follows −
import { Component } from '@angular/core';
import { MyserviceService } from './myservice.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 4 Project!';
todaydate;
componentproperty;
constructor(private myservice: MyserviceService) {}
ngOnInit() {
this.todaydate = this.myservice.showTodayDate();
console.log(this.myservice.serviceproperty);
this.myservice.serviceproperty = "component created"; // value is changed.
this.componentproperty = this.myservice.serviceproperty;
}
}
We will now fetch the variable and work on the console.log. In the next line, we will change the value of the variable to "component created". We will do the same in new-cmp.component.ts.
import { Component, OnInit } from '@angular/core';
import { MyserviceService } from './../myservice.service';
@Component({
selector: 'app-new-cmp',
templateUrl: './new-cmp.component.html',
styleUrls: ['./new-cmp.component.css']
})
export class NewCmpComponent implements OnInit {
todaydate;
newcomponentproperty;
newcomponent = "Entered in newcomponent";
constructor(private myservice: MyserviceService) {}
ngOnInit() {
this.todaydate = this.myservice.showTodayDate();
this.newcomponentproperty = this.myservice.serviceproperty;
}
}
In the above component, we are not changing anything but directly assigning the property to the component property.
Now when you execute it in the browser, the service property will be changed since the value of it is changed in app.component.ts and the same will be displayed for the new-cmp.component.ts.
Also check the value in the console before it is changed.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2055,
"s": 1995,
"text": "In this chapter, we will discuss the services in Angular 6."
},
{
"code": null,
"e": 2355,
"s": 2055,
"text": "We might come across a situation where we need some code to be used everywhere on the page. It can be for data connection that needs to be shared across components, etc. Services help us achieve that. With services, we can access methods and properties across other components in the entire project."
},
{
"code": null,
"e": 2447,
"s": 2355,
"text": "To create a service, we need to make use of the command line. The command for the same is −"
},
{
"code": null,
"e": 2597,
"s": 2447,
"text": "C:\\projectA6\\Angular6App>ng g service myservice\nCREATE src/app/myservice.service.spec.ts (392 bytes)\nCREATE src/app/myservice.service.ts (138 bytes)\n"
},
{
"code": null,
"e": 2650,
"s": 2597,
"text": "The files are created in the app folder as follows −"
},
{
"code": null,
"e": 2751,
"s": 2650,
"text": "Following are the files created at the bottom - myservice.service.specs.ts and myservice.service.ts."
},
{
"code": null,
"e": 2864,
"s": 2751,
"text": "import { Injectable } from '@angular/core';\n@Injectable()\nexport class MyserviceService {\n constructor() { }\n}"
},
{
"code": null,
"e": 3051,
"s": 2864,
"text": "Here, the Injectable module is imported from the @angular/core. It contains the @Injectable method and a class called MyserviceService. We will create our service function in this class."
},
{
"code": null,
"e": 3155,
"s": 3051,
"text": "Before creating a new service, we need to include the service created in the main parent app.module.ts."
},
{
"code": null,
"e": 3956,
"s": 3155,
"text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { RouterModule} from '@angular/router';\nimport { AppComponent } from './app.component';\nimport { MyserviceService } from './myservice.service';\nimport { NewCmpComponent } from './new-cmp/new-cmp.component';\nimport { ChangeTextDirective } from './change-text.directive';\nimport { SqrtPipe } from './app.sqrt';\n@NgModule({\n declarations: [\n SqrtPipe,\n AppComponent,\n NewCmpComponent,\n ChangeTextDirective\n ],\n imports: [\n BrowserModule,\n RouterModule.forRoot([\n {\n path: 'new-cmp',\n component: NewCmpComponent\n }\n ])\n ],\n providers: [MyserviceService],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }"
},
{
"code": null,
"e": 4125,
"s": 3956,
"text": "We have imported the Service with the class name and the same class is used in the providers. Let us now switch back to the service class and create a service function."
},
{
"code": null,
"e": 4373,
"s": 4125,
"text": "In the service class, we will create a function which will display today�s date. We can use the same function in the main parent component app.component.ts and also in the new component new-cmp.component.ts that we created in the previous chapter."
},
{
"code": null,
"e": 4459,
"s": 4373,
"text": "Let us now see how the function looks in the service and how to use it in components."
},
{
"code": null,
"e": 4648,
"s": 4459,
"text": "import { Injectable } from '@angular/core';\n@Injectable()\nexport class MyserviceService {\n constructor() { }\n showTodayDate() {\n let ndate = new Date();\n return ndate;\n }\n}"
},
{
"code": null,
"e": 4828,
"s": 4648,
"text": "In the above service file, we have created a function showTodayDate. Now we will return the new Date () created. Let us see how we can access this function in the component class."
},
{
"code": null,
"e": 5254,
"s": 4828,
"text": "import { Component } from '@angular/core';\nimport { MyserviceService } from './myservice.service';\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n title = 'Angular 6 Project!';\n todaydate;\n constructor(private myservice: MyserviceService) {}\n ngOnInit() {\n this.todaydate = this.myservice.showTodayDate();\n }\n}"
},
{
"code": null,
"e": 5479,
"s": 5254,
"text": "The ngOnInit function gets called by default in any component created. The date is fetched from the service as shown above. To fetch more details of the service, we need to first include the service in the component ts file."
},
{
"code": null,
"e": 5539,
"s": 5479,
"text": "We will display the date in the .html file as shown below −"
},
{
"code": null,
"e": 5645,
"s": 5539,
"text": "{{todaydate}}\n<app-new-cmp></app-new-cmp> \n// data to be displayed to user from the new component class.\n"
},
{
"code": null,
"e": 5713,
"s": 5645,
"text": "Let us now see how to use the service in the new component created."
},
{
"code": null,
"e": 6203,
"s": 5713,
"text": "import { Component, OnInit } from '@angular/core';\nimport { MyserviceService } from './../myservice.service';\n@Component({\n selector: 'app-new-cmp',\n templateUrl: './new-cmp.component.html',\n styleUrls: ['./new-cmp.component.css']\n})\nexport class NewCmpComponent implements OnInit {\n todaydate;\n newcomponent = \"Entered in new component created\";\n constructor(private myservice: MyserviceService) {}\n ngOnInit() {\n this.todaydate = this.myservice.showTodayDate();\n }\n}"
},
{
"code": null,
"e": 6441,
"s": 6203,
"text": "In the new component that we have created, we need to first import the service that we want and access the methods and properties of the same. Please see the code highlighted. The todaydate is displayed in the component html as follows −"
},
{
"code": null,
"e": 6512,
"s": 6441,
"text": "<p>\n {{newcomponent}}\n</p>\n<p>\n Today's Date : {{todaydate}}\n</p>\n"
},
{
"code": null,
"e": 6674,
"s": 6512,
"text": "The selector of the new component is used in the app.component.html file. The contents from the above html file will be displayed in the browser as shown below −"
},
{
"code": null,
"e": 6810,
"s": 6674,
"text": "If you change the property of the service in any component, the same is changed in other components too. Let us now see how this works."
},
{
"code": null,
"e": 7024,
"s": 6810,
"text": "We will define one variable in the service and use it in the parent and the new component. We will again change the property in the parent component and will see if the same is changed in the new component or not."
},
{
"code": null,
"e": 7129,
"s": 7024,
"text": "In myservice.service.ts, we have created a property and used the same in other parent and new component."
},
{
"code": null,
"e": 7358,
"s": 7129,
"text": "import { Injectable } from '@angular/core';\n@Injectable()\nexport class MyserviceService {\n serviceproperty = \"Service Created\";\n constructor() { }\n showTodayDate() {\n let ndate = new Date();\n return ndate;\n }\n}"
},
{
"code": null,
"e": 7487,
"s": 7358,
"text": "Let us now use the serviceproperty variable in other components. In app.component.ts, we are accessing the variable as follows −"
},
{
"code": null,
"e": 8130,
"s": 7487,
"text": "import { Component } from '@angular/core';\nimport { MyserviceService } from './myservice.service';\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n title = 'Angular 4 Project!';\n todaydate;\n componentproperty;\n constructor(private myservice: MyserviceService) {}\n ngOnInit() {\n this.todaydate = this.myservice.showTodayDate();\n console.log(this.myservice.serviceproperty);\n this.myservice.serviceproperty = \"component created\"; // value is changed.\n this.componentproperty = this.myservice.serviceproperty;\n }\n}"
},
{
"code": null,
"e": 8318,
"s": 8130,
"text": "We will now fetch the variable and work on the console.log. In the next line, we will change the value of the variable to \"component created\". We will do the same in new-cmp.component.ts."
},
{
"code": null,
"e": 8890,
"s": 8318,
"text": "import { Component, OnInit } from '@angular/core';\nimport { MyserviceService } from './../myservice.service';\n@Component({\n selector: 'app-new-cmp',\n templateUrl: './new-cmp.component.html',\n styleUrls: ['./new-cmp.component.css']\n})\nexport class NewCmpComponent implements OnInit {\n todaydate;\n newcomponentproperty;\n newcomponent = \"Entered in newcomponent\";\n constructor(private myservice: MyserviceService) {}\n ngOnInit() {\n this.todaydate = this.myservice.showTodayDate();\n this.newcomponentproperty = this.myservice.serviceproperty;\n }\n}"
},
{
"code": null,
"e": 9006,
"s": 8890,
"text": "In the above component, we are not changing anything but directly assigning the property to the component property."
},
{
"code": null,
"e": 9197,
"s": 9006,
"text": "Now when you execute it in the browser, the service property will be changed since the value of it is changed in app.component.ts and the same will be displayed for the new-cmp.component.ts."
},
{
"code": null,
"e": 9255,
"s": 9197,
"text": "Also check the value in the console before it is changed."
},
{
"code": null,
"e": 9290,
"s": 9255,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 9304,
"s": 9290,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 9339,
"s": 9304,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 9353,
"s": 9339,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 9388,
"s": 9353,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 9408,
"s": 9388,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 9443,
"s": 9408,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 9460,
"s": 9443,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 9493,
"s": 9460,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 9505,
"s": 9493,
"text": " Senol Atac"
},
{
"code": null,
"e": 9540,
"s": 9505,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 9552,
"s": 9540,
"text": " Senol Atac"
},
{
"code": null,
"e": 9559,
"s": 9552,
"text": " Print"
},
{
"code": null,
"e": 9570,
"s": 9559,
"text": " Add Notes"
}
] |
How to read text file into a list or array with Python?
|
f = open('my_file.txt', 'r+')
my_file_data = f.read()
f.close()
The above code opens 'my_file.txt' in read mode then stores the data it reads from my_file.txt in my_file_data and closes the file. The read function reads the whole file at once. You can use the following to read the file line by line and store it in a list:
f = open('my_file', 'r+')
lines = [line for line inf.readlines()]
f.close()
|
[
{
"code": null,
"e": 1126,
"s": 1062,
"text": "f = open('my_file.txt', 'r+')\nmy_file_data = f.read()\nf.close()"
},
{
"code": null,
"e": 1386,
"s": 1126,
"text": "The above code opens 'my_file.txt' in read mode then stores the data it reads from my_file.txt in my_file_data and closes the file. The read function reads the whole file at once. You can use the following to read the file line by line and store it in a list:"
},
{
"code": null,
"e": 1462,
"s": 1386,
"text": "f = open('my_file', 'r+')\nlines = [line for line inf.readlines()]\nf.close()"
}
] |
FileOutputStream in Java.
|
This writes data into a specific file or, a file descriptor (byte by byte). It is usually used to write the contents of a file with raw bytes, such as images.
To write the contents of a file using this class −
First of all, you need to instantiate this class by passing a string variable or a File object, representing the path of the file to be read.
First of all, you need to instantiate this class by passing a string variable or a File object, representing the path of the file to be read.
FileOutputStream outputStream = new FileOutputStream("file_path");
or,
File file = new File("file_path"); FileOutputStream outputStream = new FileOutputStream (file);
You can also instantiate a FileOutputStream class by passing a FileDescriptor object.
FileDescriptor descriptor = new FileDescriptor(); FileOutputStream outputStream = new FileOutputStream(descriptor);
Then write the data to a specified file using either of the variants of write() method −int write(int b) − This method accepts a single byte and writes it to the current OutputStream.int write(byte[] b) − This method accepts a byte array as a parameter and writes data from it to the current OutputStream.int write(byte[] b, int off, int len) − This method accepts a byte array, its offset (int) and, its length (int) as parameters and writes its contents to the current OutputStream.
Then write the data to a specified file using either of the variants of write() method −
int write(int b) − This method accepts a single byte and writes it to the current OutputStream.
int write(int b) − This method accepts a single byte and writes it to the current OutputStream.
int write(byte[] b) − This method accepts a byte array as a parameter and writes data from it to the current OutputStream.
int write(byte[] b) − This method accepts a byte array as a parameter and writes data from it to the current OutputStream.
int write(byte[] b, int off, int len) − This method accepts a byte array, its offset (int) and, its length (int) as parameters and writes its contents to the current OutputStream.
int write(byte[] b, int off, int len) − This method accepts a byte array, its offset (int) and, its length (int) as parameters and writes its contents to the current OutputStream.
Assume we have the following image in the directory D:/images
Following program reads the contents of the above image and writes it back to another file using the FileOutputStream class.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileInputStreamExample {
public static void main(String args[]) throws IOException {
//Creating a File object
File file = new File("D:/images/javafx.jpg");
//Creating a FileInputStream object
FileInputStream inputStream = new FileInputStream(file);
//Creating a byte array
byte bytes[] = new byte[(int) file.length()];
//Reading data into the byte array
int numOfBytes = inputStream.read(bytes);
System.out.println("Data copied successfully...");
//Creating a FileInputStream object
FileOutputStream outputStream = new FileOutputStream("D:/images/output.jpg");
//Writing the contents of the Output Stream to a file
outputStream.write(bytes);
System.out.println("Data written successfully...");
}
}
Data copied successfully...
Data written successfully...
If you verify the given path you can observe the generated image as −
|
[
{
"code": null,
"e": 1221,
"s": 1062,
"text": "This writes data into a specific file or, a file descriptor (byte by byte). It is usually used to write the contents of a file with raw bytes, such as images."
},
{
"code": null,
"e": 1272,
"s": 1221,
"text": "To write the contents of a file using this class −"
},
{
"code": null,
"e": 1414,
"s": 1272,
"text": "First of all, you need to instantiate this class by passing a string variable or a File object, representing the path of the file to be read."
},
{
"code": null,
"e": 1556,
"s": 1414,
"text": "First of all, you need to instantiate this class by passing a string variable or a File object, representing the path of the file to be read."
},
{
"code": null,
"e": 1723,
"s": 1556,
"text": "FileOutputStream outputStream = new FileOutputStream(\"file_path\");\nor,\nFile file = new File(\"file_path\"); FileOutputStream outputStream = new FileOutputStream (file);"
},
{
"code": null,
"e": 1809,
"s": 1723,
"text": "You can also instantiate a FileOutputStream class by passing a FileDescriptor object."
},
{
"code": null,
"e": 1925,
"s": 1809,
"text": "FileDescriptor descriptor = new FileDescriptor(); FileOutputStream outputStream = new FileOutputStream(descriptor);"
},
{
"code": null,
"e": 2410,
"s": 1925,
"text": "Then write the data to a specified file using either of the variants of write() method −int write(int b) − This method accepts a single byte and writes it to the current OutputStream.int write(byte[] b) − This method accepts a byte array as a parameter and writes data from it to the current OutputStream.int write(byte[] b, int off, int len) − This method accepts a byte array, its offset (int) and, its length (int) as parameters and writes its contents to the current OutputStream."
},
{
"code": null,
"e": 2499,
"s": 2410,
"text": "Then write the data to a specified file using either of the variants of write() method −"
},
{
"code": null,
"e": 2595,
"s": 2499,
"text": "int write(int b) − This method accepts a single byte and writes it to the current OutputStream."
},
{
"code": null,
"e": 2691,
"s": 2595,
"text": "int write(int b) − This method accepts a single byte and writes it to the current OutputStream."
},
{
"code": null,
"e": 2814,
"s": 2691,
"text": "int write(byte[] b) − This method accepts a byte array as a parameter and writes data from it to the current OutputStream."
},
{
"code": null,
"e": 2937,
"s": 2814,
"text": "int write(byte[] b) − This method accepts a byte array as a parameter and writes data from it to the current OutputStream."
},
{
"code": null,
"e": 3117,
"s": 2937,
"text": "int write(byte[] b, int off, int len) − This method accepts a byte array, its offset (int) and, its length (int) as parameters and writes its contents to the current OutputStream."
},
{
"code": null,
"e": 3297,
"s": 3117,
"text": "int write(byte[] b, int off, int len) − This method accepts a byte array, its offset (int) and, its length (int) as parameters and writes its contents to the current OutputStream."
},
{
"code": null,
"e": 3359,
"s": 3297,
"text": "Assume we have the following image in the directory D:/images"
},
{
"code": null,
"e": 3484,
"s": 3359,
"text": "Following program reads the contents of the above image and writes it back to another file using the FileOutputStream class."
},
{
"code": null,
"e": 4399,
"s": 3484,
"text": "import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\npublic class FileInputStreamExample {\n public static void main(String args[]) throws IOException {\n //Creating a File object\n File file = new File(\"D:/images/javafx.jpg\");\n //Creating a FileInputStream object\n FileInputStream inputStream = new FileInputStream(file);\n //Creating a byte array\n byte bytes[] = new byte[(int) file.length()];\n //Reading data into the byte array\n int numOfBytes = inputStream.read(bytes);\n System.out.println(\"Data copied successfully...\");\n //Creating a FileInputStream object\n FileOutputStream outputStream = new FileOutputStream(\"D:/images/output.jpg\");\n //Writing the contents of the Output Stream to a file\n outputStream.write(bytes);\n System.out.println(\"Data written successfully...\");\n }\n}"
},
{
"code": null,
"e": 4456,
"s": 4399,
"text": "Data copied successfully...\nData written successfully..."
},
{
"code": null,
"e": 4526,
"s": 4456,
"text": "If you verify the given path you can observe the generated image as −"
}
] |
How To Train Your Chatbot With Simple Transformers | by Thilina Rajapakse | Towards Data Science
|
Chatbots and virtual assistants, once found mostly in Sci-Fi, are becoming increasingly more common. Google Assistant’s and Siri’s of today still has a long, long way to go to reach Iron Man’s J.A.R.V.I.S. and the like, but the journey has begun. While the current crop of Conversational AI is far from perfect, they are also a far cry from their humble beginnings as simple programs like ELIZA.
Moving away from the typical rule-based chatbots, Hugging Face came up with a Transformer based way to build chatbots that lets us leverage the state-of-the-art language modelling capabilities of models like BERT and OpenAI GPT. Using this method, we can quickly build powerful and impressive Conversational AI’s that can outperform most rule-based chatbots. It also eliminates the need for tedious rule building and script writing necessary for building a good rule-based chatbot.
Simple Transformers offers a way to build these Conversational AI models quickly, efficiently, and easily. The Simple Transformers implementation is built on the Hugging Face implementation given here.
Getting the environment set up is fairly straightforward.
Install Anaconda or Miniconda Package Manager from hereCreate a new virtual environment and install packages.conda create -n transformers pythonconda activate transformersIf using Cuda:conda install pytorch cudatoolkit=10.1 -c pytorchelse:conda install pytorch cpuonly -c pytorchInstall Apex if you are using fp16 training. Please follow the instructions here. (Installing Apex from pip has caused issues for several people.)Install simpletransformers.pip install simpletransformers
Install Anaconda or Miniconda Package Manager from here
Create a new virtual environment and install packages.conda create -n transformers pythonconda activate transformersIf using Cuda:conda install pytorch cudatoolkit=10.1 -c pytorchelse:conda install pytorch cpuonly -c pytorch
Install Apex if you are using fp16 training. Please follow the instructions here. (Installing Apex from pip has caused issues for several people.)
Install simpletransformers.pip install simpletransformers
We’ll be using the Persona-Chat dataset. Note that you don’t need to manually download the dataset as the formatted JSON version of the dataset (provided by Hugging Face) will be automatically downloaded by Simple Transformers if no dataset is specified when training the model.
ConvAIModel is the class used in Simple Transformers to do all thing related to conversational AI models. This includes training, evaluating, and interacting with the models.
At the moment, you can use any of the OpenAI GPT or GPT-2 models with ConvAIModel. However, the pre-trained model provided by Hugging Face performs well out-of-the-box and will likely require less fine-tuning when creating your own chatbot. You can download the model from the here and extract the archive to follow along with the tutorial (which assumes you have downloaded the model and extracted it to gpt_personachat_cache).
The code snippet above creates a ConvAIModel and loads the Transformer with the pre-trained weights.
The ConvAIModel comes with a wide range of configuration options, which can be found in the documentation here. You can also find the list of globally available configuration options in the Simple Transformers library here.
You can further fine-tune the model on the Persona-Chat training data by simply calling the train_model() method.
This will download the dataset (if it hasn’t already been downloaded) and start the training.
To train the model on your own data, you must create a JSON file with the following structure.
This structure follows the structure used in the Persona-Chat dataset as explained below. (Docs here)
Each entry in Persona-Chat is a dict with two keys personality and utterances, and the dataset is a list of entries.
personality: list of strings containing the personality of the agent
utterances: list of dictionaries, each of which has two keys which are lists of strings.
candidates: [next_utterance_candidate_1, ..., next_utterance_candidate_19]The last candidate is the ground truth response observed in the conversational data
history: [dialog_turn_0, ... dialog_turn N], where N is an odd number since the other user starts every conversation.
Preprocessing:
Spaces before periods at end of sentences
everything lowercase
Assuming you have created a JSON file with the given structure and saved it in data/train.json, you can train the model by executing the line below.
model.train_model("data/minimal_train.json")
Evaluation can be performed on the Persona-Chat dataset just as easily as the training by calling the eval_model() method.
As with training, you may provide a different evaluation dataset as long as it follows the correct structure.
Although you can get a numerical score by calculating metrics on an evaluation dataset, the best way to learn how good a Conversational AI is to actually converse with it.
To talk with the model you have just trained, simply call model.interact(). This will pick a random personality from the dataset and let you talk with it from the terminal.
model.interact()
Alternatively, you can create a personality on the fly by giving the interact() method a list of strings to build a personality from!
Tip: To load a trained model, you need to provide the path to the directory containing the model file when creating the ConvAIModel object.
model = ConvAIModel("gpt", "outputs")
That’s it! I hope this tutorial helps you on your way to creating your own chatbot!
|
[
{
"code": null,
"e": 568,
"s": 172,
"text": "Chatbots and virtual assistants, once found mostly in Sci-Fi, are becoming increasingly more common. Google Assistant’s and Siri’s of today still has a long, long way to go to reach Iron Man’s J.A.R.V.I.S. and the like, but the journey has begun. While the current crop of Conversational AI is far from perfect, they are also a far cry from their humble beginnings as simple programs like ELIZA."
},
{
"code": null,
"e": 1050,
"s": 568,
"text": "Moving away from the typical rule-based chatbots, Hugging Face came up with a Transformer based way to build chatbots that lets us leverage the state-of-the-art language modelling capabilities of models like BERT and OpenAI GPT. Using this method, we can quickly build powerful and impressive Conversational AI’s that can outperform most rule-based chatbots. It also eliminates the need for tedious rule building and script writing necessary for building a good rule-based chatbot."
},
{
"code": null,
"e": 1252,
"s": 1050,
"text": "Simple Transformers offers a way to build these Conversational AI models quickly, efficiently, and easily. The Simple Transformers implementation is built on the Hugging Face implementation given here."
},
{
"code": null,
"e": 1310,
"s": 1252,
"text": "Getting the environment set up is fairly straightforward."
},
{
"code": null,
"e": 1793,
"s": 1310,
"text": "Install Anaconda or Miniconda Package Manager from hereCreate a new virtual environment and install packages.conda create -n transformers pythonconda activate transformersIf using Cuda:conda install pytorch cudatoolkit=10.1 -c pytorchelse:conda install pytorch cpuonly -c pytorchInstall Apex if you are using fp16 training. Please follow the instructions here. (Installing Apex from pip has caused issues for several people.)Install simpletransformers.pip install simpletransformers"
},
{
"code": null,
"e": 1849,
"s": 1793,
"text": "Install Anaconda or Miniconda Package Manager from here"
},
{
"code": null,
"e": 2074,
"s": 1849,
"text": "Create a new virtual environment and install packages.conda create -n transformers pythonconda activate transformersIf using Cuda:conda install pytorch cudatoolkit=10.1 -c pytorchelse:conda install pytorch cpuonly -c pytorch"
},
{
"code": null,
"e": 2221,
"s": 2074,
"text": "Install Apex if you are using fp16 training. Please follow the instructions here. (Installing Apex from pip has caused issues for several people.)"
},
{
"code": null,
"e": 2279,
"s": 2221,
"text": "Install simpletransformers.pip install simpletransformers"
},
{
"code": null,
"e": 2558,
"s": 2279,
"text": "We’ll be using the Persona-Chat dataset. Note that you don’t need to manually download the dataset as the formatted JSON version of the dataset (provided by Hugging Face) will be automatically downloaded by Simple Transformers if no dataset is specified when training the model."
},
{
"code": null,
"e": 2733,
"s": 2558,
"text": "ConvAIModel is the class used in Simple Transformers to do all thing related to conversational AI models. This includes training, evaluating, and interacting with the models."
},
{
"code": null,
"e": 3162,
"s": 2733,
"text": "At the moment, you can use any of the OpenAI GPT or GPT-2 models with ConvAIModel. However, the pre-trained model provided by Hugging Face performs well out-of-the-box and will likely require less fine-tuning when creating your own chatbot. You can download the model from the here and extract the archive to follow along with the tutorial (which assumes you have downloaded the model and extracted it to gpt_personachat_cache)."
},
{
"code": null,
"e": 3263,
"s": 3162,
"text": "The code snippet above creates a ConvAIModel and loads the Transformer with the pre-trained weights."
},
{
"code": null,
"e": 3487,
"s": 3263,
"text": "The ConvAIModel comes with a wide range of configuration options, which can be found in the documentation here. You can also find the list of globally available configuration options in the Simple Transformers library here."
},
{
"code": null,
"e": 3601,
"s": 3487,
"text": "You can further fine-tune the model on the Persona-Chat training data by simply calling the train_model() method."
},
{
"code": null,
"e": 3695,
"s": 3601,
"text": "This will download the dataset (if it hasn’t already been downloaded) and start the training."
},
{
"code": null,
"e": 3790,
"s": 3695,
"text": "To train the model on your own data, you must create a JSON file with the following structure."
},
{
"code": null,
"e": 3892,
"s": 3790,
"text": "This structure follows the structure used in the Persona-Chat dataset as explained below. (Docs here)"
},
{
"code": null,
"e": 4009,
"s": 3892,
"text": "Each entry in Persona-Chat is a dict with two keys personality and utterances, and the dataset is a list of entries."
},
{
"code": null,
"e": 4078,
"s": 4009,
"text": "personality: list of strings containing the personality of the agent"
},
{
"code": null,
"e": 4167,
"s": 4078,
"text": "utterances: list of dictionaries, each of which has two keys which are lists of strings."
},
{
"code": null,
"e": 4325,
"s": 4167,
"text": "candidates: [next_utterance_candidate_1, ..., next_utterance_candidate_19]The last candidate is the ground truth response observed in the conversational data"
},
{
"code": null,
"e": 4443,
"s": 4325,
"text": "history: [dialog_turn_0, ... dialog_turn N], where N is an odd number since the other user starts every conversation."
},
{
"code": null,
"e": 4458,
"s": 4443,
"text": "Preprocessing:"
},
{
"code": null,
"e": 4500,
"s": 4458,
"text": "Spaces before periods at end of sentences"
},
{
"code": null,
"e": 4521,
"s": 4500,
"text": "everything lowercase"
},
{
"code": null,
"e": 4670,
"s": 4521,
"text": "Assuming you have created a JSON file with the given structure and saved it in data/train.json, you can train the model by executing the line below."
},
{
"code": null,
"e": 4715,
"s": 4670,
"text": "model.train_model(\"data/minimal_train.json\")"
},
{
"code": null,
"e": 4838,
"s": 4715,
"text": "Evaluation can be performed on the Persona-Chat dataset just as easily as the training by calling the eval_model() method."
},
{
"code": null,
"e": 4948,
"s": 4838,
"text": "As with training, you may provide a different evaluation dataset as long as it follows the correct structure."
},
{
"code": null,
"e": 5120,
"s": 4948,
"text": "Although you can get a numerical score by calculating metrics on an evaluation dataset, the best way to learn how good a Conversational AI is to actually converse with it."
},
{
"code": null,
"e": 5293,
"s": 5120,
"text": "To talk with the model you have just trained, simply call model.interact(). This will pick a random personality from the dataset and let you talk with it from the terminal."
},
{
"code": null,
"e": 5310,
"s": 5293,
"text": "model.interact()"
},
{
"code": null,
"e": 5444,
"s": 5310,
"text": "Alternatively, you can create a personality on the fly by giving the interact() method a list of strings to build a personality from!"
},
{
"code": null,
"e": 5584,
"s": 5444,
"text": "Tip: To load a trained model, you need to provide the path to the directory containing the model file when creating the ConvAIModel object."
},
{
"code": null,
"e": 5622,
"s": 5584,
"text": "model = ConvAIModel(\"gpt\", \"outputs\")"
}
] |
Word Segmentation for Languages Without Spaces Between Words | by Xu LIANG | Towards Data Science
|
If you are working on some NLP tasks related to Chinese, Japanese and Korean, you might notice that the NLP workflow is different from the English NLP task. Because different from the English, there is no space in these languages to separate the words naturally. So word segmentation is very important for these languages. I have done a little research about different word segmentation methods. In this post, I will give simple advice to choose the best approach.
Use the Unigram Language Model. You can the implementation from SentencePiece, which is a language-independent subword tokenizer. No matter what language you use, this is a good start.
The below sentence in English is separated with space, but the sentence in Japanese has no space.
The corresponding tokens in two languages look like below.
I -> 私will be -> になるthe prirate king -> 海賊王
So how to extract the “海賊王” is the word segmentation problem we need to deal with. Usually, there are three levels we can use, the word level, character level, subword level. But in recent years, the subword level approach has shown its superiority over other approaches, so in this post, I will focus on the subword level.
This post gives a great introduction about 3 subword algorithms:
Byte Pair Encoding (BPE)
WordPiece
Unigram Language Model
The author of the Unigram Language Model also implements a library, SentencePiece, which contains two subword algorithms, BPE and Unigram Language Model.
In the recent powerful language model, BERT uses the WordPiece model and XLNet uses the Unigram Language Model.
The greatest advantage of Unigram Language Model is that this is a language-independent model. No matter what language you use, this is a good start.
Check out my other posts on Medium with a categorized view!GitHub: BrambleXuLinkedIn: Xu LiangBlog: BrambleXu
|
[
{
"code": null,
"e": 637,
"s": 172,
"text": "If you are working on some NLP tasks related to Chinese, Japanese and Korean, you might notice that the NLP workflow is different from the English NLP task. Because different from the English, there is no space in these languages to separate the words naturally. So word segmentation is very important for these languages. I have done a little research about different word segmentation methods. In this post, I will give simple advice to choose the best approach."
},
{
"code": null,
"e": 822,
"s": 637,
"text": "Use the Unigram Language Model. You can the implementation from SentencePiece, which is a language-independent subword tokenizer. No matter what language you use, this is a good start."
},
{
"code": null,
"e": 920,
"s": 822,
"text": "The below sentence in English is separated with space, but the sentence in Japanese has no space."
},
{
"code": null,
"e": 979,
"s": 920,
"text": "The corresponding tokens in two languages look like below."
},
{
"code": null,
"e": 1023,
"s": 979,
"text": "I -> 私will be -> になるthe prirate king -> 海賊王"
},
{
"code": null,
"e": 1347,
"s": 1023,
"text": "So how to extract the “海賊王” is the word segmentation problem we need to deal with. Usually, there are three levels we can use, the word level, character level, subword level. But in recent years, the subword level approach has shown its superiority over other approaches, so in this post, I will focus on the subword level."
},
{
"code": null,
"e": 1412,
"s": 1347,
"text": "This post gives a great introduction about 3 subword algorithms:"
},
{
"code": null,
"e": 1437,
"s": 1412,
"text": "Byte Pair Encoding (BPE)"
},
{
"code": null,
"e": 1447,
"s": 1437,
"text": "WordPiece"
},
{
"code": null,
"e": 1470,
"s": 1447,
"text": "Unigram Language Model"
},
{
"code": null,
"e": 1624,
"s": 1470,
"text": "The author of the Unigram Language Model also implements a library, SentencePiece, which contains two subword algorithms, BPE and Unigram Language Model."
},
{
"code": null,
"e": 1736,
"s": 1624,
"text": "In the recent powerful language model, BERT uses the WordPiece model and XLNet uses the Unigram Language Model."
},
{
"code": null,
"e": 1886,
"s": 1736,
"text": "The greatest advantage of Unigram Language Model is that this is a language-independent model. No matter what language you use, this is a good start."
}
] |
Sum of list (with string types) in Python
|
In this tutorial, we are going to write a program that adds all numbers from the list. List may contain numbers in string or integer format. See the example.
random_list = [1, '10', 'tutorialspoint', '2020', 'tutorialspoint@2020', 2020]
4051
Follow the below steps to write the program.
Initialize the list.
3Initialize a variable total with 0.
Iterate over the list.
If the element is int, then add it to the total by checking two conditions.The element will be int -> Check type.The element will be a number in string format -> Check using isdigit() method.
The element will be int -> Check type.
The element will be a number in string format -> Check using isdigit() method.
Print the total
Live Demo
# initialzing the list
random_list = [1, '10', 'tutorialspoint', '2020', 'tutorialspoint@2020', 2020]
# initializing the variable total
total = 0
# iterating over the list
for element in random_list:
# checking whether its a number or not
if isinstance(element, int) or element.isdigit():
# adding the element to the total
total += int(element)
# printing the total
print(total)
If you run the above code, then you will get the following result.
4051
If you have any doubts in the tutorial, mention them in the comment section.
|
[
{
"code": null,
"e": 1220,
"s": 1062,
"text": "In this tutorial, we are going to write a program that adds all numbers from the list. List may contain numbers in string or integer format. See the example."
},
{
"code": null,
"e": 1299,
"s": 1220,
"text": "random_list = [1, '10', 'tutorialspoint', '2020', 'tutorialspoint@2020', 2020]"
},
{
"code": null,
"e": 1304,
"s": 1299,
"text": "4051"
},
{
"code": null,
"e": 1349,
"s": 1304,
"text": "Follow the below steps to write the program."
},
{
"code": null,
"e": 1370,
"s": 1349,
"text": "Initialize the list."
},
{
"code": null,
"e": 1407,
"s": 1370,
"text": "3Initialize a variable total with 0."
},
{
"code": null,
"e": 1430,
"s": 1407,
"text": "Iterate over the list."
},
{
"code": null,
"e": 1622,
"s": 1430,
"text": "If the element is int, then add it to the total by checking two conditions.The element will be int -> Check type.The element will be a number in string format -> Check using isdigit() method."
},
{
"code": null,
"e": 1661,
"s": 1622,
"text": "The element will be int -> Check type."
},
{
"code": null,
"e": 1740,
"s": 1661,
"text": "The element will be a number in string format -> Check using isdigit() method."
},
{
"code": null,
"e": 1756,
"s": 1740,
"text": "Print the total"
},
{
"code": null,
"e": 1767,
"s": 1756,
"text": " Live Demo"
},
{
"code": null,
"e": 2164,
"s": 1767,
"text": "# initialzing the list\nrandom_list = [1, '10', 'tutorialspoint', '2020', 'tutorialspoint@2020', 2020]\n# initializing the variable total\ntotal = 0\n# iterating over the list\nfor element in random_list:\n # checking whether its a number or not\n if isinstance(element, int) or element.isdigit():\n # adding the element to the total\n total += int(element)\n# printing the total\nprint(total)"
},
{
"code": null,
"e": 2231,
"s": 2164,
"text": "If you run the above code, then you will get the following result."
},
{
"code": null,
"e": 2236,
"s": 2231,
"text": "4051"
},
{
"code": null,
"e": 2313,
"s": 2236,
"text": "If you have any doubts in the tutorial, mention them in the comment section."
}
] |
Plot in Python with Matplotlib Step by Step | by Matias Eiletz | Towards Data Science
|
Matplotlib is the most popular graphics library in Python. For instance if we look in StackOverflow, we can see that there are ~47k questions tagged with Matoplotlib, whereas if we look for other comparable libraries like Seaborn or Plotly, we get ~4k and ~7k respectively.
Hence if you are getting started with plotting in Python, I strongly recommend you to use Matplotlib, not only for the popularity reason, but also because for example Seaborn is built on top of Matplotlib, so if you understand how to plot in Matplotlib, then you will easily understand how to handle Seaborn (and it’s not the same on the other way around).
If you already work with Matplotlib, I also encourage you to stay here because you may discover new things about plotting in Python.
So in this article I would like to show you how to plot in Matplotlib, going smoothly from simple plots, to more complex stuff, giving you also the necessary tools to discover how to plot new stuff on your own.
You won’t need to download any dataset. We are going to create the necessary ones during the article, so you would be able to copy and paste and try them on your own, in a Juptyer notebook for instance.
As a sneak peek, we will be seeing all the tools needed to go from this first basic plot in the first section to the following histogram presented at the end of the second section.
Importing necessary packages
Change plot size
Starting with the first basic plot
Change line style, markers, and width
Scatter plot
Bar plot
Combine several plots in one
Modify axes
Add grid and legend
More about modifying axes
Add values on top of the plot
Add lines on top of the plot
Histograms
Bonus: Twin axes
Let’s now get started!
First we have to import the Matplotlib package, and run the magic function %matplotlib inline. This magic function is the one that will make the plots appear in your Jupyter Notebook.
import matplotlib.pyplot as plt%matplotlib inline
Matplotlib comes pre-installed in Anaconda distribution for instance, but in case the previous commands fail because you don’t have Matplotlib package installed, you can do it running this in your terminal:
python -m pip install -U pippython -m pip install -U matplotlib
Also to follow all the examples we will be going through, you have to do the following basic imports:
import pandas as pdimport numpy as np
If we want to change the plot size output, we need to change from properties. First, we can see what are the current properties:
# get current sizefig_size = plt.rcParams["figure.figsize"]print ("Current size:", fig_size)# let's make the plots a bit bigger than the default# set figure width to 14 and height to 6fig_size[0] = 14fig_size[1] = 6plt.rcParams["figure.figsize"] = fig_sizeprint ("Current size:", fig_size)
As we said, we are going to generate our own datasets to work.
# datasets x and y are lists, but they can also be, for instance, numpy arrays or pd.Series.x = [1, 2, 3, 4, 5]y = [25, 32, 34, 20, 25]# plotplt.plot(x, y)
From this, we get the simple plot:
It can be useful to do a quick check for the data you are working with, however, it is not really informative if you are going to put it into a presentation. Let’s continue and see how to put it on steroids.
Let’s say we want the line to be dashed and thicker, the markers to be circles and bigger, and the color to be green. Then, we add the five parameters that you can see after the x and y.
x = [1, 2, 3, 4, 5]y = [25, 32, 34, 20, 25]plt.plot(x, y, color='green' , marker='o', markersize=20, linestyle='--', linewidth=4)
And now we get the following:
These are just some parameters you can modify, but you can find the whole list in the Matplotlib documentation (I will add the link at the bottom of the article).
If you are plotting some discrete data, you may want to plot only the dots (or the markers, more generally). Then, you can use plt.scatter, which works almost the same as plt.plot, for example:
x = [1, 2, 3, 4, 5]y = [25, 32, 34, 20, 25]# specifying the type of marker (dots) and its sizesplt.scatter(x, y, marker='o', size=150)
Giving as a result:
And the same we can do if we want to plot the data in bars:
x = [1, 2, 3, 4, 5]y = [25, 32, 34, 20, 25]# specifying the bar colorsplt.bar(x, y, color=’green’)
Getting the following plot:
It’s good to point out that we can combine the three of them, doing something like:
x = [1, 2, 3, 4, 5]y = [25, 32, 34, 20, 25]plt.plot(x, y, color=’blue’, lw=4, alpha=0.5)plt.scatter(x, y, marker=’o’, s=400, color=’red’,alpha=0.5)plt.bar(x, y, color=’green’,alpha=0.5)
Giving as a result:
You may wonder what is that new variable alpha: it is a parameter that stands for the level of transparency. alpha=0 is totally transparent, and alpha=1 it is as if we didn’t set any alpha parameter (not transparent at all). It’s because of this transparency that you can see the red dots behind the bars, and the same with the blue line going on top of the bars. You can try the same with alpha=1 and you will see the difference!
The previous plots were nice, but there is still a lot we can do, especially if we want to make the plot more understandable or for a presentation. Maybe we want to put some limits or extend the axes from it. So let’s run the following and check the result:
x = [1, 2, 3, 4, 5]y = [25, 32, 34, 20, 25]plt.plot(x, y)# here we modify the axes, specifying min and max for x and y axes.plt.axis(xmin=-1, xmax=10, ymin=0, ymax=40)
That’s a simple way. But what if you want to specify what is on the x-axis or in the y-axis? We can see for example that in the x-axis the numbers go 2 by 2. We can change it with x-ticks or y-ticks:
plt.plot(x, y)plt.axis(xmin=-1, xmax=12, ymin=0, ymax=40)plt.xticks(np.arange(0,13,1))
Sometimes we get a little lost in the plot, and we need a grid. That is very simple! We have to add the plt.grid method like this:
plt.plot(x, y)plt.axis(xmin=-1, xmax=12, ymin=0, ymax=40)plt.xticks(np.arange(0,13,1))plt.grid(True)
Another useful feature to add to a plot, especially if you are planning to add to a presentation to communicate findings and you want the audience to understand the plot as quickly as possible, it is to add a legend. This is very simple, and it goes like this:
plt.plot(x, y,label='Nice Blue Line')plt.axis(xmin=-1, xmax=12, ymin=0, ymax=40)plt.grid(True)plt.legend(loc='upper right',prop={'size':24})
In plt.legend() example from above, I choose the size from it and the location in the plot (upper right).
Let’s go back now to the axes, and let’s modify some stuff all at once:
Change the x-ticks names (for dates, in this case)
Rotate axis
Increase the size from the x-ticks and y-ticks in the axes
Add label to the axes (and choose their font size and separation from the axes with labelpad)
Add a title to the plot
plt.plot(x, y,label='Nice Blue Line')plt.axis(xmin=0, xmax=6, ymin=0, ymax=40)# here we change the x-ticksplt.xticks(x, ('2019-02-01', '2019-02-02', '2019-02-03','2019-02-04', '2019-02-05'))# here we rotate the x-ticksplt.xticks(rotation=45)# here we change the size from both axes ticksplt.tick_params(axis='both', labelsize = 16)# here we add the axes labelsplt.ylabel('Y Label', size=16, labelpad=20)plt.xlabel('X Label', size=16, labelpad=20)# here we add the titleplt.title('Plot Title', size=18)# here we add the gridplt.grid(True)
Rotating the labels is especially useful when we have dates in the x-axis like in this example or larger numbers that one value can get over the previous and next one.
Now that we have already made our plots neat and with clear references, let’s continue with the second section.
This second section is about adding extra features to the plot itself.
I will show you how to add the numbers indicating the values in the plot, how to add lines, and in the end as a bonus, an example of this all together in a histogram.
# we use the same data points as beforex = [1, 2, 3, 4, 5]y = [25, 32, 34, 20, 25]# we plot the data pointsplt.plot(x, y)plt.axis(xmin=0, xmax=6, ymin=10, ymax=40)plt.title('Plot Title', size=18)# here we add the value in one data pointplt.annotate(str(25),xy=(1,25+1), fontsize=14)
And there we have what we wanted.
In the plot.annotate method we pass as a first argument the string we want to show (the value 25 in the shape of a string in this case) and then the coordinates: x:1 and y:25+1 (we add the +1 so that the number is not on overlapping the line).
This is not useful, however, if we have a lot of data points and we want to plot all the values on top of the curve. So let’s look at this other way, in order to do it automated for all the values:
x = [1, 2, 3, 4, 5]y = [25, 32, 34, 20, 25]# we plot the data pointsplt.plot(x, y)plt.axis(xmin=0, xmax=6, ymin=10, ymax=40)plt.title('Plot Title', size=18)# here we add all the values# we also specify font size and colorfor i,j in zip(x,y): inplot = plt.annotate(str(j) ,xy=(i,j+1) ,fontsize=12 ,color='black')
Getting, as a result, this plot:
So here as you can see, we did a for loop to plot all the values.
We used the zip function, a very useful one, that allows us to get more than one variable in each loop.
When you want to highlight one of the values from a plot, this is something that comes handy. You can use a vertical line if you want to highlight the x-axis value or a horizontal one if you want to do it with the y-axis value. For the purpose of this example, let’s use both of them:
x = [1, 2, 3, 4, 5]y = [25, 32, 34, 20, 25]plt.plot(x, y)plt.axis(xmin=0, xmax=6, ymin=10, ymax=40)plt.title('Plot Title', size=18)# here we add the vertical lineplt.axvline(x[1], color='red',linestyle='--',linewidth=1)# here we add the horizontal lineplt.axhline(y[1], color='orange',linestyle='--',linewidth=1)
As promised at the beginning of the second section, we are going to create a histogram. We are going to add a cumulative curve, and we are going to use all the extra features explained before, showing how all these features add valuable information to a plot.
The objective is to go from a very simple histogram, like from this one:
To (spoiler alert) this one:
Or to this one (with twin axes so that curve and bars have the same heigh):
I’m going to generate a toy dataset with the following code. You can copy and paste it in your Jupyter notebook to continue with the example. My objective is to show you the plot, not the creation of the dataset, so it’s because of that that I’m not going to explain the details of the following code. If you have any questions about this, however, please let me know in the comments.
data = np.random.chisquare(2,5000)r = range(12)df = pd.DataFrame(data)values = np.histogram(df, bins=r)[0]bins = np.histogram(df, bins=r)[1].astype(int)df = pd.DataFrame({'bins_left': bins[:-1],'bins_right': bins[1:], 'values': values})df['values_norm'] = df['values'] / df['values'].sum()df['labels'] = df.apply(lambda x: str(int(x['bins_left'])) + '-' + str(int(x['bins_right'])),axis=1)df['cumulative'] = df['values'].cumsum()df['perc_cumulative'] = df['cumulative']/df.cumulative.max()df['perc_cum_label'] = df.apply(lambda x: str(round(x['perc_cumulative']*100,1)) + '%',axis=1)df = df[['labels','values','values_norm','cumulative','perc_cumulative','perc_cum_label']]
So, in the end, we have this dataframe:
So in this data array, we have 5000 values, that for the sake of this example, let’s say that they represent the weights from a community of 5000 rabbits. So, we have 1935 rabbits weight between 0 and 1 kilo, 1232 of them weight between 1 and 2 kilos, and, only 15 of them, weight between 10 and 11 kilos. As the majority of them are very light, we can assume that is a community of baby rabbits with just some adults around.
The only values that are on our interest for the histogram x and y-axis, are the ones in the first two columns (labels and values).
The other columns will be useful for indicating other features in the plot.
Now, let’s go to build the histogram.
We can do a very simple one, doing this:
pd.DataFrame(data).hist()
Which will give us a plot, but far from being completely understandable at a first quick glance.
If someone asks us, “what percentage of the rabbits’ weight between 0 and 1 kilograms?” is difficult to answer looking at this plot.
If we want to make a more meaningful histogram plot, let’s make the one from before (the one from the spoiler alert) using only tools that we went over before:
# plot the bars from the histogramx = np.array(df['labels'])y = np.array(df['values_norm'])plt.bar(x,y)# plot the cumulative curvex = list(range(len(x)))y = list(df['perc_cumulative'])plt.plot(x,y,color='orange',marker='o')# change the y-axis limitsplt.axis(ymin=0, ymax=1.1)# plot the values from the cumulative curve on top of ity_labels = list(df['perc_cum_label'])for i,j in zip(x,y): inplot = plt.annotate(str(y_labels[i]) ,xy=(i-0.1,j+0.05) ,fontsize=12 ,color='black')# draw vertical lines in 50, 75 and 90 percentile.plt.axvline(np.percentile(data,50)-1, color='maroon',linestyle='--',linewidth=1)plt.axvline(np.percentile(data,75)-1, color='maroon',linestyle='--',linewidth=1)plt.axvline(np.percentile(data,90)-1, color='maroon',linestyle='--',linewidth=1)# indicate which percentile is each linep_values = [np.percentile(data,50),np.percentile(data,75),np.percentile(data,90)]p_numbers = ['p50', 'p75', 'p90']for i, j in zip(p_values, p_numbers): inplot = plt.annotate(j ,xy=(i-1 + 0.05, 1.05) ,fontsize=12 ,color='maroon')# some final tweaking in title, axis and labelsplt.title('Histogram and cumulative curve',fontsize=15)plt.ylabel('Bins', size=15, labelpad=18)plt.xlabel('Frequency', size=15, labelpad=18)plt.tick_params(axis='both', labelsize = 14)
Giving as a result:
We can do the same plot, but having the bars at the same level as the curve. We achieve this by generating twin axes.
As you will see, the code is very similar, with the particularity that at the beginning we create the twin axes. Then, we generate both plots (bars and curve), but instead of starting both of them with plt., one of them will start with host. And the other one, with par.
# we import this package for the twin axesfrom mpl_toolkits.axes_grid1 import host_subplot# we generate the twin axeshost = host_subplot(111)par = host.twinx()# we plot the bars (use host. instead of plt.)x = np.array(df['labels'])y = np.array(df['values_norm'])p1 = host.bar(x, y, color='steelblue')# we plot the curve (use par. instead of plt.)x = list(range(len(x)))y = list(df['perc_cumulative'])p2 = par.plot(x, y, color='darkorange',marker='o')# we plot the values from the cumulative curve on top of ity_labels = list(df['perc_cum_label'])for i,j in zip(x,y): inplot = par.annotate(str(y_labels[i]) ,xy=(i-0.1,j+0.05) ,fontsize=12 ,color='black')# some final tweaking in title, axis and labelsplt.title('Histogram and cumulative curve',fontsize=15)par.axis(ymin=0, ymax=1.1)host.set_xlabel("Bins", size=13, labelpad = 16)host.set_ylabel("Frequency", size=13, labelpad = 16)# draw vertical lines in 50, 75 and 90 percentile.plt.axvline(np.percentile(data,50)-1, color='maroon',linestyle='--',linewidth=1.5)plt.axvline(np.percentile(data,75)-1, color='maroon',linestyle='--',linewidth=1.5)plt.axvline(np.percentile(data,90)-1, color='maroon',linestyle='--',linewidth=1.5)# indicate which percentile is each linep_values = p_values = [np.percentile(data,50),np.percentile(data,75),np.percentile(data,90)]p_numbers = ['p50', 'p75', 'p90']for i, j in zip(p_values, p_numbers): inplot = plt.annotate(j ,xy=(i-1 + 0.05, 0.39) ,fontsize=10 ,color='maroon')
Getting, in the end, the desired plot:
And we reached the end! I hope you have enjoyed the article and that you have learned a lot (or at least a few) new things to improve your plotting skills in Python.
Follow me if you want to see more articles like this in the future.
You can also look at my previous articles, like:
Mastering Dates and Timestamps in Pandas (and Python in general) (same style as the current article)
Other articles:
Analyzing User behavior and UX performance with Feature importance
And as promised at the beginning of the First Section, a link to Matplotlib documentation where you can see everything about markers, line styles, etc:
Matplotlib Documentation
Thanks for reading!
|
[
{
"code": null,
"e": 445,
"s": 171,
"text": "Matplotlib is the most popular graphics library in Python. For instance if we look in StackOverflow, we can see that there are ~47k questions tagged with Matoplotlib, whereas if we look for other comparable libraries like Seaborn or Plotly, we get ~4k and ~7k respectively."
},
{
"code": null,
"e": 802,
"s": 445,
"text": "Hence if you are getting started with plotting in Python, I strongly recommend you to use Matplotlib, not only for the popularity reason, but also because for example Seaborn is built on top of Matplotlib, so if you understand how to plot in Matplotlib, then you will easily understand how to handle Seaborn (and it’s not the same on the other way around)."
},
{
"code": null,
"e": 935,
"s": 802,
"text": "If you already work with Matplotlib, I also encourage you to stay here because you may discover new things about plotting in Python."
},
{
"code": null,
"e": 1146,
"s": 935,
"text": "So in this article I would like to show you how to plot in Matplotlib, going smoothly from simple plots, to more complex stuff, giving you also the necessary tools to discover how to plot new stuff on your own."
},
{
"code": null,
"e": 1349,
"s": 1146,
"text": "You won’t need to download any dataset. We are going to create the necessary ones during the article, so you would be able to copy and paste and try them on your own, in a Juptyer notebook for instance."
},
{
"code": null,
"e": 1530,
"s": 1349,
"text": "As a sneak peek, we will be seeing all the tools needed to go from this first basic plot in the first section to the following histogram presented at the end of the second section."
},
{
"code": null,
"e": 1559,
"s": 1530,
"text": "Importing necessary packages"
},
{
"code": null,
"e": 1576,
"s": 1559,
"text": "Change plot size"
},
{
"code": null,
"e": 1611,
"s": 1576,
"text": "Starting with the first basic plot"
},
{
"code": null,
"e": 1649,
"s": 1611,
"text": "Change line style, markers, and width"
},
{
"code": null,
"e": 1662,
"s": 1649,
"text": "Scatter plot"
},
{
"code": null,
"e": 1671,
"s": 1662,
"text": "Bar plot"
},
{
"code": null,
"e": 1700,
"s": 1671,
"text": "Combine several plots in one"
},
{
"code": null,
"e": 1712,
"s": 1700,
"text": "Modify axes"
},
{
"code": null,
"e": 1732,
"s": 1712,
"text": "Add grid and legend"
},
{
"code": null,
"e": 1758,
"s": 1732,
"text": "More about modifying axes"
},
{
"code": null,
"e": 1788,
"s": 1758,
"text": "Add values on top of the plot"
},
{
"code": null,
"e": 1817,
"s": 1788,
"text": "Add lines on top of the plot"
},
{
"code": null,
"e": 1828,
"s": 1817,
"text": "Histograms"
},
{
"code": null,
"e": 1845,
"s": 1828,
"text": "Bonus: Twin axes"
},
{
"code": null,
"e": 1868,
"s": 1845,
"text": "Let’s now get started!"
},
{
"code": null,
"e": 2052,
"s": 1868,
"text": "First we have to import the Matplotlib package, and run the magic function %matplotlib inline. This magic function is the one that will make the plots appear in your Jupyter Notebook."
},
{
"code": null,
"e": 2102,
"s": 2052,
"text": "import matplotlib.pyplot as plt%matplotlib inline"
},
{
"code": null,
"e": 2309,
"s": 2102,
"text": "Matplotlib comes pre-installed in Anaconda distribution for instance, but in case the previous commands fail because you don’t have Matplotlib package installed, you can do it running this in your terminal:"
},
{
"code": null,
"e": 2373,
"s": 2309,
"text": "python -m pip install -U pippython -m pip install -U matplotlib"
},
{
"code": null,
"e": 2475,
"s": 2373,
"text": "Also to follow all the examples we will be going through, you have to do the following basic imports:"
},
{
"code": null,
"e": 2513,
"s": 2475,
"text": "import pandas as pdimport numpy as np"
},
{
"code": null,
"e": 2642,
"s": 2513,
"text": "If we want to change the plot size output, we need to change from properties. First, we can see what are the current properties:"
},
{
"code": null,
"e": 2932,
"s": 2642,
"text": "# get current sizefig_size = plt.rcParams[\"figure.figsize\"]print (\"Current size:\", fig_size)# let's make the plots a bit bigger than the default# set figure width to 14 and height to 6fig_size[0] = 14fig_size[1] = 6plt.rcParams[\"figure.figsize\"] = fig_sizeprint (\"Current size:\", fig_size)"
},
{
"code": null,
"e": 2995,
"s": 2932,
"text": "As we said, we are going to generate our own datasets to work."
},
{
"code": null,
"e": 3151,
"s": 2995,
"text": "# datasets x and y are lists, but they can also be, for instance, numpy arrays or pd.Series.x = [1, 2, 3, 4, 5]y = [25, 32, 34, 20, 25]# plotplt.plot(x, y)"
},
{
"code": null,
"e": 3186,
"s": 3151,
"text": "From this, we get the simple plot:"
},
{
"code": null,
"e": 3394,
"s": 3186,
"text": "It can be useful to do a quick check for the data you are working with, however, it is not really informative if you are going to put it into a presentation. Let’s continue and see how to put it on steroids."
},
{
"code": null,
"e": 3581,
"s": 3394,
"text": "Let’s say we want the line to be dashed and thicker, the markers to be circles and bigger, and the color to be green. Then, we add the five parameters that you can see after the x and y."
},
{
"code": null,
"e": 3711,
"s": 3581,
"text": "x = [1, 2, 3, 4, 5]y = [25, 32, 34, 20, 25]plt.plot(x, y, color='green' , marker='o', markersize=20, linestyle='--', linewidth=4)"
},
{
"code": null,
"e": 3741,
"s": 3711,
"text": "And now we get the following:"
},
{
"code": null,
"e": 3904,
"s": 3741,
"text": "These are just some parameters you can modify, but you can find the whole list in the Matplotlib documentation (I will add the link at the bottom of the article)."
},
{
"code": null,
"e": 4098,
"s": 3904,
"text": "If you are plotting some discrete data, you may want to plot only the dots (or the markers, more generally). Then, you can use plt.scatter, which works almost the same as plt.plot, for example:"
},
{
"code": null,
"e": 4233,
"s": 4098,
"text": "x = [1, 2, 3, 4, 5]y = [25, 32, 34, 20, 25]# specifying the type of marker (dots) and its sizesplt.scatter(x, y, marker='o', size=150)"
},
{
"code": null,
"e": 4253,
"s": 4233,
"text": "Giving as a result:"
},
{
"code": null,
"e": 4313,
"s": 4253,
"text": "And the same we can do if we want to plot the data in bars:"
},
{
"code": null,
"e": 4412,
"s": 4313,
"text": "x = [1, 2, 3, 4, 5]y = [25, 32, 34, 20, 25]# specifying the bar colorsplt.bar(x, y, color=’green’)"
},
{
"code": null,
"e": 4440,
"s": 4412,
"text": "Getting the following plot:"
},
{
"code": null,
"e": 4524,
"s": 4440,
"text": "It’s good to point out that we can combine the three of them, doing something like:"
},
{
"code": null,
"e": 4710,
"s": 4524,
"text": "x = [1, 2, 3, 4, 5]y = [25, 32, 34, 20, 25]plt.plot(x, y, color=’blue’, lw=4, alpha=0.5)plt.scatter(x, y, marker=’o’, s=400, color=’red’,alpha=0.5)plt.bar(x, y, color=’green’,alpha=0.5)"
},
{
"code": null,
"e": 4730,
"s": 4710,
"text": "Giving as a result:"
},
{
"code": null,
"e": 5161,
"s": 4730,
"text": "You may wonder what is that new variable alpha: it is a parameter that stands for the level of transparency. alpha=0 is totally transparent, and alpha=1 it is as if we didn’t set any alpha parameter (not transparent at all). It’s because of this transparency that you can see the red dots behind the bars, and the same with the blue line going on top of the bars. You can try the same with alpha=1 and you will see the difference!"
},
{
"code": null,
"e": 5419,
"s": 5161,
"text": "The previous plots were nice, but there is still a lot we can do, especially if we want to make the plot more understandable or for a presentation. Maybe we want to put some limits or extend the axes from it. So let’s run the following and check the result:"
},
{
"code": null,
"e": 5587,
"s": 5419,
"text": "x = [1, 2, 3, 4, 5]y = [25, 32, 34, 20, 25]plt.plot(x, y)# here we modify the axes, specifying min and max for x and y axes.plt.axis(xmin=-1, xmax=10, ymin=0, ymax=40)"
},
{
"code": null,
"e": 5787,
"s": 5587,
"text": "That’s a simple way. But what if you want to specify what is on the x-axis or in the y-axis? We can see for example that in the x-axis the numbers go 2 by 2. We can change it with x-ticks or y-ticks:"
},
{
"code": null,
"e": 5874,
"s": 5787,
"text": "plt.plot(x, y)plt.axis(xmin=-1, xmax=12, ymin=0, ymax=40)plt.xticks(np.arange(0,13,1))"
},
{
"code": null,
"e": 6005,
"s": 5874,
"text": "Sometimes we get a little lost in the plot, and we need a grid. That is very simple! We have to add the plt.grid method like this:"
},
{
"code": null,
"e": 6106,
"s": 6005,
"text": "plt.plot(x, y)plt.axis(xmin=-1, xmax=12, ymin=0, ymax=40)plt.xticks(np.arange(0,13,1))plt.grid(True)"
},
{
"code": null,
"e": 6367,
"s": 6106,
"text": "Another useful feature to add to a plot, especially if you are planning to add to a presentation to communicate findings and you want the audience to understand the plot as quickly as possible, it is to add a legend. This is very simple, and it goes like this:"
},
{
"code": null,
"e": 6508,
"s": 6367,
"text": "plt.plot(x, y,label='Nice Blue Line')plt.axis(xmin=-1, xmax=12, ymin=0, ymax=40)plt.grid(True)plt.legend(loc='upper right',prop={'size':24})"
},
{
"code": null,
"e": 6614,
"s": 6508,
"text": "In plt.legend() example from above, I choose the size from it and the location in the plot (upper right)."
},
{
"code": null,
"e": 6686,
"s": 6614,
"text": "Let’s go back now to the axes, and let’s modify some stuff all at once:"
},
{
"code": null,
"e": 6737,
"s": 6686,
"text": "Change the x-ticks names (for dates, in this case)"
},
{
"code": null,
"e": 6749,
"s": 6737,
"text": "Rotate axis"
},
{
"code": null,
"e": 6808,
"s": 6749,
"text": "Increase the size from the x-ticks and y-ticks in the axes"
},
{
"code": null,
"e": 6902,
"s": 6808,
"text": "Add label to the axes (and choose their font size and separation from the axes with labelpad)"
},
{
"code": null,
"e": 6926,
"s": 6902,
"text": "Add a title to the plot"
},
{
"code": null,
"e": 7464,
"s": 6926,
"text": "plt.plot(x, y,label='Nice Blue Line')plt.axis(xmin=0, xmax=6, ymin=0, ymax=40)# here we change the x-ticksplt.xticks(x, ('2019-02-01', '2019-02-02', '2019-02-03','2019-02-04', '2019-02-05'))# here we rotate the x-ticksplt.xticks(rotation=45)# here we change the size from both axes ticksplt.tick_params(axis='both', labelsize = 16)# here we add the axes labelsplt.ylabel('Y Label', size=16, labelpad=20)plt.xlabel('X Label', size=16, labelpad=20)# here we add the titleplt.title('Plot Title', size=18)# here we add the gridplt.grid(True)"
},
{
"code": null,
"e": 7632,
"s": 7464,
"text": "Rotating the labels is especially useful when we have dates in the x-axis like in this example or larger numbers that one value can get over the previous and next one."
},
{
"code": null,
"e": 7744,
"s": 7632,
"text": "Now that we have already made our plots neat and with clear references, let’s continue with the second section."
},
{
"code": null,
"e": 7815,
"s": 7744,
"text": "This second section is about adding extra features to the plot itself."
},
{
"code": null,
"e": 7982,
"s": 7815,
"text": "I will show you how to add the numbers indicating the values in the plot, how to add lines, and in the end as a bonus, an example of this all together in a histogram."
},
{
"code": null,
"e": 8265,
"s": 7982,
"text": "# we use the same data points as beforex = [1, 2, 3, 4, 5]y = [25, 32, 34, 20, 25]# we plot the data pointsplt.plot(x, y)plt.axis(xmin=0, xmax=6, ymin=10, ymax=40)plt.title('Plot Title', size=18)# here we add the value in one data pointplt.annotate(str(25),xy=(1,25+1), fontsize=14)"
},
{
"code": null,
"e": 8299,
"s": 8265,
"text": "And there we have what we wanted."
},
{
"code": null,
"e": 8543,
"s": 8299,
"text": "In the plot.annotate method we pass as a first argument the string we want to show (the value 25 in the shape of a string in this case) and then the coordinates: x:1 and y:25+1 (we add the +1 so that the number is not on overlapping the line)."
},
{
"code": null,
"e": 8741,
"s": 8543,
"text": "This is not useful, however, if we have a lot of data points and we want to plot all the values on top of the curve. So let’s look at this other way, in order to do it automated for all the values:"
},
{
"code": null,
"e": 9131,
"s": 8741,
"text": "x = [1, 2, 3, 4, 5]y = [25, 32, 34, 20, 25]# we plot the data pointsplt.plot(x, y)plt.axis(xmin=0, xmax=6, ymin=10, ymax=40)plt.title('Plot Title', size=18)# here we add all the values# we also specify font size and colorfor i,j in zip(x,y): inplot = plt.annotate(str(j) ,xy=(i,j+1) ,fontsize=12 ,color='black')"
},
{
"code": null,
"e": 9164,
"s": 9131,
"text": "Getting, as a result, this plot:"
},
{
"code": null,
"e": 9230,
"s": 9164,
"text": "So here as you can see, we did a for loop to plot all the values."
},
{
"code": null,
"e": 9334,
"s": 9230,
"text": "We used the zip function, a very useful one, that allows us to get more than one variable in each loop."
},
{
"code": null,
"e": 9619,
"s": 9334,
"text": "When you want to highlight one of the values from a plot, this is something that comes handy. You can use a vertical line if you want to highlight the x-axis value or a horizontal one if you want to do it with the y-axis value. For the purpose of this example, let’s use both of them:"
},
{
"code": null,
"e": 9932,
"s": 9619,
"text": "x = [1, 2, 3, 4, 5]y = [25, 32, 34, 20, 25]plt.plot(x, y)plt.axis(xmin=0, xmax=6, ymin=10, ymax=40)plt.title('Plot Title', size=18)# here we add the vertical lineplt.axvline(x[1], color='red',linestyle='--',linewidth=1)# here we add the horizontal lineplt.axhline(y[1], color='orange',linestyle='--',linewidth=1)"
},
{
"code": null,
"e": 10192,
"s": 9932,
"text": "As promised at the beginning of the second section, we are going to create a histogram. We are going to add a cumulative curve, and we are going to use all the extra features explained before, showing how all these features add valuable information to a plot."
},
{
"code": null,
"e": 10265,
"s": 10192,
"text": "The objective is to go from a very simple histogram, like from this one:"
},
{
"code": null,
"e": 10294,
"s": 10265,
"text": "To (spoiler alert) this one:"
},
{
"code": null,
"e": 10370,
"s": 10294,
"text": "Or to this one (with twin axes so that curve and bars have the same heigh):"
},
{
"code": null,
"e": 10755,
"s": 10370,
"text": "I’m going to generate a toy dataset with the following code. You can copy and paste it in your Jupyter notebook to continue with the example. My objective is to show you the plot, not the creation of the dataset, so it’s because of that that I’m not going to explain the details of the following code. If you have any questions about this, however, please let me know in the comments."
},
{
"code": null,
"e": 11429,
"s": 10755,
"text": "data = np.random.chisquare(2,5000)r = range(12)df = pd.DataFrame(data)values = np.histogram(df, bins=r)[0]bins = np.histogram(df, bins=r)[1].astype(int)df = pd.DataFrame({'bins_left': bins[:-1],'bins_right': bins[1:], 'values': values})df['values_norm'] = df['values'] / df['values'].sum()df['labels'] = df.apply(lambda x: str(int(x['bins_left'])) + '-' + str(int(x['bins_right'])),axis=1)df['cumulative'] = df['values'].cumsum()df['perc_cumulative'] = df['cumulative']/df.cumulative.max()df['perc_cum_label'] = df.apply(lambda x: str(round(x['perc_cumulative']*100,1)) + '%',axis=1)df = df[['labels','values','values_norm','cumulative','perc_cumulative','perc_cum_label']]"
},
{
"code": null,
"e": 11469,
"s": 11429,
"text": "So, in the end, we have this dataframe:"
},
{
"code": null,
"e": 11895,
"s": 11469,
"text": "So in this data array, we have 5000 values, that for the sake of this example, let’s say that they represent the weights from a community of 5000 rabbits. So, we have 1935 rabbits weight between 0 and 1 kilo, 1232 of them weight between 1 and 2 kilos, and, only 15 of them, weight between 10 and 11 kilos. As the majority of them are very light, we can assume that is a community of baby rabbits with just some adults around."
},
{
"code": null,
"e": 12027,
"s": 11895,
"text": "The only values that are on our interest for the histogram x and y-axis, are the ones in the first two columns (labels and values)."
},
{
"code": null,
"e": 12103,
"s": 12027,
"text": "The other columns will be useful for indicating other features in the plot."
},
{
"code": null,
"e": 12141,
"s": 12103,
"text": "Now, let’s go to build the histogram."
},
{
"code": null,
"e": 12182,
"s": 12141,
"text": "We can do a very simple one, doing this:"
},
{
"code": null,
"e": 12208,
"s": 12182,
"text": "pd.DataFrame(data).hist()"
},
{
"code": null,
"e": 12305,
"s": 12208,
"text": "Which will give us a plot, but far from being completely understandable at a first quick glance."
},
{
"code": null,
"e": 12438,
"s": 12305,
"text": "If someone asks us, “what percentage of the rabbits’ weight between 0 and 1 kilograms?” is difficult to answer looking at this plot."
},
{
"code": null,
"e": 12598,
"s": 12438,
"text": "If we want to make a more meaningful histogram plot, let’s make the one from before (the one from the spoiler alert) using only tools that we went over before:"
},
{
"code": null,
"e": 14019,
"s": 12598,
"text": "# plot the bars from the histogramx = np.array(df['labels'])y = np.array(df['values_norm'])plt.bar(x,y)# plot the cumulative curvex = list(range(len(x)))y = list(df['perc_cumulative'])plt.plot(x,y,color='orange',marker='o')# change the y-axis limitsplt.axis(ymin=0, ymax=1.1)# plot the values from the cumulative curve on top of ity_labels = list(df['perc_cum_label'])for i,j in zip(x,y): inplot = plt.annotate(str(y_labels[i]) ,xy=(i-0.1,j+0.05) ,fontsize=12 ,color='black')# draw vertical lines in 50, 75 and 90 percentile.plt.axvline(np.percentile(data,50)-1, color='maroon',linestyle='--',linewidth=1)plt.axvline(np.percentile(data,75)-1, color='maroon',linestyle='--',linewidth=1)plt.axvline(np.percentile(data,90)-1, color='maroon',linestyle='--',linewidth=1)# indicate which percentile is each linep_values = [np.percentile(data,50),np.percentile(data,75),np.percentile(data,90)]p_numbers = ['p50', 'p75', 'p90']for i, j in zip(p_values, p_numbers): inplot = plt.annotate(j ,xy=(i-1 + 0.05, 1.05) ,fontsize=12 ,color='maroon')# some final tweaking in title, axis and labelsplt.title('Histogram and cumulative curve',fontsize=15)plt.ylabel('Bins', size=15, labelpad=18)plt.xlabel('Frequency', size=15, labelpad=18)plt.tick_params(axis='both', labelsize = 14)"
},
{
"code": null,
"e": 14039,
"s": 14019,
"text": "Giving as a result:"
},
{
"code": null,
"e": 14157,
"s": 14039,
"text": "We can do the same plot, but having the bars at the same level as the curve. We achieve this by generating twin axes."
},
{
"code": null,
"e": 14428,
"s": 14157,
"text": "As you will see, the code is very similar, with the particularity that at the beginning we create the twin axes. Then, we generate both plots (bars and curve), but instead of starting both of them with plt., one of them will start with host. And the other one, with par."
},
{
"code": null,
"e": 16038,
"s": 14428,
"text": "# we import this package for the twin axesfrom mpl_toolkits.axes_grid1 import host_subplot# we generate the twin axeshost = host_subplot(111)par = host.twinx()# we plot the bars (use host. instead of plt.)x = np.array(df['labels'])y = np.array(df['values_norm'])p1 = host.bar(x, y, color='steelblue')# we plot the curve (use par. instead of plt.)x = list(range(len(x)))y = list(df['perc_cumulative'])p2 = par.plot(x, y, color='darkorange',marker='o')# we plot the values from the cumulative curve on top of ity_labels = list(df['perc_cum_label'])for i,j in zip(x,y): inplot = par.annotate(str(y_labels[i]) ,xy=(i-0.1,j+0.05) ,fontsize=12 ,color='black')# some final tweaking in title, axis and labelsplt.title('Histogram and cumulative curve',fontsize=15)par.axis(ymin=0, ymax=1.1)host.set_xlabel(\"Bins\", size=13, labelpad = 16)host.set_ylabel(\"Frequency\", size=13, labelpad = 16)# draw vertical lines in 50, 75 and 90 percentile.plt.axvline(np.percentile(data,50)-1, color='maroon',linestyle='--',linewidth=1.5)plt.axvline(np.percentile(data,75)-1, color='maroon',linestyle='--',linewidth=1.5)plt.axvline(np.percentile(data,90)-1, color='maroon',linestyle='--',linewidth=1.5)# indicate which percentile is each linep_values = p_values = [np.percentile(data,50),np.percentile(data,75),np.percentile(data,90)]p_numbers = ['p50', 'p75', 'p90']for i, j in zip(p_values, p_numbers): inplot = plt.annotate(j ,xy=(i-1 + 0.05, 0.39) ,fontsize=10 ,color='maroon')"
},
{
"code": null,
"e": 16077,
"s": 16038,
"text": "Getting, in the end, the desired plot:"
},
{
"code": null,
"e": 16243,
"s": 16077,
"text": "And we reached the end! I hope you have enjoyed the article and that you have learned a lot (or at least a few) new things to improve your plotting skills in Python."
},
{
"code": null,
"e": 16311,
"s": 16243,
"text": "Follow me if you want to see more articles like this in the future."
},
{
"code": null,
"e": 16360,
"s": 16311,
"text": "You can also look at my previous articles, like:"
},
{
"code": null,
"e": 16461,
"s": 16360,
"text": "Mastering Dates and Timestamps in Pandas (and Python in general) (same style as the current article)"
},
{
"code": null,
"e": 16477,
"s": 16461,
"text": "Other articles:"
},
{
"code": null,
"e": 16544,
"s": 16477,
"text": "Analyzing User behavior and UX performance with Feature importance"
},
{
"code": null,
"e": 16696,
"s": 16544,
"text": "And as promised at the beginning of the First Section, a link to Matplotlib documentation where you can see everything about markers, line styles, etc:"
},
{
"code": null,
"e": 16721,
"s": 16696,
"text": "Matplotlib Documentation"
}
] |
Line Chart Animation with Plotly on Jupyter | by Shinichi Okada | Towards Data Science
|
Table of ContentsIntroduction1. Data preparation2. All countries line chart3. Adding LOG and LINEAR buttons4. Changing hovermode5. Line chart animation6. Scatter and bar chart animationsConclusion
In this article, I will try to reproduce one of Our World in Data charts using Plotly animation on Jupyter.
ourworldindata.org is an excellent website and I really like their visualizations.
The above chart can animate the graph, highlight lines, select different cases on the right side, select LINEAR and LOG buttons, and select countries you want to display.
The project is an open-source project and you can explore their GitHub repo.
It is a JavaScript-based app, using MySQL as a database and React, Mobx, TypeScript, Node, Express, D3, and other JavaScripts.
Plotly supports creating animations, buttons, and selectable lines.
However, current Plotly animations have some limitations, and smooth inter-frame transitions are only possible for a scatter and bar chart. It does not support a checkbox, even though PlotlyDash which is a Python framework for building web applications supports Checklist.
This article assumes you are already familiar with the basic operation in JupyterLab/Jupyter Notebook.
Plotly installation
plotly.py may be installed using pip.
$ pip install plotly==4.8.1
or conda.
$ conda install -c plotly plotly=4.8.1
Using pip:
$ pip install jupyterlab "ipywidgets>=7.5"
or Conda:
$ conda install jupyterlab "ipywidgets=7.5"
Then run the following (you need node installed):
# JupyterLab renderer support $ jupyter labextension install jupyterlab-plotly@4.8.1 # OPTIONAL: Jupyter widgets extension $ jupyter labextension install @jupyter-widgets/jupyterlab-manager plotlywidget@4.8.1
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
You can download the dataset from Our World in Data or this repo.
import pandas as pdimport plotly.express as pxdf = pd.read_csv('https://raw.githubusercontent.com/shinokada/covid-19-stats/master/data/daily-new-confirmed-cases-of-covid-19-tests-per-case.csv')display(df.head())display(df.shape)
import pandas as pdimport plotly.express as pxdf = pd.read_csv('https://raw.githubusercontent.com/shinokada/covid-19-stats/master/data/daily-new-confirmed-cases-of-covid-19-tests-per-case.csv') excludes = ["World", "Africa", "North America", "South America", "Asia", "Europe", "European Union", "High income", "Low income", "Lower middle income", "Oceania", "Upper middle income", "World excl. China", "World excl. China and South Korea", "International", "World excl. China, South Korea, Japan and Singapore","Asia excl. China"] df=df[~df['Entity'].isin(excludes)]df.columns = ['Country','Code','Date','Confirmed','Days since confirmed']df['Date']= pd.to_datetime(df['Date']).dt.strftime('%Y-%m-%d')df_all=df[(df['Date']>'2020-03-01') & (df['Date'] <'2020-06-14')]
Import necessary libraries, Pandas, and Plotly.express. Read a comma-separated values(csv) file into DataFrame.
excludes is a list of names in the Entity column that we want to exclude.
isin method finds excludes values in Entity column and we use ~ to exclude these rows.
We rename the column names to Country, Code, Date, Confirmed, Days since confirmed.
We change the data type of Date column from object to datetime.We also format it to Year-Month-Day.
We select rows from 2020-03-01 to 2020-06-14 in theDate column.
display(df.head())display(df.shape)
Let’s create a line chart using df_all. We set Date for the x-axis, Confirmed for the y-axis and use Country for line colors.
fig = px.line(df_all, x="Date", y="Confirmed", color="Country")fig.show()
The chart has the ability to reveal more information about a data point by moving a mouse cursor over the point. We can hide or show lines by clicking country names on the right side.
We are going to add two buttons that change the y-axis scale.
fig = px.line(df_all, x="Date", y="Confirmed", color="Country") fig.update_layout( updatemenus=[ dict( type = "buttons", direction = "left", buttons=list([ dict( args=[{"yaxis.type": "linear"}], label="LINEAR", method="relayout" ), dict( args=[{"yaxis.type": "log"}], label="LOG", method="relayout" ) ]), ), ])fig.show()
Using theupdate_layout method to update the properties of the figure’s layout. Adding two buttons, LINEAR and LOG and changing the yaxis.type to linear and log accordingly.
Plotly has three different hovermode. The default setting is hovermode='closest', as we can see in the previous image, a single hover label appears for the point directly underneath the cursor.
For this chart, we are going to use a unified hovermode='x unified'. It shows a single hover label with all the data information. For clarity, we select four countries.
import numpy as npimport pandas as pdimport plotly.graph_objects as go #plotly 4.0.0rc1 df = pd.read_csv('https://raw.githubusercontent.com/shinokada/covid-19-stats/master/data/daily-new-confirmed-cases-of-covid-19-tests-per-case.csv')df.columns = ['Country','Code','Date','Confirmed','Days since confirmed']df['Date']= pd.to_datetime(df['Date']).dt.strftime('%Y-%m-%d')df=df[(df['Date']>'2020-03-15') & (df['Date'] <'2020-06-14')] includes=['United States','Russia', 'India','Brazil']df_selected=df[df['Country'].isin(includes)] fig = px.line(df_selected, x="Date", y="Confirmed", color="Country") fig.update_layout( hovermode='x unified', updatemenus=[ dict( type = "buttons", direction = "left", buttons=list([ dict( args=[{"yaxis.type": "linear"}], label="LINEAR", method="relayout" ), dict( args=[{"yaxis.type": "log"}], label="LOG", method="relayout" ) ]), ), ])fig.show()
Plotly animations have some limitations and the line chart is not supported.
Line chart animation can be done but it is not as neat as other animations such as those for bar and scatter charts.
import numpy as npimport pandas as pdimport plotly.graph_objects as godf = pd.read_csv('https://raw.githubusercontent.com/shinokada/covid-19-stats/master/data/daily-new-confirmed-cases-of-covid-19-tests-per-case.csv')df.columns = ['Country','Code','Date','Confirmed','Days since confirmed']df['Date']= pd.to_datetime(df['Date']).dt.strftime('%Y-%m-%d')df=df[(df['Date']>'2020-03-15') & (df['Date'] <'2020-06-14')]usa=df[df['Country'].isin(['United States'])]brazil=df[df['Country'].isin(['Brazil'])]india=df[df['Country'].isin(['India'])]russia=df[df['Country'].isin(['Russia'])]trace1 = go.Scatter(x=usa['Date'][:2], y=usa['Confirmed'][:2], mode='lines', line=dict(width=1.5))trace2 = go.Scatter(x = brazil['Date'][:2], y = brazil['Confirmed'][:2], mode='lines', line=dict(width=1.5))trace3 = go.Scatter(x = india['Date'][:2], y = india['Confirmed'][:2], mode='lines', line=dict(width=1.5))trace4 = go.Scatter(x = russia['Date'][:2], y = russia['Confirmed'][:2], mode='lines', line=dict(width=1.5))frames = [dict(data= [dict(type='scatter', x=usa['Date'][:k+1], y=usa['Confirmed'][:k+1]), dict(type='scatter', x=brazil['Date'][:k+1], y=brazil['Confirmed'][:k+1]), dict(type='scatter', x=india['Date'][:k+1], y=india['Confirmed'][:k+1]), dict(type='scatter', x=russia['Date'][:k+1], y=russia['Confirmed'][:k+1]), ], traces= [0, 1, 2, 3], )for k in range(1, len(usa)-1)]layout = go.Layout(width=700, height=600, showlegend=False, hovermode='x unified', updatemenus=[ dict( type='buttons', showactive=False, y=1.05, x=1.15, xanchor='right', yanchor='top', pad=dict(t=0, r=10), buttons=[dict(label='Play', method='animate', args=[None, dict(frame=dict(duration=3, redraw=False), transition=dict(duration=0), fromcurrent=True, mode='immediate')] )] ), dict( type = "buttons", direction = "left", buttons=list([ dict( args=[{"yaxis.type": "linear"}], label="LINEAR", method="relayout" ), dict( args=[{"yaxis.type": "log"}], label="LOG", method="relayout" ) ]), ), ] )layout.update(xaxis =dict(range=['2020-03-16', '2020-06-13'], autorange=False), yaxis =dict(range=[0, 35000], autorange=False));fig = go.Figure(data=[trace1, trace2, trace3, trace4], frames=frames, layout=layout)fig.show()
We can add more countries if we want.
We create four separate DataFrame. You can increase or decrease the number of countries.
We create four traces with own x, y, mode, and line values. If you change the number of countries, you need to adjust here as well.
We create frames with data list values. traces=[0,1,2,3] is used to iterate frame[k]['data'][0], frame[k]['data'][1], etc. If you change the number of countries, again, you need to adjust the code here. e.g. traces=[0,1,2,3,4,5].
We set width, height, hovermode, and updatemenus. We set two kinds of buttons, one for play and others for LINEAR and LOG.
update updates the properties of the figure with a dict with keyword arguments.
We create a new Figure instance and add all the traces we created in line 15–33. If you change the number of countries, you need to update this line.
Plotly supports the scatter and bar chart animations.
You can find the code here.
You can drop the animation buttons by adding fig["layout"].pop("updatemenus"), and use it as a slider.
Code
In a bar chart animation, we can hover to see more detailed information and we can hide/show items by clicking on the right menu.
Code
It was not exactly the same as Our World in Data Website, but we learned how to create line charts, line chart animations, add unified hover mode, and add buttons.
Currently, Plotly requires more code to make a line chart animation. Also, it would be great if the scatter chart could draw trace lines and a speed control parameter for the animation.
Get full access to every story on Medium by becoming a member.
|
[
{
"code": null,
"e": 369,
"s": 172,
"text": "Table of ContentsIntroduction1. Data preparation2. All countries line chart3. Adding LOG and LINEAR buttons4. Changing hovermode5. Line chart animation6. Scatter and bar chart animationsConclusion"
},
{
"code": null,
"e": 477,
"s": 369,
"text": "In this article, I will try to reproduce one of Our World in Data charts using Plotly animation on Jupyter."
},
{
"code": null,
"e": 560,
"s": 477,
"text": "ourworldindata.org is an excellent website and I really like their visualizations."
},
{
"code": null,
"e": 731,
"s": 560,
"text": "The above chart can animate the graph, highlight lines, select different cases on the right side, select LINEAR and LOG buttons, and select countries you want to display."
},
{
"code": null,
"e": 808,
"s": 731,
"text": "The project is an open-source project and you can explore their GitHub repo."
},
{
"code": null,
"e": 935,
"s": 808,
"text": "It is a JavaScript-based app, using MySQL as a database and React, Mobx, TypeScript, Node, Express, D3, and other JavaScripts."
},
{
"code": null,
"e": 1003,
"s": 935,
"text": "Plotly supports creating animations, buttons, and selectable lines."
},
{
"code": null,
"e": 1276,
"s": 1003,
"text": "However, current Plotly animations have some limitations, and smooth inter-frame transitions are only possible for a scatter and bar chart. It does not support a checkbox, even though PlotlyDash which is a Python framework for building web applications supports Checklist."
},
{
"code": null,
"e": 1379,
"s": 1276,
"text": "This article assumes you are already familiar with the basic operation in JupyterLab/Jupyter Notebook."
},
{
"code": null,
"e": 1399,
"s": 1379,
"text": "Plotly installation"
},
{
"code": null,
"e": 1437,
"s": 1399,
"text": "plotly.py may be installed using pip."
},
{
"code": null,
"e": 1465,
"s": 1437,
"text": "$ pip install plotly==4.8.1"
},
{
"code": null,
"e": 1475,
"s": 1465,
"text": "or conda."
},
{
"code": null,
"e": 1514,
"s": 1475,
"text": "$ conda install -c plotly plotly=4.8.1"
},
{
"code": null,
"e": 1525,
"s": 1514,
"text": "Using pip:"
},
{
"code": null,
"e": 1568,
"s": 1525,
"text": "$ pip install jupyterlab \"ipywidgets>=7.5\""
},
{
"code": null,
"e": 1578,
"s": 1568,
"text": "or Conda:"
},
{
"code": null,
"e": 1622,
"s": 1578,
"text": "$ conda install jupyterlab \"ipywidgets=7.5\""
},
{
"code": null,
"e": 1672,
"s": 1622,
"text": "Then run the following (you need node installed):"
},
{
"code": null,
"e": 1882,
"s": 1672,
"text": "# JupyterLab renderer support $ jupyter labextension install jupyterlab-plotly@4.8.1 # OPTIONAL: Jupyter widgets extension $ jupyter labextension install @jupyter-widgets/jupyterlab-manager plotlywidget@4.8.1"
},
{
"code": null,
"e": 1905,
"s": 1882,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1928,
"s": 1905,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1951,
"s": 1928,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2017,
"s": 1951,
"text": "You can download the dataset from Our World in Data or this repo."
},
{
"code": null,
"e": 2246,
"s": 2017,
"text": "import pandas as pdimport plotly.express as pxdf = pd.read_csv('https://raw.githubusercontent.com/shinokada/covid-19-stats/master/data/daily-new-confirmed-cases-of-covid-19-tests-per-case.csv')display(df.head())display(df.shape)"
},
{
"code": null,
"e": 3023,
"s": 2246,
"text": "import pandas as pdimport plotly.express as pxdf = pd.read_csv('https://raw.githubusercontent.com/shinokada/covid-19-stats/master/data/daily-new-confirmed-cases-of-covid-19-tests-per-case.csv') excludes = [\"World\", \"Africa\", \"North America\", \"South America\", \"Asia\", \"Europe\", \"European Union\", \"High income\", \"Low income\", \"Lower middle income\", \"Oceania\", \"Upper middle income\", \"World excl. China\", \"World excl. China and South Korea\", \"International\", \"World excl. China, South Korea, Japan and Singapore\",\"Asia excl. China\"] df=df[~df['Entity'].isin(excludes)]df.columns = ['Country','Code','Date','Confirmed','Days since confirmed']df['Date']= pd.to_datetime(df['Date']).dt.strftime('%Y-%m-%d')df_all=df[(df['Date']>'2020-03-01') & (df['Date'] <'2020-06-14')]"
},
{
"code": null,
"e": 3135,
"s": 3023,
"text": "Import necessary libraries, Pandas, and Plotly.express. Read a comma-separated values(csv) file into DataFrame."
},
{
"code": null,
"e": 3209,
"s": 3135,
"text": "excludes is a list of names in the Entity column that we want to exclude."
},
{
"code": null,
"e": 3296,
"s": 3209,
"text": "isin method finds excludes values in Entity column and we use ~ to exclude these rows."
},
{
"code": null,
"e": 3380,
"s": 3296,
"text": "We rename the column names to Country, Code, Date, Confirmed, Days since confirmed."
},
{
"code": null,
"e": 3480,
"s": 3380,
"text": "We change the data type of Date column from object to datetime.We also format it to Year-Month-Day."
},
{
"code": null,
"e": 3544,
"s": 3480,
"text": "We select rows from 2020-03-01 to 2020-06-14 in theDate column."
},
{
"code": null,
"e": 3580,
"s": 3544,
"text": "display(df.head())display(df.shape)"
},
{
"code": null,
"e": 3706,
"s": 3580,
"text": "Let’s create a line chart using df_all. We set Date for the x-axis, Confirmed for the y-axis and use Country for line colors."
},
{
"code": null,
"e": 3780,
"s": 3706,
"text": "fig = px.line(df_all, x=\"Date\", y=\"Confirmed\", color=\"Country\")fig.show()"
},
{
"code": null,
"e": 3964,
"s": 3780,
"text": "The chart has the ability to reveal more information about a data point by moving a mouse cursor over the point. We can hide or show lines by clicking country names on the right side."
},
{
"code": null,
"e": 4026,
"s": 3964,
"text": "We are going to add two buttons that change the y-axis scale."
},
{
"code": null,
"e": 4585,
"s": 4026,
"text": "fig = px.line(df_all, x=\"Date\", y=\"Confirmed\", color=\"Country\") fig.update_layout( updatemenus=[ dict( type = \"buttons\", direction = \"left\", buttons=list([ dict( args=[{\"yaxis.type\": \"linear\"}], label=\"LINEAR\", method=\"relayout\" ), dict( args=[{\"yaxis.type\": \"log\"}], label=\"LOG\", method=\"relayout\" ) ]), ), ])fig.show()"
},
{
"code": null,
"e": 4758,
"s": 4585,
"text": "Using theupdate_layout method to update the properties of the figure’s layout. Adding two buttons, LINEAR and LOG and changing the yaxis.type to linear and log accordingly."
},
{
"code": null,
"e": 4952,
"s": 4758,
"text": "Plotly has three different hovermode. The default setting is hovermode='closest', as we can see in the previous image, a single hover label appears for the point directly underneath the cursor."
},
{
"code": null,
"e": 5121,
"s": 4952,
"text": "For this chart, we are going to use a unified hovermode='x unified'. It shows a single hover label with all the data information. For clarity, we select four countries."
},
{
"code": null,
"e": 6242,
"s": 5121,
"text": "import numpy as npimport pandas as pdimport plotly.graph_objects as go #plotly 4.0.0rc1 df = pd.read_csv('https://raw.githubusercontent.com/shinokada/covid-19-stats/master/data/daily-new-confirmed-cases-of-covid-19-tests-per-case.csv')df.columns = ['Country','Code','Date','Confirmed','Days since confirmed']df['Date']= pd.to_datetime(df['Date']).dt.strftime('%Y-%m-%d')df=df[(df['Date']>'2020-03-15') & (df['Date'] <'2020-06-14')] includes=['United States','Russia', 'India','Brazil']df_selected=df[df['Country'].isin(includes)] fig = px.line(df_selected, x=\"Date\", y=\"Confirmed\", color=\"Country\") fig.update_layout( hovermode='x unified', updatemenus=[ dict( type = \"buttons\", direction = \"left\", buttons=list([ dict( args=[{\"yaxis.type\": \"linear\"}], label=\"LINEAR\", method=\"relayout\" ), dict( args=[{\"yaxis.type\": \"log\"}], label=\"LOG\", method=\"relayout\" ) ]), ), ])fig.show()"
},
{
"code": null,
"e": 6319,
"s": 6242,
"text": "Plotly animations have some limitations and the line chart is not supported."
},
{
"code": null,
"e": 6436,
"s": 6319,
"text": "Line chart animation can be done but it is not as neat as other animations such as those for bar and scatter charts."
},
{
"code": null,
"e": 10341,
"s": 6436,
"text": "import numpy as npimport pandas as pdimport plotly.graph_objects as godf = pd.read_csv('https://raw.githubusercontent.com/shinokada/covid-19-stats/master/data/daily-new-confirmed-cases-of-covid-19-tests-per-case.csv')df.columns = ['Country','Code','Date','Confirmed','Days since confirmed']df['Date']= pd.to_datetime(df['Date']).dt.strftime('%Y-%m-%d')df=df[(df['Date']>'2020-03-15') & (df['Date'] <'2020-06-14')]usa=df[df['Country'].isin(['United States'])]brazil=df[df['Country'].isin(['Brazil'])]india=df[df['Country'].isin(['India'])]russia=df[df['Country'].isin(['Russia'])]trace1 = go.Scatter(x=usa['Date'][:2], y=usa['Confirmed'][:2], mode='lines', line=dict(width=1.5))trace2 = go.Scatter(x = brazil['Date'][:2], y = brazil['Confirmed'][:2], mode='lines', line=dict(width=1.5))trace3 = go.Scatter(x = india['Date'][:2], y = india['Confirmed'][:2], mode='lines', line=dict(width=1.5))trace4 = go.Scatter(x = russia['Date'][:2], y = russia['Confirmed'][:2], mode='lines', line=dict(width=1.5))frames = [dict(data= [dict(type='scatter', x=usa['Date'][:k+1], y=usa['Confirmed'][:k+1]), dict(type='scatter', x=brazil['Date'][:k+1], y=brazil['Confirmed'][:k+1]), dict(type='scatter', x=india['Date'][:k+1], y=india['Confirmed'][:k+1]), dict(type='scatter', x=russia['Date'][:k+1], y=russia['Confirmed'][:k+1]), ], traces= [0, 1, 2, 3], )for k in range(1, len(usa)-1)]layout = go.Layout(width=700, height=600, showlegend=False, hovermode='x unified', updatemenus=[ dict( type='buttons', showactive=False, y=1.05, x=1.15, xanchor='right', yanchor='top', pad=dict(t=0, r=10), buttons=[dict(label='Play', method='animate', args=[None, dict(frame=dict(duration=3, redraw=False), transition=dict(duration=0), fromcurrent=True, mode='immediate')] )] ), dict( type = \"buttons\", direction = \"left\", buttons=list([ dict( args=[{\"yaxis.type\": \"linear\"}], label=\"LINEAR\", method=\"relayout\" ), dict( args=[{\"yaxis.type\": \"log\"}], label=\"LOG\", method=\"relayout\" ) ]), ), ] )layout.update(xaxis =dict(range=['2020-03-16', '2020-06-13'], autorange=False), yaxis =dict(range=[0, 35000], autorange=False));fig = go.Figure(data=[trace1, trace2, trace3, trace4], frames=frames, layout=layout)fig.show()"
},
{
"code": null,
"e": 10379,
"s": 10341,
"text": "We can add more countries if we want."
},
{
"code": null,
"e": 10468,
"s": 10379,
"text": "We create four separate DataFrame. You can increase or decrease the number of countries."
},
{
"code": null,
"e": 10600,
"s": 10468,
"text": "We create four traces with own x, y, mode, and line values. If you change the number of countries, you need to adjust here as well."
},
{
"code": null,
"e": 10830,
"s": 10600,
"text": "We create frames with data list values. traces=[0,1,2,3] is used to iterate frame[k]['data'][0], frame[k]['data'][1], etc. If you change the number of countries, again, you need to adjust the code here. e.g. traces=[0,1,2,3,4,5]."
},
{
"code": null,
"e": 10953,
"s": 10830,
"text": "We set width, height, hovermode, and updatemenus. We set two kinds of buttons, one for play and others for LINEAR and LOG."
},
{
"code": null,
"e": 11033,
"s": 10953,
"text": "update updates the properties of the figure with a dict with keyword arguments."
},
{
"code": null,
"e": 11183,
"s": 11033,
"text": "We create a new Figure instance and add all the traces we created in line 15–33. If you change the number of countries, you need to update this line."
},
{
"code": null,
"e": 11237,
"s": 11183,
"text": "Plotly supports the scatter and bar chart animations."
},
{
"code": null,
"e": 11265,
"s": 11237,
"text": "You can find the code here."
},
{
"code": null,
"e": 11368,
"s": 11265,
"text": "You can drop the animation buttons by adding fig[\"layout\"].pop(\"updatemenus\"), and use it as a slider."
},
{
"code": null,
"e": 11373,
"s": 11368,
"text": "Code"
},
{
"code": null,
"e": 11503,
"s": 11373,
"text": "In a bar chart animation, we can hover to see more detailed information and we can hide/show items by clicking on the right menu."
},
{
"code": null,
"e": 11508,
"s": 11503,
"text": "Code"
},
{
"code": null,
"e": 11672,
"s": 11508,
"text": "It was not exactly the same as Our World in Data Website, but we learned how to create line charts, line chart animations, add unified hover mode, and add buttons."
},
{
"code": null,
"e": 11858,
"s": 11672,
"text": "Currently, Plotly requires more code to make a line chart animation. Also, it would be great if the scatter chart could draw trace lines and a speed control parameter for the animation."
}
] |
Can we override the main method in java?
|
Overriding is one of the mechanisms to achieve polymorphism. This is the case when we have two classes where one inherits the properties of another using the extends keyword and, these two classes have the same method including parameters and return type (say, sample()).
Since it is an inheritance. If we instantiate the subclass a copy of superclass’s members is created in the subclass object and, thus both methods are available to the subclass (object).
When we invoke this method (sample) JVM calls the respective method based on the object used to call the method.
Live Demo
class Super{
public static void sample(){
System.out.println("Method of the superclass");
}
}
public class OverridingExample extends Super {
public static void sample(){
System.out.println("Method of the subclass");
}
public static void main(String args[]){
Super obj1 = (Super) new OverridingExample();
OverridingExample obj2 = new OverridingExample();
obj1.sample();
obj2.sample();
}
}
Method of the superclass
Method of the subclass
When superclass and subclass contain the same method including parameters and if they are static. The method in the superclass will be hidden by the one that is in the subclass.
This mechanism is known as method hiding in short, though super and subclasses have methods with the same signature if they are static, it is not considered as overriding.
You cannot override static methods and since the public static void main() method is static we cannot override it.
Live Demo
class Super{
public static void main(String args[]) {
System.out.println("This is the main method of the superclass");
}
}
class Sub extends Super{
public static void main(String args[]) {
System.out.println("This is the main method of the subclass");
}
}
public class MainOverridingExample{
public static void main(String args[]) {
MainOverridingExample obj = new MainOverridingExample();
Super.main(args);
Sub.main(args);
}
}
This is the main method of the superclass
This is the main method of the subclass
|
[
{
"code": null,
"e": 1334,
"s": 1062,
"text": "Overriding is one of the mechanisms to achieve polymorphism. This is the case when we have two classes where one inherits the properties of another using the extends keyword and, these two classes have the same method including parameters and return type (say, sample())."
},
{
"code": null,
"e": 1521,
"s": 1334,
"text": "Since it is an inheritance. If we instantiate the subclass a copy of superclass’s members is created in the subclass object and, thus both methods are available to the subclass (object)."
},
{
"code": null,
"e": 1634,
"s": 1521,
"text": "When we invoke this method (sample) JVM calls the respective method based on the object used to call the method."
},
{
"code": null,
"e": 1645,
"s": 1634,
"text": " Live Demo"
},
{
"code": null,
"e": 2087,
"s": 1645,
"text": "class Super{\n public static void sample(){\n System.out.println(\"Method of the superclass\");\n }\n}\npublic class OverridingExample extends Super {\n public static void sample(){\n System.out.println(\"Method of the subclass\");\n }\n public static void main(String args[]){\n Super obj1 = (Super) new OverridingExample();\n OverridingExample obj2 = new OverridingExample();\n obj1.sample();\n obj2.sample();\n }\n}"
},
{
"code": null,
"e": 2135,
"s": 2087,
"text": "Method of the superclass\nMethod of the subclass"
},
{
"code": null,
"e": 2313,
"s": 2135,
"text": "When superclass and subclass contain the same method including parameters and if they are static. The method in the superclass will be hidden by the one that is in the subclass."
},
{
"code": null,
"e": 2485,
"s": 2313,
"text": "This mechanism is known as method hiding in short, though super and subclasses have methods with the same signature if they are static, it is not considered as overriding."
},
{
"code": null,
"e": 2600,
"s": 2485,
"text": "You cannot override static methods and since the public static void main() method is static we cannot override it."
},
{
"code": null,
"e": 2611,
"s": 2600,
"text": " Live Demo"
},
{
"code": null,
"e": 2891,
"s": 2611,
"text": "class Super{\n public static void main(String args[]) {\n System.out.println(\"This is the main method of the superclass\");\n }\n}\nclass Sub extends Super{\n public static void main(String args[]) {\n System.out.println(\"This is the main method of the subclass\");\n }\n}"
},
{
"code": null,
"e": 3087,
"s": 2891,
"text": "public class MainOverridingExample{\n public static void main(String args[]) {\n MainOverridingExample obj = new MainOverridingExample();\n Super.main(args);\n Sub.main(args);\n }\n}"
},
{
"code": null,
"e": 3169,
"s": 3087,
"text": "This is the main method of the superclass\nThis is the main method of the subclass"
}
] |
MoviePy – Creating Text Clip - GeeksforGeeks
|
18 Aug, 2020
In this article we will see how we can create a text clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Video is formed by the frames, combination of frames creates a video each frame is an individual image. Text clip is basically a clip here we can say it as image containing text.
In order to do this we will use TextClip method
Syntax : TextClip(text)
Argument : It takes string as necessary argument and color size other styling effect are optional argument
Return : It returns TextClip object
Below is the implementation
# importing editor from movie pyfrom moviepy.editor import * # texttext = "GeeksforGeeks" # creating a text clip# having font arial-bold# with font size = 70# and color = greenclip = TextClip(text, font ="Arial-Bold", fontsize = 70, color ="green") # showing clip clip.ipython_display()
Output :
Another example
# importing editor from movie pyfrom moviepy.editor import * # texttext = "Hello" # creating a text clip# having font arial-bold# with font size = 50# and color = blackclip = TextClip(text, font ="Arial-Bold", fontsize = 50, color ="black") # showing clip clip.ipython_display()
Output :
Python-MoviePy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
Python OOPs Concepts
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Stack in Python
Reading and Writing to text files in Python
Python Classes and Objects
sum() function in Python
|
[
{
"code": null,
"e": 24057,
"s": 24029,
"text": "\n18 Aug, 2020"
},
{
"code": null,
"e": 24412,
"s": 24057,
"text": "In this article we will see how we can create a text clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Video is formed by the frames, combination of frames creates a video each frame is an individual image. Text clip is basically a clip here we can say it as image containing text."
},
{
"code": null,
"e": 24460,
"s": 24412,
"text": "In order to do this we will use TextClip method"
},
{
"code": null,
"e": 24484,
"s": 24460,
"text": "Syntax : TextClip(text)"
},
{
"code": null,
"e": 24591,
"s": 24484,
"text": "Argument : It takes string as necessary argument and color size other styling effect are optional argument"
},
{
"code": null,
"e": 24627,
"s": 24591,
"text": "Return : It returns TextClip object"
},
{
"code": null,
"e": 24655,
"s": 24627,
"text": "Below is the implementation"
},
{
"code": "# importing editor from movie pyfrom moviepy.editor import * # texttext = \"GeeksforGeeks\" # creating a text clip# having font arial-bold# with font size = 70# and color = greenclip = TextClip(text, font =\"Arial-Bold\", fontsize = 70, color =\"green\") # showing clip clip.ipython_display() ",
"e": 24947,
"s": 24655,
"text": null
},
{
"code": null,
"e": 24956,
"s": 24947,
"text": "Output :"
},
{
"code": null,
"e": 24972,
"s": 24956,
"text": "Another example"
},
{
"code": "# importing editor from movie pyfrom moviepy.editor import * # texttext = \"Hello\" # creating a text clip# having font arial-bold# with font size = 50# and color = blackclip = TextClip(text, font =\"Arial-Bold\", fontsize = 50, color =\"black\") # showing clip clip.ipython_display() ",
"e": 25256,
"s": 24972,
"text": null
},
{
"code": null,
"e": 25265,
"s": 25256,
"text": "Output :"
},
{
"code": null,
"e": 25280,
"s": 25265,
"text": "Python-MoviePy"
},
{
"code": null,
"e": 25287,
"s": 25280,
"text": "Python"
},
{
"code": null,
"e": 25385,
"s": 25287,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25394,
"s": 25385,
"text": "Comments"
},
{
"code": null,
"e": 25407,
"s": 25394,
"text": "Old Comments"
},
{
"code": null,
"e": 25425,
"s": 25407,
"text": "Python Dictionary"
},
{
"code": null,
"e": 25447,
"s": 25425,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 25468,
"s": 25447,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 25503,
"s": 25468,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 25535,
"s": 25503,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25577,
"s": 25535,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 25593,
"s": 25577,
"text": "Stack in Python"
},
{
"code": null,
"e": 25637,
"s": 25593,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 25664,
"s": 25637,
"text": "Python Classes and Objects"
}
] |
C# - Relational Operators
|
Following table shows all the relational operators supported by C#. Assume variable A holds 10 and variable B holds 20, then −
The following example demonstrates all the relational operators available in C# −
using System;
class Program {
static void Main(string[] args) {
int a = 21;
int b = 10;
if (a == b) {
Console.WriteLine("Line 1 - a is equal to b");
} else {
Console.WriteLine("Line 1 - a is not equal to b");
}
if (a < b) {
Console.WriteLine("Line 2 - a is less than b");
} else {
Console.WriteLine("Line 2 - a is not less than b");
}
if (a > b) {
Console.WriteLine("Line 3 - a is greater than b");
} else {
Console.WriteLine("Line 3 - a is not greater than b");
}
/* Lets change value of a and b */
a = 5;
b = 20;
if (a <= b) {
Console.WriteLine("Line 4 - a is either less than or equal to b");
}
if (b >= a) {
Console.WriteLine("Line 5-b is either greater than or equal to b");
}
}
}
When the above code is compiled and executed, it produces the following result −
Line 1 - a is not equal to b
Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either less than or equal to b
Line 5 - b is either greater than or equal to b
119 Lectures
23.5 hours
Raja Biswas
37 Lectures
13 hours
Trevoir Williams
16 Lectures
1 hours
Peter Jepson
159 Lectures
21.5 hours
Ebenezer Ogbu
193 Lectures
17 hours
Arnold Higuit
24 Lectures
2.5 hours
Eric Frick
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2397,
"s": 2270,
"text": "Following table shows all the relational operators supported by C#. Assume variable A holds 10 and variable B holds 20, then −"
},
{
"code": null,
"e": 2479,
"s": 2397,
"text": "The following example demonstrates all the relational operators available in C# −"
},
{
"code": null,
"e": 3396,
"s": 2479,
"text": "using System;\n\nclass Program {\n static void Main(string[] args) {\n int a = 21;\n int b = 10;\n \n if (a == b) {\n Console.WriteLine(\"Line 1 - a is equal to b\");\n } else {\n Console.WriteLine(\"Line 1 - a is not equal to b\");\n }\n \n if (a < b) {\n Console.WriteLine(\"Line 2 - a is less than b\");\n } else {\n Console.WriteLine(\"Line 2 - a is not less than b\");\n }\n \n if (a > b) {\n Console.WriteLine(\"Line 3 - a is greater than b\");\n } else {\n Console.WriteLine(\"Line 3 - a is not greater than b\");\n }\n \n /* Lets change value of a and b */\n a = 5;\n b = 20;\n \n if (a <= b) { \n Console.WriteLine(\"Line 4 - a is either less than or equal to b\");\n }\n \n if (b >= a) {\n Console.WriteLine(\"Line 5-b is either greater than or equal to b\");\n }\n }\n}"
},
{
"code": null,
"e": 3477,
"s": 3396,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3659,
"s": 3477,
"text": "Line 1 - a is not equal to b\nLine 2 - a is not less than b\nLine 3 - a is greater than b\nLine 4 - a is either less than or equal to b\nLine 5 - b is either greater than or equal to b\n"
},
{
"code": null,
"e": 3696,
"s": 3659,
"text": "\n 119 Lectures \n 23.5 hours \n"
},
{
"code": null,
"e": 3709,
"s": 3696,
"text": " Raja Biswas"
},
{
"code": null,
"e": 3743,
"s": 3709,
"text": "\n 37 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3761,
"s": 3743,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 3794,
"s": 3761,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3808,
"s": 3794,
"text": " Peter Jepson"
},
{
"code": null,
"e": 3845,
"s": 3808,
"text": "\n 159 Lectures \n 21.5 hours \n"
},
{
"code": null,
"e": 3860,
"s": 3845,
"text": " Ebenezer Ogbu"
},
{
"code": null,
"e": 3895,
"s": 3860,
"text": "\n 193 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 3910,
"s": 3895,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 3945,
"s": 3910,
"text": "\n 24 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3957,
"s": 3945,
"text": " Eric Frick"
},
{
"code": null,
"e": 3964,
"s": 3957,
"text": " Print"
},
{
"code": null,
"e": 3975,
"s": 3964,
"text": " Add Notes"
}
] |
Ruby | Array collect() operation - GeeksforGeeks
|
08 Jan, 2020
Array#collect() : collect() is an Array class method which invokes the argument block once for each element of the array. A new array is returned which has the value returned by the block.
Syntax: Array.collect()
Parameter: Arrays in which we want elements to be invoked
Return: array with all the envoked elements
Code #1 : Example for collect() method
# Ruby code for collect() method # declaring arraya = [1, 2, 3, 4] # invoking block for each elementputs "collect a : #{a.collect {|x| x + 1 }}\n\n" puts "collect a : #{a.collect {|x| x - 5*7 }}\n\n"
Output :
collect a : [2, 3, 4, 5]
collect a : [-34, -33, -32, -31]
Code #2 : Example for collect() method
# Ruby code for collect() method # declaring arraya = ["cat", "rat", "geeks"] # invoking block for each elementputs "collect a : #{a.collect {|x| x + "!" }}\n\n" puts "collect a : #{a.collect {|x| x + "_at" }}\n\n"
Output :
collect a : ["cat!", "rat!", "geeks!"]
collect a : ["cat_at", "rat_at", "geeks_at"]
Ruby Array-class
Ruby Collections
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Ruby | Array count() operation
Include v/s Extend in Ruby
Ruby | Enumerator each_with_index function
Ruby | Array select() function
Global Variable in Ruby
Ruby | Hash delete() function
Ruby | String gsub! Method
Ruby | String capitalize() Method
How to Make a Custom Array of Hashes in Ruby?
Ruby | Case Statement
|
[
{
"code": null,
"e": 23359,
"s": 23331,
"text": "\n08 Jan, 2020"
},
{
"code": null,
"e": 23548,
"s": 23359,
"text": "Array#collect() : collect() is an Array class method which invokes the argument block once for each element of the array. A new array is returned which has the value returned by the block."
},
{
"code": null,
"e": 23680,
"s": 23548,
"text": "Syntax: Array.collect()\n\nParameter: Arrays in which we want elements to be invoked\n\nReturn: array with all the envoked elements\n"
},
{
"code": null,
"e": 23719,
"s": 23680,
"text": "Code #1 : Example for collect() method"
},
{
"code": "# Ruby code for collect() method # declaring arraya = [1, 2, 3, 4] # invoking block for each elementputs \"collect a : #{a.collect {|x| x + 1 }}\\n\\n\" puts \"collect a : #{a.collect {|x| x - 5*7 }}\\n\\n\"",
"e": 23922,
"s": 23719,
"text": null
},
{
"code": null,
"e": 23931,
"s": 23922,
"text": "Output :"
},
{
"code": null,
"e": 23991,
"s": 23931,
"text": "collect a : [2, 3, 4, 5]\n\ncollect a : [-34, -33, -32, -31]\n"
},
{
"code": null,
"e": 24030,
"s": 23991,
"text": "Code #2 : Example for collect() method"
},
{
"code": "# Ruby code for collect() method # declaring arraya = [\"cat\", \"rat\", \"geeks\"] # invoking block for each elementputs \"collect a : #{a.collect {|x| x + \"!\" }}\\n\\n\" puts \"collect a : #{a.collect {|x| x + \"_at\" }}\\n\\n\"",
"e": 24248,
"s": 24030,
"text": null
},
{
"code": null,
"e": 24257,
"s": 24248,
"text": "Output :"
},
{
"code": null,
"e": 24344,
"s": 24257,
"text": "collect a : [\"cat!\", \"rat!\", \"geeks!\"]\n\ncollect a : [\"cat_at\", \"rat_at\", \"geeks_at\"]\n\n"
},
{
"code": null,
"e": 24361,
"s": 24344,
"text": "Ruby Array-class"
},
{
"code": null,
"e": 24378,
"s": 24361,
"text": "Ruby Collections"
},
{
"code": null,
"e": 24391,
"s": 24378,
"text": "Ruby-Methods"
},
{
"code": null,
"e": 24396,
"s": 24391,
"text": "Ruby"
},
{
"code": null,
"e": 24494,
"s": 24396,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24503,
"s": 24494,
"text": "Comments"
},
{
"code": null,
"e": 24516,
"s": 24503,
"text": "Old Comments"
},
{
"code": null,
"e": 24547,
"s": 24516,
"text": "Ruby | Array count() operation"
},
{
"code": null,
"e": 24574,
"s": 24547,
"text": "Include v/s Extend in Ruby"
},
{
"code": null,
"e": 24617,
"s": 24574,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 24648,
"s": 24617,
"text": "Ruby | Array select() function"
},
{
"code": null,
"e": 24672,
"s": 24648,
"text": "Global Variable in Ruby"
},
{
"code": null,
"e": 24702,
"s": 24672,
"text": "Ruby | Hash delete() function"
},
{
"code": null,
"e": 24729,
"s": 24702,
"text": "Ruby | String gsub! Method"
},
{
"code": null,
"e": 24763,
"s": 24729,
"text": "Ruby | String capitalize() Method"
},
{
"code": null,
"e": 24809,
"s": 24763,
"text": "How to Make a Custom Array of Hashes in Ruby?"
}
] |
Performing Null check using HANA SQL Script
|
You can go for using either NULLIF or COALESCE function to serve your requirement.
NULLIF (expression, expression"): This function will return the same type whatever is specified as the first expression.
Basically, NULLIF returns
The first expression if the two expressions are not equal.
The first expression if the two expressions are not equal.
NULL of type of first expressions if the expressions are equal
NULL of type of first expressions if the expressions are equal
The other function available is COALESCE which basically checks if the first Value provided is NULL then it will return the second value.
c = COALESCE(b , a)
If b is null then the function will return an otherwise b. So If you need to put a null check and use some default value in place of NULL then you can go ahead and use COALESCE.
|
[
{
"code": null,
"e": 1145,
"s": 1062,
"text": "You can go for using either NULLIF or COALESCE function to serve your requirement."
},
{
"code": null,
"e": 1266,
"s": 1145,
"text": "NULLIF (expression, expression\"): This function will return the same type whatever is specified as the first expression."
},
{
"code": null,
"e": 1292,
"s": 1266,
"text": "Basically, NULLIF returns"
},
{
"code": null,
"e": 1351,
"s": 1292,
"text": "The first expression if the two expressions are not equal."
},
{
"code": null,
"e": 1410,
"s": 1351,
"text": "The first expression if the two expressions are not equal."
},
{
"code": null,
"e": 1473,
"s": 1410,
"text": "NULL of type of first expressions if the expressions are equal"
},
{
"code": null,
"e": 1536,
"s": 1473,
"text": "NULL of type of first expressions if the expressions are equal"
},
{
"code": null,
"e": 1674,
"s": 1536,
"text": "The other function available is COALESCE which basically checks if the first Value provided is NULL then it will return the second value."
},
{
"code": null,
"e": 1694,
"s": 1674,
"text": "c = COALESCE(b , a)"
},
{
"code": null,
"e": 1872,
"s": 1694,
"text": "If b is null then the function will return an otherwise b. So If you need to put a null check and use some default value in place of NULL then you can go ahead and use COALESCE."
}
] |
What is Google API Vision? And how to use it | by Christophe Pere | Towards Data Science
|
This post finds his root in an interesting project of knowledge extraction. The first step was to extract the text of pdf documents. The company that I work for is based on the Google platform, so naturally, I would like to use the OCR of the API Vision but, can’t find an easy way to use the API to extract text. So here this post.
The notebook of this post is available on GitHub
Google released the API to help people, industry, and researchers to use their functionalities.
Google Cloud's Vision API has powerful machine learning models pre-trained through REST and RPC APIs. Tag images and quickly organize them into millions of predefined categories. You will be able to detect objects and faces, read printed or handwritten text, and integrate useful metadata into your image catalog. (source: API Vision)
The part of the API that interested us for this post is the OCR part.
Optical Character Recognition or OCR is a technology where characters are recognized and detected inside an image. Most of the time Convolutional Neural Networks (CNN) are trained on a very large dataset of characters and numbers in different types and colors. You can imagine a small window slicing on each pixel or group of pixels to detect characters or partial characters, spaces, forms, lines etc.
A service account is a special type of Google account intended to represent a non-human user that needs to authenticate and be authorized to access data in Google APIs. (source: IAM google cloud)
Basically you can imagine it as an RSA key (encrypted key to communicate with high security between machine via the internet) with which you can connect to Google services (API, GCS, IAM...). Its basic form is a json file.
Here, I will show you the different functions to use the API and extract the text from the image automatically.
Libraries needed to be installed:
!pip install google-cloud!pip install google-cloud-storage!pip install google-cloud-pubsub!pip install google-cloud-vision!pip install pdf2image!pip install google-api-python-client!pip install google-auth
The libraries used:
from pdf2image import convert_from_bytesimport globfrom tqdm import tqdmimport base64import jsonimport osfrom io import BytesIOimport numpy as npimport iofrom PIL import Imagefrom google.cloud import pubsub_v1from google.cloud import visionfrom google.oauth2 import service_accountimport googleapiclient.discovery# to see a progress bartqdm().pandas()
The OCR can take pdf, tiff and jpeg formats to be used in the API.In this post we will convert the pdf into jpeg to concatenate many pages in one picture. Two manners of using jpeg:
First, you could convert your pdf in jpeg files and save them into another repository:
# Name files where the pdf are and where you want to save the resultsNAME_INPUT_FOLDER = "PDF FOLDER NAME"NAME_OUTPUT_FOLDER= "RESULT TEXTS FOLDER"list_pdf = glob.glob(NAME_INPUT_FOLDER+"/*.pdf") # stock the name of the pdf files # Loop over all the filesfor i in list_pdf: # convert the pdf into jpeg pages = convert_from_path(i, 500) for page in tqdm(enumerate(pages)): # save each page into jpeg page[1].save(NAME_OUTPUT_FOLDER+"/"+i.split('/')[-1].split('.')[0]+'_'+str(page[0])+'.jpg', 'JPEG') # keep the name of the document and add increment
Here, you can use your jpeg document with the API. But, you can do it better without saving the jpeg file and use it in memory to call the API directly.
Before going deeper we need to configure the credentials of the Vision API. You’ll see, it’s very simple:
SCOPES = ['https://www.googleapis.com/auth/cloud-vision']SERVICE_ACCOUNT_FILE = "PUT the PATH of YOUR SERVICE ACCOUNT JSON FILE HERE"# Configure the google credentialscredentials = service_account.Credentials.from_service_account_file( SERVICE_ACCOUNT_FILE, scopes=SCOPES)
This needed more code because we also concatenate 10 pages of documents to create a “big picture” and feed it to the API. One call versus 10 is better for the price because you’ll pay each time you’ll request the API.
Let’s go:
With these two functions, you’ll be able to load a pdf file, convert it into bytes, create a “big picture” and feed it to the function detect_text_document() (details below).
The function detect_text_document takes in input the content of the pictures and the credentials (information of your service account).
The output is a text extracted from the images. The goal of this function is to concatenate words into paragraphs and documents.
You can use this block of functions like this:
for doc_pdf in tqdm(list_pdf): # call the function which convert into jpeg, stack 10 images # and call the API, save the output into txt file concat_file_ocr(doc_pdf)
The input is just the path obtained with the glob function. The credentials were generated in the Setup Credentials part. This loop will take each pdf of the input files, call the API with a jpeg file obtained by converting the pdf and save text files containing the detection.
Here, you reach the end of the tutorial on how to use the Vision API and generate text files containing the detection automatically. You know how to configure credentials with your service account and convert a pdf into a jpeg file (one jpeg per page). Is it all? No, I have some bonuses for you (see below).
The previous functions allow you to use the API with the concatenation of pages. But, we can use the API per page of the pdf document. The function below will request the API for each page of the convert pdf into a jpeg format.
It’s very easy to use it, just call this function with the path of the pdf folder and the credentials. Like this:
if per_page: # option True if you want to use per page # call the API vision per page of the pdf for i in tqdm(list_pdf): # open the pdf and convert it into a PlImage format jpeg call_ocr_save_txt(i, cred=credentials)
Just for fun, you can use this API with multiprocessing (ok it’s not real multiprocessing in python with the Global Interpreter Lock (GIL)). But, here the code:
if multi_proc: nb_threads = mp.cpu_count() # return the number of CPU print(f"The number of available CPU is {nb_threads}") # if you want to use the API without stacking the pages if per_page: # create threads corresponding to the number specified pool = mp.Pool(processes=nb_threads) # map the function with part of the list for each thread result = pool.map(call_ocr_save_txt, list_pdf) if per_document: pool = mp.Pool(processes=nb_threads) result = pool.map(concat_file_ocr, list_pdf)
|
[
{
"code": null,
"e": 505,
"s": 172,
"text": "This post finds his root in an interesting project of knowledge extraction. The first step was to extract the text of pdf documents. The company that I work for is based on the Google platform, so naturally, I would like to use the OCR of the API Vision but, can’t find an easy way to use the API to extract text. So here this post."
},
{
"code": null,
"e": 554,
"s": 505,
"text": "The notebook of this post is available on GitHub"
},
{
"code": null,
"e": 650,
"s": 554,
"text": "Google released the API to help people, industry, and researchers to use their functionalities."
},
{
"code": null,
"e": 985,
"s": 650,
"text": "Google Cloud's Vision API has powerful machine learning models pre-trained through REST and RPC APIs. Tag images and quickly organize them into millions of predefined categories. You will be able to detect objects and faces, read printed or handwritten text, and integrate useful metadata into your image catalog. (source: API Vision)"
},
{
"code": null,
"e": 1055,
"s": 985,
"text": "The part of the API that interested us for this post is the OCR part."
},
{
"code": null,
"e": 1458,
"s": 1055,
"text": "Optical Character Recognition or OCR is a technology where characters are recognized and detected inside an image. Most of the time Convolutional Neural Networks (CNN) are trained on a very large dataset of characters and numbers in different types and colors. You can imagine a small window slicing on each pixel or group of pixels to detect characters or partial characters, spaces, forms, lines etc."
},
{
"code": null,
"e": 1654,
"s": 1458,
"text": "A service account is a special type of Google account intended to represent a non-human user that needs to authenticate and be authorized to access data in Google APIs. (source: IAM google cloud)"
},
{
"code": null,
"e": 1877,
"s": 1654,
"text": "Basically you can imagine it as an RSA key (encrypted key to communicate with high security between machine via the internet) with which you can connect to Google services (API, GCS, IAM...). Its basic form is a json file."
},
{
"code": null,
"e": 1989,
"s": 1877,
"text": "Here, I will show you the different functions to use the API and extract the text from the image automatically."
},
{
"code": null,
"e": 2023,
"s": 1989,
"text": "Libraries needed to be installed:"
},
{
"code": null,
"e": 2229,
"s": 2023,
"text": "!pip install google-cloud!pip install google-cloud-storage!pip install google-cloud-pubsub!pip install google-cloud-vision!pip install pdf2image!pip install google-api-python-client!pip install google-auth"
},
{
"code": null,
"e": 2249,
"s": 2229,
"text": "The libraries used:"
},
{
"code": null,
"e": 2601,
"s": 2249,
"text": "from pdf2image import convert_from_bytesimport globfrom tqdm import tqdmimport base64import jsonimport osfrom io import BytesIOimport numpy as npimport iofrom PIL import Imagefrom google.cloud import pubsub_v1from google.cloud import visionfrom google.oauth2 import service_accountimport googleapiclient.discovery# to see a progress bartqdm().pandas()"
},
{
"code": null,
"e": 2783,
"s": 2601,
"text": "The OCR can take pdf, tiff and jpeg formats to be used in the API.In this post we will convert the pdf into jpeg to concatenate many pages in one picture. Two manners of using jpeg:"
},
{
"code": null,
"e": 2870,
"s": 2783,
"text": "First, you could convert your pdf in jpeg files and save them into another repository:"
},
{
"code": null,
"e": 3472,
"s": 2870,
"text": "# Name files where the pdf are and where you want to save the resultsNAME_INPUT_FOLDER = \"PDF FOLDER NAME\"NAME_OUTPUT_FOLDER= \"RESULT TEXTS FOLDER\"list_pdf = glob.glob(NAME_INPUT_FOLDER+\"/*.pdf\") # stock the name of the pdf files # Loop over all the filesfor i in list_pdf: # convert the pdf into jpeg pages = convert_from_path(i, 500) for page in tqdm(enumerate(pages)): # save each page into jpeg page[1].save(NAME_OUTPUT_FOLDER+\"/\"+i.split('/')[-1].split('.')[0]+'_'+str(page[0])+'.jpg', 'JPEG') # keep the name of the document and add increment "
},
{
"code": null,
"e": 3625,
"s": 3472,
"text": "Here, you can use your jpeg document with the API. But, you can do it better without saving the jpeg file and use it in memory to call the API directly."
},
{
"code": null,
"e": 3731,
"s": 3625,
"text": "Before going deeper we need to configure the credentials of the Vision API. You’ll see, it’s very simple:"
},
{
"code": null,
"e": 4011,
"s": 3731,
"text": "SCOPES = ['https://www.googleapis.com/auth/cloud-vision']SERVICE_ACCOUNT_FILE = \"PUT the PATH of YOUR SERVICE ACCOUNT JSON FILE HERE\"# Configure the google credentialscredentials = service_account.Credentials.from_service_account_file( SERVICE_ACCOUNT_FILE, scopes=SCOPES)"
},
{
"code": null,
"e": 4229,
"s": 4011,
"text": "This needed more code because we also concatenate 10 pages of documents to create a “big picture” and feed it to the API. One call versus 10 is better for the price because you’ll pay each time you’ll request the API."
},
{
"code": null,
"e": 4239,
"s": 4229,
"text": "Let’s go:"
},
{
"code": null,
"e": 4414,
"s": 4239,
"text": "With these two functions, you’ll be able to load a pdf file, convert it into bytes, create a “big picture” and feed it to the function detect_text_document() (details below)."
},
{
"code": null,
"e": 4550,
"s": 4414,
"text": "The function detect_text_document takes in input the content of the pictures and the credentials (information of your service account)."
},
{
"code": null,
"e": 4679,
"s": 4550,
"text": "The output is a text extracted from the images. The goal of this function is to concatenate words into paragraphs and documents."
},
{
"code": null,
"e": 4726,
"s": 4679,
"text": "You can use this block of functions like this:"
},
{
"code": null,
"e": 4915,
"s": 4726,
"text": "for doc_pdf in tqdm(list_pdf): # call the function which convert into jpeg, stack 10 images # and call the API, save the output into txt file concat_file_ocr(doc_pdf)"
},
{
"code": null,
"e": 5193,
"s": 4915,
"text": "The input is just the path obtained with the glob function. The credentials were generated in the Setup Credentials part. This loop will take each pdf of the input files, call the API with a jpeg file obtained by converting the pdf and save text files containing the detection."
},
{
"code": null,
"e": 5502,
"s": 5193,
"text": "Here, you reach the end of the tutorial on how to use the Vision API and generate text files containing the detection automatically. You know how to configure credentials with your service account and convert a pdf into a jpeg file (one jpeg per page). Is it all? No, I have some bonuses for you (see below)."
},
{
"code": null,
"e": 5730,
"s": 5502,
"text": "The previous functions allow you to use the API with the concatenation of pages. But, we can use the API per page of the pdf document. The function below will request the API for each page of the convert pdf into a jpeg format."
},
{
"code": null,
"e": 5844,
"s": 5730,
"text": "It’s very easy to use it, just call this function with the path of the pdf folder and the credentials. Like this:"
},
{
"code": null,
"e": 6082,
"s": 5844,
"text": "if per_page: # option True if you want to use per page # call the API vision per page of the pdf for i in tqdm(list_pdf): # open the pdf and convert it into a PlImage format jpeg call_ocr_save_txt(i, cred=credentials)"
},
{
"code": null,
"e": 6243,
"s": 6082,
"text": "Just for fun, you can use this API with multiprocessing (ok it’s not real multiprocessing in python with the Global Interpreter Lock (GIL)). But, here the code:"
}
] |
How to create a notification alert using Kotlin?
|
This example demonstrates how to create a notification alert using Kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇒New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:onClick="btnNotify"
android:text="Show Notification" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
package app.com.kotlinapp
import android.app.*
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
lateinit var notificationChannel: NotificationChannel
lateinit var notificationManager: NotificationManager
lateinit var builder: Notification.Builder
private val channelId = "12345"
private val description = "Test Notification"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as
NotificationManager
}
fun btnNotify(view: View) {
val intent = Intent(this, LauncherActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationChannel = NotificationChannel(channelId, description, NotificationManager .IMPORTANCE_HIGH)
notificationChannel.lightColor = Color.BLUE notificationChannel.enableVibration(true)
notificationManager.createNotificationChannel(notificationChannel)
builder = Notification.Builder(this, channelId).setContentTitle("NOTIFICATION USING " +
"KOTLIN").setContentText("Test Notification").setSmallIcon(R.drawable .ic_brightness).setLargeIcon(BitmapFactory.decodeResource(this.resources, R.drawable
.ic_launcher_background)).setContentIntent(pendingIntent)
}
notificationManager.notify(12345, builder.build())
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.kotlinapp">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
|
[
{
"code": null,
"e": 1137,
"s": 1062,
"text": "This example demonstrates how to create a notification alert using Kotlin."
},
{
"code": null,
"e": 1265,
"s": 1137,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1330,
"s": 1265,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1928,
"s": 1330,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <Button\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:onClick=\"btnNotify\"\n android:text=\"Show Notification\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 1983,
"s": 1928,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 3742,
"s": 1983,
"text": "package app.com.kotlinapp\nimport android.app.*\nimport android.content.Context\nimport android.content.Intent\nimport android.graphics.BitmapFactory\nimport android.graphics.Color\nimport android.os.Build\nimport android.os.Bundle\nimport android.view.View\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n lateinit var notificationChannel: NotificationChannel\n lateinit var notificationManager: NotificationManager\n lateinit var builder: Notification.Builder\n private val channelId = \"12345\"\n private val description = \"Test Notification\"\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as\n NotificationManager\n }\n fun btnNotify(view: View) {\n val intent = Intent(this, LauncherActivity::class.java)\n val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {\n notificationChannel = NotificationChannel(channelId, description, NotificationManager .IMPORTANCE_HIGH)\n notificationChannel.lightColor = Color.BLUE notificationChannel.enableVibration(true)\n notificationManager.createNotificationChannel(notificationChannel)\n builder = Notification.Builder(this, channelId).setContentTitle(\"NOTIFICATION USING \" +\n\"KOTLIN\").setContentText(\"Test Notification\").setSmallIcon(R.drawable .ic_brightness).setLargeIcon(BitmapFactory.decodeResource(this.resources, R.drawable\n.ic_launcher_background)).setContentIntent(pendingIntent)\n }\n notificationManager.notify(12345, builder.build())\n }\n}"
},
{
"code": null,
"e": 3797,
"s": 3742,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4473,
"s": 3797,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.kotlinapp\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4824,
"s": 4473,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 4865,
"s": 4824,
"text": "Click here to download the project code."
}
] |
Android - Bluetooth
|
Among many ways, Bluetooth is a way to send or receive data between two different devices. Android platform includes support for the Bluetooth framework that allows a device to wirelessly exchange data with other Bluetooth devices.
Android provides Bluetooth API to perform these different operations.
Scan for other Bluetooth devices
Scan for other Bluetooth devices
Get a list of paired devices
Get a list of paired devices
Connect to other devices through service discovery
Connect to other devices through service discovery
Android provides BluetoothAdapter class to communicate with Bluetooth. Create an object of this calling by calling the static method getDefaultAdapter(). Its syntax is given below.
private BluetoothAdapter BA;
BA = BluetoothAdapter.getDefaultAdapter();
In order to enable the Bluetooth of your device, call the intent with the following Bluetooth constant ACTION_REQUEST_ENABLE. Its syntax is.
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
Apart from this constant, there are other constants provided the API , that supports different tasks. They are listed below.
ACTION_REQUEST_DISCOVERABLE
This constant is used for turn on discovering of bluetooth
ACTION_STATE_CHANGED
This constant will notify that Bluetooth state has been changed
ACTION_FOUND
This constant is used for receiving information about each device that is discovered
Once you enable the Bluetooth , you can get a list of paired devices by calling getBondedDevices() method. It returns a set of bluetooth devices. Its syntax is.
private Set<BluetoothDevice>pairedDevices;
pairedDevices = BA.getBondedDevices();
Apart form the parried Devices , there are other methods in the API that gives more control over Blueetooth. They are listed below.
enable()
This method enables the adapter if not enabled
isEnabled()
This method returns true if adapter is enabled
disable()
This method disables the adapter
getName()
This method returns the name of the Bluetooth adapter
setName(String name)
This method changes the Bluetooth name
getState()
This method returns the current state of the Bluetooth Adapter.
startDiscovery()
This method starts the discovery process of the Bluetooth for 120 seconds.
This example provides demonstration of BluetoothAdapter class to manipulate Bluetooth and show list of paired devices by the Bluetooth.
To experiment with this example , you need to run this on an actual device.
Here is the content of src/MainActivity.java
package com.example.sairamkrishna.myapplication;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Set;
public class MainActivity extends Activity {
Button b1,b2,b3,b4;
private BluetoothAdapter BA;
private Set<BluetoothDevice>pairedDevices;
ListView lv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button);
b2=(Button)findViewById(R.id.button2);
b3=(Button)findViewById(R.id.button3);
b4=(Button)findViewById(R.id.button4);
BA = BluetoothAdapter.getDefaultAdapter();
lv = (ListView)findViewById(R.id.listView);
}
public void on(View v){
if (!BA.isEnabled()) {
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
Toast.makeText(getApplicationContext(), "Turned on",Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Already on", Toast.LENGTH_LONG).show();
}
}
public void off(View v){
BA.disable();
Toast.makeText(getApplicationContext(), "Turned off" ,Toast.LENGTH_LONG).show();
}
public void visible(View v){
Intent getVisible = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(getVisible, 0);
}
public void list(View v){
pairedDevices = BA.getBondedDevices();
ArrayList list = new ArrayList();
for(BluetoothDevice bt : pairedDevices) list.add(bt.getName());
Toast.makeText(getApplicationContext(), "Showing Paired Devices",Toast.LENGTH_SHORT).show();
final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
}
}
Here is the content of activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:transitionGroup="true">
<TextView android:text="Bluetooth Example"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:theme="@style/Base.TextAppearance.AppCompat" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Turn On"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_toStartOf="@+id/imageView"
android:layout_toLeftOf="@+id/imageView"
android:clickable="true"
android:onClick="on" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get visible"
android:onClick="visible"
android:id="@+id/button2"
android:layout_alignBottom="@+id/button"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="List devices"
android:onClick="list"
android:id="@+id/button3"
android:layout_below="@+id/imageView"
android:layout_toRightOf="@+id/imageView"
android:layout_toEndOf="@+id/imageView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="turn off"
android:onClick="off"
android:id="@+id/button4"
android:layout_below="@+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/listView"
android:layout_alignParentBottom="true"
android:layout_alignLeft="@+id/button"
android:layout_alignStart="@+id/button"
android:layout_below="@+id/textView2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Paired devices:"
android:id="@+id/textView2"
android:textColor="#ff34ff06"
android:textSize="25dp"
android:layout_below="@+id/button4"
android:layout_alignLeft="@+id/listView"
android:layout_alignStart="@+id/listView" />
</RelativeLayout>
Here is the content of Strings.xml
<resources>
<string name="app_name">My Application</string>
</resources>
Here is the content of AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Android studio, open one of your project's activity files and click Run icon from the tool bar.If your Bluetooth will not be turned on then, it will ask your permission to enable the Bluetooth.
Now just select the Get Visible button to turn on your visibility. The following screen would appear asking your permission to turn on discovery for 120 seconds.
Now just select the List Devices option. It will list down the paired devices in the list view. In my case , I have only one paired device. It is shown below.
Now just select the Turn off button to switch off the Bluetooth. Following message would appear when you switch off the bluetooth indicating the successful switching off of Bluetooth.
46 Lectures
7.5 hours
Aditya Dua
32 Lectures
3.5 hours
Sharad Kumar
9 Lectures
1 hours
Abhilash Nelson
14 Lectures
1.5 hours
Abhilash Nelson
15 Lectures
1.5 hours
Abhilash Nelson
10 Lectures
1 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3839,
"s": 3607,
"text": "Among many ways, Bluetooth is a way to send or receive data between two different devices. Android platform includes support for the Bluetooth framework that allows a device to wirelessly exchange data with other Bluetooth devices."
},
{
"code": null,
"e": 3909,
"s": 3839,
"text": "Android provides Bluetooth API to perform these different operations."
},
{
"code": null,
"e": 3942,
"s": 3909,
"text": "Scan for other Bluetooth devices"
},
{
"code": null,
"e": 3975,
"s": 3942,
"text": "Scan for other Bluetooth devices"
},
{
"code": null,
"e": 4004,
"s": 3975,
"text": "Get a list of paired devices"
},
{
"code": null,
"e": 4033,
"s": 4004,
"text": "Get a list of paired devices"
},
{
"code": null,
"e": 4084,
"s": 4033,
"text": "Connect to other devices through service discovery"
},
{
"code": null,
"e": 4135,
"s": 4084,
"text": "Connect to other devices through service discovery"
},
{
"code": null,
"e": 4316,
"s": 4135,
"text": "Android provides BluetoothAdapter class to communicate with Bluetooth. Create an object of this calling by calling the static method getDefaultAdapter(). Its syntax is given below."
},
{
"code": null,
"e": 4388,
"s": 4316,
"text": "private BluetoothAdapter BA;\nBA = BluetoothAdapter.getDefaultAdapter();"
},
{
"code": null,
"e": 4529,
"s": 4388,
"text": "In order to enable the Bluetooth of your device, call the intent with the following Bluetooth constant ACTION_REQUEST_ENABLE. Its syntax is."
},
{
"code": null,
"e": 4639,
"s": 4529,
"text": "Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);\nstartActivityForResult(turnOn, 0); "
},
{
"code": null,
"e": 4764,
"s": 4639,
"text": "Apart from this constant, there are other constants provided the API , that supports different tasks. They are listed below."
},
{
"code": null,
"e": 4792,
"s": 4764,
"text": "ACTION_REQUEST_DISCOVERABLE"
},
{
"code": null,
"e": 4851,
"s": 4792,
"text": "This constant is used for turn on discovering of bluetooth"
},
{
"code": null,
"e": 4872,
"s": 4851,
"text": "ACTION_STATE_CHANGED"
},
{
"code": null,
"e": 4936,
"s": 4872,
"text": "This constant will notify that Bluetooth state has been changed"
},
{
"code": null,
"e": 4949,
"s": 4936,
"text": "ACTION_FOUND"
},
{
"code": null,
"e": 5034,
"s": 4949,
"text": "This constant is used for receiving information about each device that is discovered"
},
{
"code": null,
"e": 5195,
"s": 5034,
"text": "Once you enable the Bluetooth , you can get a list of paired devices by calling getBondedDevices() method. It returns a set of bluetooth devices. Its syntax is."
},
{
"code": null,
"e": 5277,
"s": 5195,
"text": "private Set<BluetoothDevice>pairedDevices;\npairedDevices = BA.getBondedDevices();"
},
{
"code": null,
"e": 5409,
"s": 5277,
"text": "Apart form the parried Devices , there are other methods in the API that gives more control over Blueetooth. They are listed below."
},
{
"code": null,
"e": 5418,
"s": 5409,
"text": "enable()"
},
{
"code": null,
"e": 5465,
"s": 5418,
"text": "This method enables the adapter if not enabled"
},
{
"code": null,
"e": 5477,
"s": 5465,
"text": "isEnabled()"
},
{
"code": null,
"e": 5524,
"s": 5477,
"text": "This method returns true if adapter is enabled"
},
{
"code": null,
"e": 5534,
"s": 5524,
"text": "disable()"
},
{
"code": null,
"e": 5567,
"s": 5534,
"text": "This method disables the adapter"
},
{
"code": null,
"e": 5577,
"s": 5567,
"text": "getName()"
},
{
"code": null,
"e": 5631,
"s": 5577,
"text": "This method returns the name of the Bluetooth adapter"
},
{
"code": null,
"e": 5652,
"s": 5631,
"text": "setName(String name)"
},
{
"code": null,
"e": 5691,
"s": 5652,
"text": "This method changes the Bluetooth name"
},
{
"code": null,
"e": 5702,
"s": 5691,
"text": "getState()"
},
{
"code": null,
"e": 5766,
"s": 5702,
"text": "This method returns the current state of the Bluetooth Adapter."
},
{
"code": null,
"e": 5783,
"s": 5766,
"text": "startDiscovery()"
},
{
"code": null,
"e": 5858,
"s": 5783,
"text": "This method starts the discovery process of the Bluetooth for 120 seconds."
},
{
"code": null,
"e": 5994,
"s": 5858,
"text": "This example provides demonstration of BluetoothAdapter class to manipulate Bluetooth and show list of paired devices by the Bluetooth."
},
{
"code": null,
"e": 6070,
"s": 5994,
"text": "To experiment with this example , you need to run this on an actual device."
},
{
"code": null,
"e": 6115,
"s": 6070,
"text": "Here is the content of src/MainActivity.java"
},
{
"code": null,
"e": 8298,
"s": 6115,
"text": "package com.example.sairamkrishna.myapplication;\n\nimport android.app.Activity;\nimport android.bluetooth.BluetoothAdapter;\nimport android.bluetooth.BluetoothDevice;\n\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.view.View;\n\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\n\nimport android.widget.Toast;\nimport java.util.ArrayList;\nimport java.util.Set;\n\npublic class MainActivity extends Activity {\n Button b1,b2,b3,b4;\n private BluetoothAdapter BA;\n private Set<BluetoothDevice>pairedDevices;\n ListView lv;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n b1 = (Button) findViewById(R.id.button);\n b2=(Button)findViewById(R.id.button2);\n b3=(Button)findViewById(R.id.button3);\n b4=(Button)findViewById(R.id.button4);\n\n BA = BluetoothAdapter.getDefaultAdapter();\n lv = (ListView)findViewById(R.id.listView);\n }\n\n public void on(View v){\n if (!BA.isEnabled()) {\n Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);\n startActivityForResult(turnOn, 0);\n Toast.makeText(getApplicationContext(), \"Turned on\",Toast.LENGTH_LONG).show();\n } else {\n Toast.makeText(getApplicationContext(), \"Already on\", Toast.LENGTH_LONG).show();\n }\n }\n\n public void off(View v){\n BA.disable();\n Toast.makeText(getApplicationContext(), \"Turned off\" ,Toast.LENGTH_LONG).show();\n }\n\n \n public void visible(View v){\n Intent getVisible = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);\n startActivityForResult(getVisible, 0);\n }\n\n \n public void list(View v){\n pairedDevices = BA.getBondedDevices();\n \n ArrayList list = new ArrayList();\n\n for(BluetoothDevice bt : pairedDevices) list.add(bt.getName());\n Toast.makeText(getApplicationContext(), \"Showing Paired Devices\",Toast.LENGTH_SHORT).show();\n\n final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);\n \n lv.setAdapter(adapter);\n }\n}"
},
{
"code": null,
"e": 8339,
"s": 8298,
"text": "Here is the content of activity_main.xml"
},
{
"code": null,
"e": 11879,
"s": 8339,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout \nxmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\" \n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" \n android:paddingLeft=\"@dimen/activity_horizontal_margin\"\n android:paddingRight=\"@dimen/activity_horizontal_margin\"\n android:paddingTop=\"@dimen/activity_vertical_margin\"\n android:paddingBottom=\"@dimen/activity_vertical_margin\"\n tools:context=\".MainActivity\"\n android:transitionGroup=\"true\">\n \n <TextView android:text=\"Bluetooth Example\" \n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/textview\"\n android:textSize=\"35dp\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\" />\n \n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Tutorials point\"\n android:id=\"@+id/textView\"\n android:layout_below=\"@+id/textview\"\n android:layout_centerHorizontal=\"true\"\n android:textColor=\"#ff7aff24\"\n android:textSize=\"35dp\" />\n \n <ImageView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/imageView\"\n android:src=\"@drawable/abc\"\n android:layout_below=\"@+id/textView\"\n android:layout_centerHorizontal=\"true\"\n android:theme=\"@style/Base.TextAppearance.AppCompat\" />\n \n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Turn On\"\n android:id=\"@+id/button\"\n android:layout_below=\"@+id/imageView\"\n android:layout_toStartOf=\"@+id/imageView\"\n android:layout_toLeftOf=\"@+id/imageView\"\n android:clickable=\"true\"\n android:onClick=\"on\" />\n \n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Get visible\"\n android:onClick=\"visible\"\n android:id=\"@+id/button2\"\n android:layout_alignBottom=\"@+id/button\"\n android:layout_centerHorizontal=\"true\" />\n \n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"List devices\"\n android:onClick=\"list\"\n android:id=\"@+id/button3\"\n android:layout_below=\"@+id/imageView\"\n android:layout_toRightOf=\"@+id/imageView\"\n android:layout_toEndOf=\"@+id/imageView\" />\n \n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"turn off\"\n android:onClick=\"off\"\n android:id=\"@+id/button4\"\n android:layout_below=\"@+id/button\"\n android:layout_alignParentLeft=\"true\"\n android:layout_alignParentStart=\"true\" />\n \n <ListView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/listView\"\n android:layout_alignParentBottom=\"true\"\n android:layout_alignLeft=\"@+id/button\"\n android:layout_alignStart=\"@+id/button\"\n android:layout_below=\"@+id/textView2\" />\n \n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Paired devices:\"\n android:id=\"@+id/textView2\"\n android:textColor=\"#ff34ff06\"\n android:textSize=\"25dp\"\n android:layout_below=\"@+id/button4\"\n android:layout_alignLeft=\"@+id/listView\"\n android:layout_alignStart=\"@+id/listView\" />\n\n</RelativeLayout>"
},
{
"code": null,
"e": 11914,
"s": 11879,
"text": "Here is the content of Strings.xml"
},
{
"code": null,
"e": 11990,
"s": 11914,
"text": "<resources>\n <string name=\"app_name\">My Application</string>\n</resources>"
},
{
"code": null,
"e": 12033,
"s": 11990,
"text": "Here is the content of AndroidManifest.xml"
},
{
"code": null,
"e": 12876,
"s": 12033,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.sairamkrishna.myapplication\" >\n <uses-permission android:name=\"android.permission.BLUETOOTH\"/>\n <uses-permission android:name=\"android.permission.BLUETOOTH_ADMIN\"/>\n \n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:theme=\"@style/AppTheme\" >\n \n <activity\n android:name=\".MainActivity\"\n android:label=\"@string/app_name\" >\n \n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n \n </activity>\n \n </application>\n</manifest>"
},
{
"code": null,
"e": 13208,
"s": 12876,
"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 tool bar.If your Bluetooth will not be turned on then, it will ask your permission to enable the Bluetooth."
},
{
"code": null,
"e": 13370,
"s": 13208,
"text": "Now just select the Get Visible button to turn on your visibility. The following screen would appear asking your permission to turn on discovery for 120 seconds."
},
{
"code": null,
"e": 13529,
"s": 13370,
"text": "Now just select the List Devices option. It will list down the paired devices in the list view. In my case , I have only one paired device. It is shown below."
},
{
"code": null,
"e": 13713,
"s": 13529,
"text": "Now just select the Turn off button to switch off the Bluetooth. Following message would appear when you switch off the bluetooth indicating the successful switching off of Bluetooth."
},
{
"code": null,
"e": 13748,
"s": 13713,
"text": "\n 46 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 13760,
"s": 13748,
"text": " Aditya Dua"
},
{
"code": null,
"e": 13795,
"s": 13760,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 13809,
"s": 13795,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 13841,
"s": 13809,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 13858,
"s": 13841,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 13893,
"s": 13858,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 13910,
"s": 13893,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 13945,
"s": 13910,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 13962,
"s": 13945,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 13995,
"s": 13962,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 14012,
"s": 13995,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 14019,
"s": 14012,
"text": " Print"
},
{
"code": null,
"e": 14030,
"s": 14019,
"text": " Add Notes"
}
] |
cleardevice() function in C - GeeksforGeeks
|
23 Jan, 2018
The header file graphics.h contains cleardevice() function which clears the screen in graphics mode and sets the current position to (0,0). Clearing the screen consists of filling the screen with current background color.
Syntax :
void cleardevice();
Below is the implementation of cleardevice() in C:
// C Implementation for cleardevice()#include <graphics.h> // driver codeint main(){ // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // "graphics.h" header file int gd = DETECT, gm; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, ""); // set the background colour as GREEN setbkcolor(GREEN); // outtext function displays // text at current position. outtext("Press any key to clear the screen."); getch(); // cleardevice function cleardevice(); outtext("Press any key to exit..."); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0;}
Output:
On executing the program, the output window looks like :
On pressing any key :
To exit, press any key.
c-graphics
computer-graphics
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
Core Dump (Segmentation fault) in C/C++
fork() in C
Command line arguments in C/C++
Function Pointer in C
Substring in C++
Different methods to reverse a string in C/C++
Structures in C
|
[
{
"code": null,
"e": 24492,
"s": 24464,
"text": "\n23 Jan, 2018"
},
{
"code": null,
"e": 24714,
"s": 24492,
"text": "The header file graphics.h contains cleardevice() function which clears the screen in graphics mode and sets the current position to (0,0). Clearing the screen consists of filling the screen with current background color."
},
{
"code": null,
"e": 24723,
"s": 24714,
"text": "Syntax :"
},
{
"code": null,
"e": 24744,
"s": 24723,
"text": "void cleardevice();\n"
},
{
"code": null,
"e": 24795,
"s": 24744,
"text": "Below is the implementation of cleardevice() in C:"
},
{
"code": "// C Implementation for cleardevice()#include <graphics.h> // driver codeint main(){ // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // \"graphics.h\" header file int gd = DETECT, gm; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, \"\"); // set the background colour as GREEN setbkcolor(GREEN); // outtext function displays // text at current position. outtext(\"Press any key to clear the screen.\"); getch(); // cleardevice function cleardevice(); outtext(\"Press any key to exit...\"); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0;}",
"e": 25666,
"s": 24795,
"text": null
},
{
"code": null,
"e": 25674,
"s": 25666,
"text": "Output:"
},
{
"code": null,
"e": 25781,
"s": 25674,
"text": "On executing the program, the output window looks like :\n\nOn pressing any key :\n\nTo exit, press any key.\n\n"
},
{
"code": null,
"e": 25792,
"s": 25781,
"text": "c-graphics"
},
{
"code": null,
"e": 25810,
"s": 25792,
"text": "computer-graphics"
},
{
"code": null,
"e": 25821,
"s": 25810,
"text": "C Language"
},
{
"code": null,
"e": 25919,
"s": 25821,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25954,
"s": 25919,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 25982,
"s": 25954,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 26028,
"s": 25982,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 26068,
"s": 26028,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 26080,
"s": 26068,
"text": "fork() in C"
},
{
"code": null,
"e": 26112,
"s": 26080,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 26134,
"s": 26112,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 26151,
"s": 26134,
"text": "Substring in C++"
},
{
"code": null,
"e": 26198,
"s": 26151,
"text": "Different methods to reverse a string in C/C++"
}
] |
Insert current date to the database in MySQL?
|
To insert current date to the database, you can use NOW(). Following is the syntax −
INSERT INTO yourTableName(yourDateColumnName) VALUES(NOW());
If your column has datatype date then NOW() function inserts only current date, not time and MySQL will give a warning. To remove the warning, you can use CURDATE().
Let us first create a table −
mysql> create table insertcurrentdate
-> (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> currentDate date
-> );
Query OK, 0 rows affected (1.09 sec)
Following is the query to insert some records in the table using insert command. We have used both NOW() and CURDATE() to display current date −
mysql> insert into insertcurrentdate(currentDate) values(NOW());
Query OK, 1 row affected, 1 warning (0.24 sec)
mysql> insert into insertcurrentdate(currentDate) values(CURDATE());
Query OK, 1 row affected (0.18 sec)
Following is the query to display all records from the table using select statement −
mysql> select * from insertcurrentdate;
This will produce the following output −
+----+-------------+
| Id | currentDate |
+----+-------------+
| 1 | 2019-04-05 |
| 2 | 2019-04-05 |
+----+-------------+
2 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1147,
"s": 1062,
"text": "To insert current date to the database, you can use NOW(). Following is the syntax −"
},
{
"code": null,
"e": 1208,
"s": 1147,
"text": "INSERT INTO yourTableName(yourDateColumnName) VALUES(NOW());"
},
{
"code": null,
"e": 1374,
"s": 1208,
"text": "If your column has datatype date then NOW() function inserts only current date, not time and MySQL will give a warning. To remove the warning, you can use CURDATE()."
},
{
"code": null,
"e": 1404,
"s": 1374,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1569,
"s": 1404,
"text": "mysql> create table insertcurrentdate\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> currentDate date\n -> );\nQuery OK, 0 rows affected (1.09 sec)"
},
{
"code": null,
"e": 1714,
"s": 1569,
"text": "Following is the query to insert some records in the table using insert command. We have used both NOW() and CURDATE() to display current date −"
},
{
"code": null,
"e": 1932,
"s": 1714,
"text": "mysql> insert into insertcurrentdate(currentDate) values(NOW());\nQuery OK, 1 row affected, 1 warning (0.24 sec)\n\nmysql> insert into insertcurrentdate(currentDate) values(CURDATE());\nQuery OK, 1 row affected (0.18 sec)"
},
{
"code": null,
"e": 2018,
"s": 1932,
"text": "Following is the query to display all records from the table using select statement −"
},
{
"code": null,
"e": 2058,
"s": 2018,
"text": "mysql> select * from insertcurrentdate;"
},
{
"code": null,
"e": 2099,
"s": 2058,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2250,
"s": 2099,
"text": "+----+-------------+\n| Id | currentDate |\n+----+-------------+\n| 1 | 2019-04-05 |\n| 2 | 2019-04-05 |\n+----+-------------+\n2 rows in set (0.00 sec)"
}
] |
C++ Library - <limits>
|
It is a Numeric limits type and it provides information about the properties of arithmetic types (either integral or floating-point) in the specific platform for which the library compiles.
Following is the declaration for std::numeric_limits.
template <class T> numeric_limits;
template <class T> numeric_limits;
T − It is a type of class.
In below example for std::numeric_limits.
#include <limits>
#include <iostream>
int main() {
std::cout << "type\tlowest type\thighest type\n";
std::cout << "int\t"
<< std::numeric_limits<int>::lowest() << '\t'
<< std::numeric_limits<int>::max() << '\n';
std::cout << "float\t"
<< std::numeric_limits<float>::lowest() << '\t'
<< std::numeric_limits<float>::max() << '\n';
std::cout << "double\t"
<< std::numeric_limits<double>::lowest() << '\t'
<< std::numeric_limits<double>::max() << '\n';
}
The sample output should be like this −
type lowest type highest type
int -2147483648 2147483647
float -3.40282e+38 3.40282e+38
double -1.79769e+308 1.79769e+308
The fundamental arithmetic types of C++98 should be like this −
The fundamental arithmetic types of C++11 should be like this −
It is a minimum finite value.
For floating types with denormalization (variable number of exponent bits): minimum positive normalized value.
Equivalent to CHAR_MIN, SCHAR_MIN, SHRT_MIN, INT_MIN, LONG_MIN, LLONG_MIN, FLT_MIN, BL_MIN, LDBL_MIN or 0, depending on type.
It is a maximum finite value.
Equivalent to CHAR_MAX, SCHAR_MAX, UCHAR_MAX, SHRT_MAX, USHRT_MAX, INT_MAX, UINT_MAX, LONG_MAX, ULONG_MAX, LLONG_MAX, ULLONG_MAX, UINT_LEAST16_MAX, UINT_LEAST32_MAX, FLT_MAX, DBL_MAX or LDBL_MAX, depending on type.
It is a minimum finite value. (since C++11)
For integral types: the same as min().
For floating-point types: implementation-dependent; generally, the negative of max().
It is for integer types: number of non-sign bits (radix base digits) in the representation.
For floating types: number of digits (in radix base) in the mantissa (equivalent to FLT_MANT_DIG, DBL_MANT_DIG or LDBL_MANT_DIG).
It is a number of digits (in decimal base), that can be represented without change.
Equivalent to FLT_DIG, DBL_DIG or LDBL_DIG for floating types.
It is for integer types: base of the representation.
For floating types: base of the exponent of the representation (equivalent to FLT_RADIX).
It is a machine epsilon (the difference between 1 and the least value greater than 1 that is representable).
Equivalent to FLT_EPSILON, DBL_EPSILON or LDBL_EPSILON for floating types.
It is a minimum negative integer value such that radix raised to (min_exponent-1) generates a normalized floating-point number.
Equivalent to FLT_MIN_EXP, DBL_MIN_EXP or LDBL_MIN_EXP for floating types.
It is a minimum negative integer value such that 10 raised to that power generates a normalized floating-point number.
Equivalent to FLT_MIN_10_EXP, DBL_MIN_10_EXP or LDBL_MIN_10_EXP for floating types.
It is a maximum integer value such that radix raised to (max_exponent-1) generates a representable finite floating-point number.
Equivalent to FLT_MAX_EXP, DBL_MAX_EXP or LDBL_MAX_EXP for floating types.
It is a maximum integer value such that 10 raised to that power generates a normalized finite floating-point number.
Equivalent to FLT_MAX_10_EXP, DBL_MAX_10_EXP or LDBL_MAX_10_EXP for floating types.
It is a denormalized values (representations with a variable number of exponent bits). A type may have any of the following enum values −
denorm_absent, if it does not allow denormalized values.
denorm_present, if it allows denormalized values.
denorm_indeterminate, if indeterminate at compile time.
Minimum positive denormalized value.
It is for types not allowing denormalized values: same as min().
true if the type adheres to IEC-559 / IEEE-754 standard.
An IEC-559 type always has has_infinity, has_quiet_NaN and has_signaling_NaN set to true; And infinity, quiet_NaN and signaling_NaN return some non-zero value.
It is a rounding style. A type may have any of the following enum values −
round_toward_zero, if it rounds toward zero.
round_to_nearest, if it rounds to the nearest representable value.
round_toward_infinity, if it rounds toward infinity.
round_toward_neg_infinity, if it rounds toward negative infinity.
round_indeterminate, if the rounding style is indeterminable at compile time.
For all above types that are not fundamental arithmetic types, the default template definition is used −
template <class T> class numeric_limits {
public:
static const bool is_specialized = false;
static T min() throw();
static T max() throw();
static const int digits = 0;
static const int digits10 = 0;
static const bool is_signed = false;
static const bool is_integer = false;
static const bool is_exact = false;
static const int radix = 0;
static T epsilon() throw();
static T round_error() throw();
static const int min_exponent = 0;
static const int min_exponent10 = 0;
static const int max_exponent = 0;
static const int max_exponent10 = 0;
static const bool has_infinity = false;
static const bool has_quiet_NaN = false;
static const bool has_signaling_NaN = false;
static const float_denorm_style has_denorm = denorm_absent;
static const bool has_denorm_loss = false;
static T infinity() throw();
static T quiet_NaN() throw();
static T signaling_NaN() throw();
static T denorm_min() throw();
static const bool is_iec559 = false;
static const bool is_bounded = false;
static const bool is_modulo = false;
static const bool traps = false;
static const bool tinyness_before = false;
static const float_round_style round_style = round_toward_zero;
};
template <class T> class numeric_limits {
public:
static constexpr bool is_specialized = false;
static constexpr T min() noexcept { return T(); }
static constexpr T max() noexcept { return T(); }
static constexpr T lowest() noexcept { return T(); }
static constexpr int digits = 0;
static constexpr int digits10 = 0;
static constexpr bool is_signed = false;
static constexpr bool is_integer = false;
static constexpr bool is_exact = false;
static constexpr int radix = 0;
static constexpr T epsilon() noexcept { return T(); }
static constexpr T round_error() noexcept { return T(); }
static constexpr int min_exponent = 0;
static constexpr int min_exponent10 = 0;
static constexpr int max_exponent = 0;
static constexpr int max_exponent10 = 0;
static constexpr bool has_infinity = false;
static constexpr bool has_quiet_NaN = false;
static constexpr bool has_signaling_NaN = false;
static constexpr float_denorm_style has_denorm = denorm_absent;
static constexpr bool has_denorm_loss = false;
static constexpr T infinity() noexcept { return T(); }
static constexpr T quiet_NaN() noexcept { return T(); }
static constexpr T signaling_NaN() noexcept { return T(); }
static constexpr T denorm_min() noexcept { return T(); }
static constexpr bool is_iec559 = false;
static constexpr bool is_bounded = false;
static constexpr bool is_modulo = false;
static constexpr bool traps = false;
static constexpr bool tinyness_before = false;
};
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2793,
"s": 2603,
"text": "It is a Numeric limits type and it provides information about the properties of arithmetic types (either integral or floating-point) in the specific platform for which the library compiles."
},
{
"code": null,
"e": 2847,
"s": 2793,
"text": "Following is the declaration for std::numeric_limits."
},
{
"code": null,
"e": 2883,
"s": 2847,
"text": "template <class T> numeric_limits; "
},
{
"code": null,
"e": 2919,
"s": 2883,
"text": "template <class T> numeric_limits; "
},
{
"code": null,
"e": 2946,
"s": 2919,
"text": "T − It is a type of class."
},
{
"code": null,
"e": 2988,
"s": 2946,
"text": "In below example for std::numeric_limits."
},
{
"code": null,
"e": 3488,
"s": 2988,
"text": "#include <limits>\n#include <iostream>\n\nint main() {\n std::cout << \"type\\tlowest type\\thighest type\\n\";\n std::cout << \"int\\t\"\n << std::numeric_limits<int>::lowest() << '\\t'\n << std::numeric_limits<int>::max() << '\\n';\n std::cout << \"float\\t\"\n << std::numeric_limits<float>::lowest() << '\\t'\n << std::numeric_limits<float>::max() << '\\n';\n std::cout << \"double\\t\"\n << std::numeric_limits<double>::lowest() << '\\t'\n << std::numeric_limits<double>::max() << '\\n';\n}"
},
{
"code": null,
"e": 3528,
"s": 3488,
"text": "The sample output should be like this −"
},
{
"code": null,
"e": 3651,
"s": 3528,
"text": "type\tlowest type\thighest type\nint\t-2147483648\t2147483647\nfloat\t-3.40282e+38\t3.40282e+38\ndouble\t-1.79769e+308\t1.79769e+308\n"
},
{
"code": null,
"e": 3715,
"s": 3651,
"text": "The fundamental arithmetic types of C++98 should be like this −"
},
{
"code": null,
"e": 3779,
"s": 3715,
"text": "The fundamental arithmetic types of C++11 should be like this −"
},
{
"code": null,
"e": 3809,
"s": 3779,
"text": "It is a minimum finite value."
},
{
"code": null,
"e": 3920,
"s": 3809,
"text": "For floating types with denormalization (variable number of exponent bits): minimum positive normalized value."
},
{
"code": null,
"e": 4046,
"s": 3920,
"text": "Equivalent to CHAR_MIN, SCHAR_MIN, SHRT_MIN, INT_MIN, LONG_MIN, LLONG_MIN, FLT_MIN, BL_MIN, LDBL_MIN or 0, depending on type."
},
{
"code": null,
"e": 4076,
"s": 4046,
"text": "It is a maximum finite value."
},
{
"code": null,
"e": 4291,
"s": 4076,
"text": "Equivalent to CHAR_MAX, SCHAR_MAX, UCHAR_MAX, SHRT_MAX, USHRT_MAX, INT_MAX, UINT_MAX, LONG_MAX, ULONG_MAX, LLONG_MAX, ULLONG_MAX, UINT_LEAST16_MAX, UINT_LEAST32_MAX, FLT_MAX, DBL_MAX or LDBL_MAX, depending on type."
},
{
"code": null,
"e": 4335,
"s": 4291,
"text": "It is a minimum finite value. (since C++11)"
},
{
"code": null,
"e": 4374,
"s": 4335,
"text": "For integral types: the same as min()."
},
{
"code": null,
"e": 4460,
"s": 4374,
"text": "For floating-point types: implementation-dependent; generally, the negative of max()."
},
{
"code": null,
"e": 4552,
"s": 4460,
"text": "It is for integer types: number of non-sign bits (radix base digits) in the representation."
},
{
"code": null,
"e": 4682,
"s": 4552,
"text": "For floating types: number of digits (in radix base) in the mantissa (equivalent to FLT_MANT_DIG, DBL_MANT_DIG or LDBL_MANT_DIG)."
},
{
"code": null,
"e": 4766,
"s": 4682,
"text": "It is a number of digits (in decimal base), that can be represented without change."
},
{
"code": null,
"e": 4829,
"s": 4766,
"text": "Equivalent to FLT_DIG, DBL_DIG or LDBL_DIG for floating types."
},
{
"code": null,
"e": 4882,
"s": 4829,
"text": "It is for integer types: base of the representation."
},
{
"code": null,
"e": 4972,
"s": 4882,
"text": "For floating types: base of the exponent of the representation (equivalent to FLT_RADIX)."
},
{
"code": null,
"e": 5081,
"s": 4972,
"text": "It is a machine epsilon (the difference between 1 and the least value greater than 1 that is representable)."
},
{
"code": null,
"e": 5156,
"s": 5081,
"text": "Equivalent to FLT_EPSILON, DBL_EPSILON or LDBL_EPSILON for floating types."
},
{
"code": null,
"e": 5284,
"s": 5156,
"text": "It is a minimum negative integer value such that radix raised to (min_exponent-1) generates a normalized floating-point number."
},
{
"code": null,
"e": 5359,
"s": 5284,
"text": "Equivalent to FLT_MIN_EXP, DBL_MIN_EXP or LDBL_MIN_EXP for floating types."
},
{
"code": null,
"e": 5478,
"s": 5359,
"text": "It is a minimum negative integer value such that 10 raised to that power generates a normalized floating-point number."
},
{
"code": null,
"e": 5562,
"s": 5478,
"text": "Equivalent to FLT_MIN_10_EXP, DBL_MIN_10_EXP or LDBL_MIN_10_EXP for floating types."
},
{
"code": null,
"e": 5691,
"s": 5562,
"text": "It is a maximum integer value such that radix raised to (max_exponent-1) generates a representable finite floating-point number."
},
{
"code": null,
"e": 5766,
"s": 5691,
"text": "Equivalent to FLT_MAX_EXP, DBL_MAX_EXP or LDBL_MAX_EXP for floating types."
},
{
"code": null,
"e": 5883,
"s": 5766,
"text": "It is a maximum integer value such that 10 raised to that power generates a normalized finite floating-point number."
},
{
"code": null,
"e": 5967,
"s": 5883,
"text": "Equivalent to FLT_MAX_10_EXP, DBL_MAX_10_EXP or LDBL_MAX_10_EXP for floating types."
},
{
"code": null,
"e": 6105,
"s": 5967,
"text": "It is a denormalized values (representations with a variable number of exponent bits). A type may have any of the following enum values −"
},
{
"code": null,
"e": 6162,
"s": 6105,
"text": "denorm_absent, if it does not allow denormalized values."
},
{
"code": null,
"e": 6212,
"s": 6162,
"text": "denorm_present, if it allows denormalized values."
},
{
"code": null,
"e": 6268,
"s": 6212,
"text": "denorm_indeterminate, if indeterminate at compile time."
},
{
"code": null,
"e": 6305,
"s": 6268,
"text": "Minimum positive denormalized value."
},
{
"code": null,
"e": 6370,
"s": 6305,
"text": "It is for types not allowing denormalized values: same as min()."
},
{
"code": null,
"e": 6427,
"s": 6370,
"text": "true if the type adheres to IEC-559 / IEEE-754 standard."
},
{
"code": null,
"e": 6587,
"s": 6427,
"text": "An IEC-559 type always has has_infinity, has_quiet_NaN and has_signaling_NaN set to true; And infinity, quiet_NaN and signaling_NaN return some non-zero value."
},
{
"code": null,
"e": 6662,
"s": 6587,
"text": "It is a rounding style. A type may have any of the following enum values −"
},
{
"code": null,
"e": 6707,
"s": 6662,
"text": "round_toward_zero, if it rounds toward zero."
},
{
"code": null,
"e": 6774,
"s": 6707,
"text": "round_to_nearest, if it rounds to the nearest representable value."
},
{
"code": null,
"e": 6827,
"s": 6774,
"text": "round_toward_infinity, if it rounds toward infinity."
},
{
"code": null,
"e": 6893,
"s": 6827,
"text": "round_toward_neg_infinity, if it rounds toward negative infinity."
},
{
"code": null,
"e": 6971,
"s": 6893,
"text": "round_indeterminate, if the rounding style is indeterminable at compile time."
},
{
"code": null,
"e": 7076,
"s": 6971,
"text": "For all above types that are not fundamental arithmetic types, the default template definition is used −"
},
{
"code": null,
"e": 8414,
"s": 7076,
"text": "template <class T> class numeric_limits {\n public:\n static const bool is_specialized = false;\n static T min() throw();\n static T max() throw();\n static const int digits = 0;\n static const int digits10 = 0;\n static const bool is_signed = false;\n static const bool is_integer = false;\n static const bool is_exact = false;\n static const int radix = 0;\n static T epsilon() throw();\n static T round_error() throw();\n\n static const int min_exponent = 0;\n static const int min_exponent10 = 0;\n static const int max_exponent = 0;\n static const int max_exponent10 = 0;\n\n static const bool has_infinity = false;\n static const bool has_quiet_NaN = false;\n static const bool has_signaling_NaN = false;\n static const float_denorm_style has_denorm = denorm_absent;\n static const bool has_denorm_loss = false;\n static T infinity() throw();\n static T quiet_NaN() throw();\n static T signaling_NaN() throw();\n static T denorm_min() throw();\n\n static const bool is_iec559 = false;\n static const bool is_bounded = false;\n static const bool is_modulo = false;\n\n static const bool traps = false;\n static const bool tinyness_before = false;\n static const float_round_style round_style = round_toward_zero;\n};"
},
{
"code": null,
"e": 10033,
"s": 8414,
"text": "template <class T> class numeric_limits {\n public:\n static constexpr bool is_specialized = false;\n static constexpr T min() noexcept { return T(); }\n static constexpr T max() noexcept { return T(); }\n static constexpr T lowest() noexcept { return T(); }\n static constexpr int digits = 0;\n static constexpr int digits10 = 0;\n static constexpr bool is_signed = false;\n static constexpr bool is_integer = false;\n static constexpr bool is_exact = false;\n static constexpr int radix = 0;\n static constexpr T epsilon() noexcept { return T(); }\n static constexpr T round_error() noexcept { return T(); }\n\n static constexpr int min_exponent = 0;\n static constexpr int min_exponent10 = 0;\n static constexpr int max_exponent = 0;\n static constexpr int max_exponent10 = 0;\n\n static constexpr bool has_infinity = false;\n static constexpr bool has_quiet_NaN = false;\n static constexpr bool has_signaling_NaN = false;\n static constexpr float_denorm_style has_denorm = denorm_absent;\n static constexpr bool has_denorm_loss = false;\n static constexpr T infinity() noexcept { return T(); }\n static constexpr T quiet_NaN() noexcept { return T(); }\n static constexpr T signaling_NaN() noexcept { return T(); }\n static constexpr T denorm_min() noexcept { return T(); }\n\n static constexpr bool is_iec559 = false;\n static constexpr bool is_bounded = false;\n static constexpr bool is_modulo = false;\n\n static constexpr bool traps = false;\n static constexpr bool tinyness_before = false;\n};"
},
{
"code": null,
"e": 10040,
"s": 10033,
"text": " Print"
},
{
"code": null,
"e": 10051,
"s": 10040,
"text": " Add Notes"
}
] |
Find MongoDB documents that contains specific field?
|
To find documents that contain specific field, use $exists. Let us create a collection with documents −
> db.demo247.insertOne({"ClientDetails":[{"ClientFirstName":"Chris","ClientAge":34}]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e46b2a31627c0c63e7dba69")
}
>db.demo247.insertOne({"ClientDetails":[{"ClientFirstName":"John","ClientLastName":"Smith","ClientAge":31}]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e46b2be1627c0c63e7dba6a")
}
> db.demo247.insertOne({"ClientDetails":[{"ClientFirstName":"David","ClientAge":33}]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e46b2cd1627c0c63e7dba6b")
}
>db.demo247.insertOne({"ClientDetails":[{"ClientFirstName":"David","ClientLastName":"Miller","ClientAge":31}]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e46b2de1627c0c63e7dba6c")
}
Display all documents from a collection with the help of find() method −
> db.demo247.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5e46b2a31627c0c63e7dba69"),
"ClientDetails" : [
{
"ClientFirstName" : "Chris",
"ClientAge" : 34
}
]
}
{
"_id" : ObjectId("5e46b2be1627c0c63e7dba6a"),
"ClientDetails" : [
{
"ClientFirstName" : "John",
"ClientLastName" : "Smith",
"ClientAge" : 31
}
]
}
{
"_id" : ObjectId("5e46b2cd1627c0c63e7dba6b"),
"ClientDetails" : [
{
"ClientFirstName" : "David",
"ClientAge" : 33
}
]
}
{
"_id" : ObjectId("5e46b2de1627c0c63e7dba6c"),
"ClientDetails" : [
{
"ClientFirstName" : "David",
"ClientLastName" : "Miller",
"ClientAge" : 31
}
]
}
Following is the query to find documents that contains specific field −
> db.demo247.find({"ClientDetails.ClientLastName":{$exists:true}});
This will produce the following output −
{
"_id" : ObjectId("5e46b2be1627c0c63e7dba6a"), "ClientDetails" : [
{ "ClientFirstName" : "John", "ClientLastName" : "Smith", "ClientAge" : 31 }
]
}
{
"_id" : ObjectId("5e46b2de1627c0c63e7dba6c"), "ClientDetails" : [
{ "ClientFirstName" : "David", "ClientLastName" : "Miller", "ClientAge" : 31 }
]
}
|
[
{
"code": null,
"e": 1166,
"s": 1062,
"text": "To find documents that contain specific field, use $exists. Let us create a collection with documents −"
},
{
"code": null,
"e": 1906,
"s": 1166,
"text": "> db.demo247.insertOne({\"ClientDetails\":[{\"ClientFirstName\":\"Chris\",\"ClientAge\":34}]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e46b2a31627c0c63e7dba69\")\n}\n>db.demo247.insertOne({\"ClientDetails\":[{\"ClientFirstName\":\"John\",\"ClientLastName\":\"Smith\",\"ClientAge\":31}]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e46b2be1627c0c63e7dba6a\")\n}\n> db.demo247.insertOne({\"ClientDetails\":[{\"ClientFirstName\":\"David\",\"ClientAge\":33}]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e46b2cd1627c0c63e7dba6b\")\n}\n>db.demo247.insertOne({\"ClientDetails\":[{\"ClientFirstName\":\"David\",\"ClientLastName\":\"Miller\",\"ClientAge\":31}]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e46b2de1627c0c63e7dba6c\")\n}"
},
{
"code": null,
"e": 1979,
"s": 1906,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 2009,
"s": 1979,
"text": "> db.demo247.find().pretty();"
},
{
"code": null,
"e": 2050,
"s": 2009,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2768,
"s": 2050,
"text": "{\n \"_id\" : ObjectId(\"5e46b2a31627c0c63e7dba69\"),\n \"ClientDetails\" : [\n {\n \"ClientFirstName\" : \"Chris\",\n \"ClientAge\" : 34\n }\n ]\n}\n{\n \"_id\" : ObjectId(\"5e46b2be1627c0c63e7dba6a\"),\n \"ClientDetails\" : [\n {\n \"ClientFirstName\" : \"John\",\n \"ClientLastName\" : \"Smith\",\n \"ClientAge\" : 31\n }\n ]\n}\n{\n \"_id\" : ObjectId(\"5e46b2cd1627c0c63e7dba6b\"),\n \"ClientDetails\" : [\n {\n \"ClientFirstName\" : \"David\",\n \"ClientAge\" : 33\n }\n ]\n}\n{\n \"_id\" : ObjectId(\"5e46b2de1627c0c63e7dba6c\"),\n \"ClientDetails\" : [\n {\n \"ClientFirstName\" : \"David\",\n \"ClientLastName\" : \"Miller\",\n \"ClientAge\" : 31\n }\n ]\n}"
},
{
"code": null,
"e": 2840,
"s": 2768,
"text": "Following is the query to find documents that contains specific field −"
},
{
"code": null,
"e": 2908,
"s": 2840,
"text": "> db.demo247.find({\"ClientDetails.ClientLastName\":{$exists:true}});"
},
{
"code": null,
"e": 2949,
"s": 2908,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3274,
"s": 2949,
"text": "{\n \"_id\" : ObjectId(\"5e46b2be1627c0c63e7dba6a\"), \"ClientDetails\" : [\n { \"ClientFirstName\" : \"John\", \"ClientLastName\" : \"Smith\", \"ClientAge\" : 31 }\n ]\n}\n{\n \"_id\" : ObjectId(\"5e46b2de1627c0c63e7dba6c\"), \"ClientDetails\" : [\n { \"ClientFirstName\" : \"David\", \"ClientLastName\" : \"Miller\", \"ClientAge\" : 31 }\n ] \n}"
}
] |
Python 3 - Tkinter Bitmaps
|
This attribute to displays a bitmap. There are following type of bitmaps available −
"error"
"gray75"
"gray50"
"gray25"
"gray12"
"hourglass"
"info"
"questhead"
"question"
"warning"
# !/usr/bin/python3
from tkinter import *
import tkinter
top = Tk()
B1 = Button(top, text = "error", relief = RAISED,\ bitmap = "error")
B2 = Button(t vcop, text = "hourglass", relief = RAISED,\ bitmap = "hourglass")
B3 = Button(top, text = "info", relief = RAISED,\ bitmap = "info")
B4 = Button(top, text = "question", relief = RAISED,\ bitmap = "question")
B5 = Button(top, text = "warning", relief = RAISED,\ bitmap' = "warning")
B1.pack()
B2.pack()
B3.pack()
B4.pack()
B5.pack()
top.mainloop()
When the above code is executed, it produces the following result −
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": 2426,
"s": 2340,
"text": "This attribute to displays a bitmap. There are following type of bitmaps available −"
},
{
"code": null,
"e": 2434,
"s": 2426,
"text": "\"error\""
},
{
"code": null,
"e": 2443,
"s": 2434,
"text": "\"gray75\""
},
{
"code": null,
"e": 2452,
"s": 2443,
"text": "\"gray50\""
},
{
"code": null,
"e": 2461,
"s": 2452,
"text": "\"gray25\""
},
{
"code": null,
"e": 2470,
"s": 2461,
"text": "\"gray12\""
},
{
"code": null,
"e": 2482,
"s": 2470,
"text": "\"hourglass\""
},
{
"code": null,
"e": 2489,
"s": 2482,
"text": "\"info\""
},
{
"code": null,
"e": 2501,
"s": 2489,
"text": "\"questhead\""
},
{
"code": null,
"e": 2512,
"s": 2501,
"text": "\"question\""
},
{
"code": null,
"e": 2522,
"s": 2512,
"text": "\"warning\""
},
{
"code": null,
"e": 3023,
"s": 2522,
"text": "# !/usr/bin/python3\nfrom tkinter import *\nimport tkinter\n\ntop = Tk()\n\nB1 = Button(top, text = \"error\", relief = RAISED,\\ bitmap = \"error\")\nB2 = Button(t vcop, text = \"hourglass\", relief = RAISED,\\ bitmap = \"hourglass\")\nB3 = Button(top, text = \"info\", relief = RAISED,\\ bitmap = \"info\")\nB4 = Button(top, text = \"question\", relief = RAISED,\\ bitmap = \"question\")\nB5 = Button(top, text = \"warning\", relief = RAISED,\\ bitmap' = \"warning\")\n\nB1.pack()\nB2.pack()\nB3.pack()\nB4.pack()\nB5.pack()\ntop.mainloop()"
},
{
"code": null,
"e": 3091,
"s": 3023,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 3128,
"s": 3091,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3144,
"s": 3128,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3177,
"s": 3144,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3196,
"s": 3177,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3231,
"s": 3196,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3253,
"s": 3231,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3287,
"s": 3253,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3315,
"s": 3287,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3350,
"s": 3315,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3364,
"s": 3350,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3397,
"s": 3364,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3414,
"s": 3397,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3421,
"s": 3414,
"text": " Print"
},
{
"code": null,
"e": 3432,
"s": 3421,
"text": " Add Notes"
}
] |
5 smart Python NumPy functions. Elegant NumPy functions for neat... | by Baijayanta Roy | Towards Data Science
|
In everyday data processing for Machine Learning and Data Science projects, we encounter unique situations, those require boilerplate code to solve the problem. Over the period some of those are converted into base features provided by the core language or the package itself as per need and usage from the community. Here I am sharing 5 elegant python Numpy functions, which can be used for efficient and neat data manipulation.
Numpy allows us to reshape a matrix provided new shape should be compatible with the original shape. One interesting aspect of this new shape is, we can give one of the shape parameters as -1. It simply means that it is an unknown dimension and we want Numpy to figure it out. Numpy will figure this by looking at the ‘length of the array and remaining dimensions’ and making sure it satisfies the above-mentioned criteria. Let’s see one example now.
a = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])a.shape(2, 4)
Suppose we give row as 1 and -1 as column then Numpy will able to find column as 8.
a.reshape(1,-1)array([[1, 2, 3, 4, 5, 6, 7, 8]])
Suppose we give row as -1 and 1 as column then Numpy will able to find row as 8.
a.reshape(-1,1)array([[1], [2], [3], [4], [5], [6], [7], [8]])
Similarly below are possible.
a.reshape(-1,4)array([[1, 2, 3, 4], [5, 6, 7, 8]])a.reshape(-1,2)array([[1, 2], [3, 4], [5, 6], [7, 8]])a.reshape(2,-1)array([[1, 2, 3, 4], [5, 6, 7, 8]])a.reshape(4,-1)array([[1, 2], [3, 4], [5, 6], [7, 8]])
This is also applicable to any higher level tensor reshape as well but only one dimension can be given -1.
a.reshape(2,2,-1)array([[[1, 2], [3, 4]],[[5, 6], [7, 8]]])a.reshape(2,-1,1)array([[[1], [2], [3], [4]],[[5], [6], [7], [8]]])
If we try to reshape a non-compatible shape or more than one unknown shape then there will be an error message.
a.reshape(-1,-1)ValueError: can only specify one unknown dimensiona.reshape(3,-1)ValueError: cannot reshape array of size 8 into shape (3,newaxis)
To summarize, when reshaping an array, the new shape must contain the same number of elements as the old shape, meaning the products of the two shapes’ dimensions must be equal. When using a -1, the dimension corresponding to the -1 will be the product of the dimensions of the original array divided by the product of the dimensions given to reshape to maintain the same number of elements.
Numpy has a function called argpartition which can efficiently find the largest N values index and in-turn N values. It gives index and then you can sort if you need sorted values.
a = np.array([10, 7, 4, 3, 2, 2, 5, 9, 0, 4, 6, 0])index = np.argpartition(a, -5)[-5:]indexarray([ 6, 1, 10, 7, 0], dtype=int64)np.sort(a[index])array([ 5, 6, 7, 9, 10])
In many data problems or algorithms (like PPO in Reinforcement Learning) we need to keep all values within an upper and lower limit. Numpy has a built-in function called Clip that can be used for such purpose. Numpy clip() function is used to Clip (limit) the values in an array. Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of [-1, 1] is specified, values smaller than -1 become -1, and values larger than 1 become 1.
#Example-1a = np.array([10, 7, 4, 3, 2, 2, 5, 9, 0, 4, 6, 0])print (np.clip(a,2,6))[6 6 4 3 2 2 5 6 2 4 6 2]#Example-2a = np.array([10, -1, 4, -3, 2, 2, 5, 9, 0, 4, 6, 0])print (np.clip(a,2,5))[5 2 4 2 2 2 5 5 2 4 5 2]
We can use the Numpy extract() function to extract specific elements from an array that matches the condition.
arr = np.arange(10)arrarray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])# Define the codition, here we take MOD 3 if zerocondition = np.mod(arr, 3)==0conditionarray([ True, False, False, True, False, False, True, False, False,True])np.extract(condition, arr)array([0, 3, 6, 9])
Similarly, we can use direct condition with a combination of AND and OR if required like
np.extract(((arr > 2) & (arr < 8)), arr)array([3, 4, 5, 6, 7])
Return the unique values in an array that are not in present in another array. This is equivalent to a difference of two arrays.
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])b = np.array([3,4,7,6,7,8,11,12,14])c = np.setdiff1d(a,b)carray([1, 2, 5, 9])
These are 5 Numpy functions that are not used frequently by the community but they are neat and elegant. In my view, we should use them whenever there is a similar situation as these provide not just less code but mostly a smart way of achieving a solution for a complex problem.
|
[
{
"code": null,
"e": 602,
"s": 172,
"text": "In everyday data processing for Machine Learning and Data Science projects, we encounter unique situations, those require boilerplate code to solve the problem. Over the period some of those are converted into base features provided by the core language or the package itself as per need and usage from the community. Here I am sharing 5 elegant python Numpy functions, which can be used for efficient and neat data manipulation."
},
{
"code": null,
"e": 1053,
"s": 602,
"text": "Numpy allows us to reshape a matrix provided new shape should be compatible with the original shape. One interesting aspect of this new shape is, we can give one of the shape parameters as -1. It simply means that it is an unknown dimension and we want Numpy to figure it out. Numpy will figure this by looking at the ‘length of the array and remaining dimensions’ and making sure it satisfies the above-mentioned criteria. Let’s see one example now."
},
{
"code": null,
"e": 1122,
"s": 1053,
"text": "a = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])a.shape(2, 4)"
},
{
"code": null,
"e": 1206,
"s": 1122,
"text": "Suppose we give row as 1 and -1 as column then Numpy will able to find column as 8."
},
{
"code": null,
"e": 1255,
"s": 1206,
"text": "a.reshape(1,-1)array([[1, 2, 3, 4, 5, 6, 7, 8]])"
},
{
"code": null,
"e": 1336,
"s": 1255,
"text": "Suppose we give row as -1 and 1 as column then Numpy will able to find row as 8."
},
{
"code": null,
"e": 1441,
"s": 1336,
"text": "a.reshape(-1,1)array([[1], [2], [3], [4], [5], [6], [7], [8]])"
},
{
"code": null,
"e": 1471,
"s": 1441,
"text": "Similarly below are possible."
},
{
"code": null,
"e": 1728,
"s": 1471,
"text": "a.reshape(-1,4)array([[1, 2, 3, 4], [5, 6, 7, 8]])a.reshape(-1,2)array([[1, 2], [3, 4], [5, 6], [7, 8]])a.reshape(2,-1)array([[1, 2, 3, 4], [5, 6, 7, 8]])a.reshape(4,-1)array([[1, 2], [3, 4], [5, 6], [7, 8]])"
},
{
"code": null,
"e": 1835,
"s": 1728,
"text": "This is also applicable to any higher level tensor reshape as well but only one dimension can be given -1."
},
{
"code": null,
"e": 2018,
"s": 1835,
"text": "a.reshape(2,2,-1)array([[[1, 2], [3, 4]],[[5, 6], [7, 8]]])a.reshape(2,-1,1)array([[[1], [2], [3], [4]],[[5], [6], [7], [8]]])"
},
{
"code": null,
"e": 2130,
"s": 2018,
"text": "If we try to reshape a non-compatible shape or more than one unknown shape then there will be an error message."
},
{
"code": null,
"e": 2277,
"s": 2130,
"text": "a.reshape(-1,-1)ValueError: can only specify one unknown dimensiona.reshape(3,-1)ValueError: cannot reshape array of size 8 into shape (3,newaxis)"
},
{
"code": null,
"e": 2669,
"s": 2277,
"text": "To summarize, when reshaping an array, the new shape must contain the same number of elements as the old shape, meaning the products of the two shapes’ dimensions must be equal. When using a -1, the dimension corresponding to the -1 will be the product of the dimensions of the original array divided by the product of the dimensions given to reshape to maintain the same number of elements."
},
{
"code": null,
"e": 2850,
"s": 2669,
"text": "Numpy has a function called argpartition which can efficiently find the largest N values index and in-turn N values. It gives index and then you can sort if you need sorted values."
},
{
"code": null,
"e": 3026,
"s": 2850,
"text": "a = np.array([10, 7, 4, 3, 2, 2, 5, 9, 0, 4, 6, 0])index = np.argpartition(a, -5)[-5:]indexarray([ 6, 1, 10, 7, 0], dtype=int64)np.sort(a[index])array([ 5, 6, 7, 9, 10])"
},
{
"code": null,
"e": 3510,
"s": 3026,
"text": "In many data problems or algorithms (like PPO in Reinforcement Learning) we need to keep all values within an upper and lower limit. Numpy has a built-in function called Clip that can be used for such purpose. Numpy clip() function is used to Clip (limit) the values in an array. Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of [-1, 1] is specified, values smaller than -1 become -1, and values larger than 1 become 1."
},
{
"code": null,
"e": 3729,
"s": 3510,
"text": "#Example-1a = np.array([10, 7, 4, 3, 2, 2, 5, 9, 0, 4, 6, 0])print (np.clip(a,2,6))[6 6 4 3 2 2 5 6 2 4 6 2]#Example-2a = np.array([10, -1, 4, -3, 2, 2, 5, 9, 0, 4, 6, 0])print (np.clip(a,2,5))[5 2 4 2 2 2 5 5 2 4 5 2]"
},
{
"code": null,
"e": 3840,
"s": 3729,
"text": "We can use the Numpy extract() function to extract specific elements from an array that matches the condition."
},
{
"code": null,
"e": 4107,
"s": 3840,
"text": "arr = np.arange(10)arrarray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])# Define the codition, here we take MOD 3 if zerocondition = np.mod(arr, 3)==0conditionarray([ True, False, False, True, False, False, True, False, False,True])np.extract(condition, arr)array([0, 3, 6, 9])"
},
{
"code": null,
"e": 4196,
"s": 4107,
"text": "Similarly, we can use direct condition with a combination of AND and OR if required like"
},
{
"code": null,
"e": 4259,
"s": 4196,
"text": "np.extract(((arr > 2) & (arr < 8)), arr)array([3, 4, 5, 6, 7])"
},
{
"code": null,
"e": 4388,
"s": 4259,
"text": "Return the unique values in an array that are not in present in another array. This is equivalent to a difference of two arrays."
},
{
"code": null,
"e": 4507,
"s": 4388,
"text": "a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])b = np.array([3,4,7,6,7,8,11,12,14])c = np.setdiff1d(a,b)carray([1, 2, 5, 9])"
}
] |
Explore and Visualize your LinkedIn Network with Python and Sentiment Analysis | by Khuyen Tran | Towards Data Science
|
If you are a LinkedIn user, have you ever wondered about the segments of people in your network? If you are working to expand your connections in the data science world, do most of the people in your network work in a data science-related field?
How about your messages? Are they mostly positive and about the topics that are related to your interests?
As an active user on LinkedIn with more than 500 connections, I was curious about the statistics of people in my network as well as the messages I received over the last 2 years.
What is good about analyzing LinkedIn data? Well, if you are optimizing your LinkedIn profile for job opportunities, why not use available data as your tool?
In this article, I will combine visualization and natural language processing to analyze my network and messages. After this article, you should be able to analyze your own LinkedIn data and gain insights from it!
It didn’t take me too much effort to get the data because you can directly download it from LinkedIn. Here is how you can do it.
Specifically, I imported the messages and connections data.
I’m going to be embedding the visualizations from each library using Datapane, which is a Python framework and API for publishing and sharing Python reports. If you want to leave a comment for any of my plot or table below, feel free to click “View full report” in the left corner to leave your comment, and I will get back to you!
Here are the notebooks for this article so you can follow along with the article and visualize your own data!
Start with import and check the data
In the table above, I just show 10 of my latest connections as examples.Connected On indicates the date I connect to that person. I will convert that column into a date-time and visualize it with Plotly
There is a peak in my number of new connections per day, especially from January 2020 to July 2020, the period when I was the most active on LinkedIn.
Which organizations do the people in my network work at? I could use a bar graph like this:
But maybe treemap does a better job to visualize companies in this case?
Treemaps display hierarchical data as a set of nested rectangles. Each group is represented by a rectangle, which area is proportional to its value.
With a treemap, it is easier to compare the proportion of one company related to the others! It looks like a large percentage of the people from my network are from Bayer Crop Science. The second-largest percentage is from my university.
Wow! I wouldn’t expect to see so many data scientists. It is great that the top common positions in my network are my target groups for networking.
Some people might have titles start with ‘data scientist’ but also have more words in their titles. Find out all the positions with words start with ‘Data scientist’
>>> network.Position.str.startswith('Data Scientist').sum()268
It is time to analyze messages! What hidden facts can I discover from 3895 messages over the last 2 years?
There are some interesting columns in this data. Since we are interested in the content of messages, let’s dig deeper into it.
Besides English, some of my messages are Vietnamese and some are other languages (that I had no idea what they mean). Since I just want to analyze English messages, I will use LanguageDetector from spacy_langdetect to extract English messages from the rest.
For example, I will check whether the text ‘This is an English test’ is detected as an English text
{'language': 'en', 'score': 0.9999987378584019}This is an english text. {'language': 'en', 'score': 0.999998324978528}
99% that it is an English test. Let’s try again with a Vietnamese text
{'language': 'vi', 'score': 0.9999995883738908}Đây là Tiếng Việt {'language': 'vi', 'score': 0.9999981449655853}
And it is detected as a Vietnamese! Now let’s use this with the entire message
Awesome! Now we have all the messages in English.
Named entity is a real-world object, such as persons, locations, organizations, products, etc.. For example, is Barack Obama a person’s name or a location? Is New York a location or an organization?
There are many ways to detect named entity, but SpaCy if my favorite tool. Let’s test it out with this message:
"This is amazing Tran, it's wonderful you could experience that part of Mexico. Yes, I was born in Guadalajara, and lived in Morelia when I was a kid. I visited Guanajuato just a couple of times. What is even better, I have been living in Japan and Singapore for many years, and about 6 months in Hà Nội. I was amazed about the tons of similarities between Vietnam and Mexico "
[(Tran, 'ORG'), (Mexico, 'GPE'), (Guadalajara, 'GPE'), (Morelia, 'GPE'), (Guanajuato, 'PERSON'), (Japan, 'GPE'), (Singapore, 'GPE'), (many years, 'DATE'), (about 6 months, 'DATE'), (Hà Nội, 'ORG'), (tons, 'QUANTITY'), (Vietnam, 'GPE'), (Mexico, 'GPE')]
ORG is organization, GPE is geopolitical entity, PERSON is the name of the person, DATE is date entity, and QUANTITY is quantity entity.
displacy.serve(message1, style=’ent’)
We can even also visualize named entity in the sentence
Some of these are not classified correctly such as Tran (a person’s name) or Guanajuato (a location), but most of these are correct! Let’s find the named entity of for all the messages
Most of the named entities in my messages are person entity! This seems like we got a lot of person entity in the messages, but we also should be careful about the correctness of the model. Although most of them are classified correctly, some are not.
What are the most common words in my LinkedIn messages?
Start with some basic data processing
After cleaning our text, let’s visualize what we got
These are the large words are the words we expect to see from LinkedIn messages. We also know that my conversation is really into data. Pretty cool!
What is the sentiment of my LinkedIn messages? I would guess most of them are mostly positive but by what percentage? Since I do not have the training data set available, I am using the pre-trained dataset instead. SentimentIntensityAnalyzer from NLTK is a perfect tool for this.
{'neg': 0.0, 'neu': 0.323, 'pos': 0.677, 'compound': 0.6369}
SentimentIntensityAnalyzer analyses what percentage are neutral, negative, and positive. Compound is the final result of a combination of percentages. Thus, we could create the function to analyze sentiment based on compound
Use this function to predict the sentiment of sample text
>>> predict_sentiment('Negative', 62.9)>>> predict_sentiment('It is super useful')('Positive', 77.3)>>> predict_sentiment('It is just okay')('Positive', 38.8)
This seems to work pretty well! If it doesn’t work as well for your text, find other ways to extract sentiment here.
Now we can apply this to all of our messages
As expected, most of the messages are positive. I couldn’t recall a time when my messages are negative. What are the negative messages and what words made them negative?
Let’s look at some negative words as well as visualize them
>>> sample = list(sentiment_df[sentiment_df['Sentiment'] == 'Negative'].Message)[2]>>> sample'lots code gets shipped w technical debt'
It is negative because of word debt!
What are the indicators of positive words? We take a sample of a positive sentence to find out
The word ‘glad’ makes the sentence more positive!
Congratulations! You have just learned how to analyze your own LinkedIn data or perhaps similar text data with natural language processing. We don’t know what is hidden inside the data until we make an effort to discover it. Analyze your own data and you will be surprised by what you see and well as learning something helpful!
Leave me a comment in any of the plots above if you have any questions! You could find all the plots and tables in the article in this report!
Want to generate your own report on your LinkedIn data? The notebooks for this article could be found here. Be sure to add CSV files in the directory of the notebook and you are ready to analyze!
I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter.
Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:
|
[
{
"code": null,
"e": 292,
"s": 46,
"text": "If you are a LinkedIn user, have you ever wondered about the segments of people in your network? If you are working to expand your connections in the data science world, do most of the people in your network work in a data science-related field?"
},
{
"code": null,
"e": 399,
"s": 292,
"text": "How about your messages? Are they mostly positive and about the topics that are related to your interests?"
},
{
"code": null,
"e": 578,
"s": 399,
"text": "As an active user on LinkedIn with more than 500 connections, I was curious about the statistics of people in my network as well as the messages I received over the last 2 years."
},
{
"code": null,
"e": 736,
"s": 578,
"text": "What is good about analyzing LinkedIn data? Well, if you are optimizing your LinkedIn profile for job opportunities, why not use available data as your tool?"
},
{
"code": null,
"e": 950,
"s": 736,
"text": "In this article, I will combine visualization and natural language processing to analyze my network and messages. After this article, you should be able to analyze your own LinkedIn data and gain insights from it!"
},
{
"code": null,
"e": 1079,
"s": 950,
"text": "It didn’t take me too much effort to get the data because you can directly download it from LinkedIn. Here is how you can do it."
},
{
"code": null,
"e": 1139,
"s": 1079,
"text": "Specifically, I imported the messages and connections data."
},
{
"code": null,
"e": 1471,
"s": 1139,
"text": "I’m going to be embedding the visualizations from each library using Datapane, which is a Python framework and API for publishing and sharing Python reports. If you want to leave a comment for any of my plot or table below, feel free to click “View full report” in the left corner to leave your comment, and I will get back to you!"
},
{
"code": null,
"e": 1581,
"s": 1471,
"text": "Here are the notebooks for this article so you can follow along with the article and visualize your own data!"
},
{
"code": null,
"e": 1618,
"s": 1581,
"text": "Start with import and check the data"
},
{
"code": null,
"e": 1821,
"s": 1618,
"text": "In the table above, I just show 10 of my latest connections as examples.Connected On indicates the date I connect to that person. I will convert that column into a date-time and visualize it with Plotly"
},
{
"code": null,
"e": 1972,
"s": 1821,
"text": "There is a peak in my number of new connections per day, especially from January 2020 to July 2020, the period when I was the most active on LinkedIn."
},
{
"code": null,
"e": 2064,
"s": 1972,
"text": "Which organizations do the people in my network work at? I could use a bar graph like this:"
},
{
"code": null,
"e": 2137,
"s": 2064,
"text": "But maybe treemap does a better job to visualize companies in this case?"
},
{
"code": null,
"e": 2286,
"s": 2137,
"text": "Treemaps display hierarchical data as a set of nested rectangles. Each group is represented by a rectangle, which area is proportional to its value."
},
{
"code": null,
"e": 2524,
"s": 2286,
"text": "With a treemap, it is easier to compare the proportion of one company related to the others! It looks like a large percentage of the people from my network are from Bayer Crop Science. The second-largest percentage is from my university."
},
{
"code": null,
"e": 2672,
"s": 2524,
"text": "Wow! I wouldn’t expect to see so many data scientists. It is great that the top common positions in my network are my target groups for networking."
},
{
"code": null,
"e": 2838,
"s": 2672,
"text": "Some people might have titles start with ‘data scientist’ but also have more words in their titles. Find out all the positions with words start with ‘Data scientist’"
},
{
"code": null,
"e": 2901,
"s": 2838,
"text": ">>> network.Position.str.startswith('Data Scientist').sum()268"
},
{
"code": null,
"e": 3008,
"s": 2901,
"text": "It is time to analyze messages! What hidden facts can I discover from 3895 messages over the last 2 years?"
},
{
"code": null,
"e": 3135,
"s": 3008,
"text": "There are some interesting columns in this data. Since we are interested in the content of messages, let’s dig deeper into it."
},
{
"code": null,
"e": 3393,
"s": 3135,
"text": "Besides English, some of my messages are Vietnamese and some are other languages (that I had no idea what they mean). Since I just want to analyze English messages, I will use LanguageDetector from spacy_langdetect to extract English messages from the rest."
},
{
"code": null,
"e": 3493,
"s": 3393,
"text": "For example, I will check whether the text ‘This is an English test’ is detected as an English text"
},
{
"code": null,
"e": 3612,
"s": 3493,
"text": "{'language': 'en', 'score': 0.9999987378584019}This is an english text. {'language': 'en', 'score': 0.999998324978528}"
},
{
"code": null,
"e": 3683,
"s": 3612,
"text": "99% that it is an English test. Let’s try again with a Vietnamese text"
},
{
"code": null,
"e": 3802,
"s": 3683,
"text": "{'language': 'vi', 'score': 0.9999995883738908}Đây là Tiếng Việt {'language': 'vi', 'score': 0.9999981449655853}"
},
{
"code": null,
"e": 3881,
"s": 3802,
"text": "And it is detected as a Vietnamese! Now let’s use this with the entire message"
},
{
"code": null,
"e": 3931,
"s": 3881,
"text": "Awesome! Now we have all the messages in English."
},
{
"code": null,
"e": 4130,
"s": 3931,
"text": "Named entity is a real-world object, such as persons, locations, organizations, products, etc.. For example, is Barack Obama a person’s name or a location? Is New York a location or an organization?"
},
{
"code": null,
"e": 4242,
"s": 4130,
"text": "There are many ways to detect named entity, but SpaCy if my favorite tool. Let’s test it out with this message:"
},
{
"code": null,
"e": 4623,
"s": 4242,
"text": "\"This is amazing Tran, it's wonderful you could experience that part of Mexico. Yes, I was born in Guadalajara, and lived in Morelia when I was a kid. I visited Guanajuato just a couple of times. What is even better, I have been living in Japan and Singapore for many years, and about 6 months in Hà Nội. I was amazed about the tons of similarities between Vietnam and Mexico \""
},
{
"code": null,
"e": 4879,
"s": 4623,
"text": "[(Tran, 'ORG'), (Mexico, 'GPE'), (Guadalajara, 'GPE'), (Morelia, 'GPE'), (Guanajuato, 'PERSON'), (Japan, 'GPE'), (Singapore, 'GPE'), (many years, 'DATE'), (about 6 months, 'DATE'), (Hà Nội, 'ORG'), (tons, 'QUANTITY'), (Vietnam, 'GPE'), (Mexico, 'GPE')]"
},
{
"code": null,
"e": 5016,
"s": 4879,
"text": "ORG is organization, GPE is geopolitical entity, PERSON is the name of the person, DATE is date entity, and QUANTITY is quantity entity."
},
{
"code": null,
"e": 5054,
"s": 5016,
"text": "displacy.serve(message1, style=’ent’)"
},
{
"code": null,
"e": 5110,
"s": 5054,
"text": "We can even also visualize named entity in the sentence"
},
{
"code": null,
"e": 5295,
"s": 5110,
"text": "Some of these are not classified correctly such as Tran (a person’s name) or Guanajuato (a location), but most of these are correct! Let’s find the named entity of for all the messages"
},
{
"code": null,
"e": 5547,
"s": 5295,
"text": "Most of the named entities in my messages are person entity! This seems like we got a lot of person entity in the messages, but we also should be careful about the correctness of the model. Although most of them are classified correctly, some are not."
},
{
"code": null,
"e": 5603,
"s": 5547,
"text": "What are the most common words in my LinkedIn messages?"
},
{
"code": null,
"e": 5641,
"s": 5603,
"text": "Start with some basic data processing"
},
{
"code": null,
"e": 5694,
"s": 5641,
"text": "After cleaning our text, let’s visualize what we got"
},
{
"code": null,
"e": 5843,
"s": 5694,
"text": "These are the large words are the words we expect to see from LinkedIn messages. We also know that my conversation is really into data. Pretty cool!"
},
{
"code": null,
"e": 6123,
"s": 5843,
"text": "What is the sentiment of my LinkedIn messages? I would guess most of them are mostly positive but by what percentage? Since I do not have the training data set available, I am using the pre-trained dataset instead. SentimentIntensityAnalyzer from NLTK is a perfect tool for this."
},
{
"code": null,
"e": 6184,
"s": 6123,
"text": "{'neg': 0.0, 'neu': 0.323, 'pos': 0.677, 'compound': 0.6369}"
},
{
"code": null,
"e": 6409,
"s": 6184,
"text": "SentimentIntensityAnalyzer analyses what percentage are neutral, negative, and positive. Compound is the final result of a combination of percentages. Thus, we could create the function to analyze sentiment based on compound"
},
{
"code": null,
"e": 6467,
"s": 6409,
"text": "Use this function to predict the sentiment of sample text"
},
{
"code": null,
"e": 6626,
"s": 6467,
"text": ">>> predict_sentiment('Negative', 62.9)>>> predict_sentiment('It is super useful')('Positive', 77.3)>>> predict_sentiment('It is just okay')('Positive', 38.8)"
},
{
"code": null,
"e": 6743,
"s": 6626,
"text": "This seems to work pretty well! If it doesn’t work as well for your text, find other ways to extract sentiment here."
},
{
"code": null,
"e": 6788,
"s": 6743,
"text": "Now we can apply this to all of our messages"
},
{
"code": null,
"e": 6958,
"s": 6788,
"text": "As expected, most of the messages are positive. I couldn’t recall a time when my messages are negative. What are the negative messages and what words made them negative?"
},
{
"code": null,
"e": 7018,
"s": 6958,
"text": "Let’s look at some negative words as well as visualize them"
},
{
"code": null,
"e": 7153,
"s": 7018,
"text": ">>> sample = list(sentiment_df[sentiment_df['Sentiment'] == 'Negative'].Message)[2]>>> sample'lots code gets shipped w technical debt'"
},
{
"code": null,
"e": 7190,
"s": 7153,
"text": "It is negative because of word debt!"
},
{
"code": null,
"e": 7285,
"s": 7190,
"text": "What are the indicators of positive words? We take a sample of a positive sentence to find out"
},
{
"code": null,
"e": 7335,
"s": 7285,
"text": "The word ‘glad’ makes the sentence more positive!"
},
{
"code": null,
"e": 7664,
"s": 7335,
"text": "Congratulations! You have just learned how to analyze your own LinkedIn data or perhaps similar text data with natural language processing. We don’t know what is hidden inside the data until we make an effort to discover it. Analyze your own data and you will be surprised by what you see and well as learning something helpful!"
},
{
"code": null,
"e": 7807,
"s": 7664,
"text": "Leave me a comment in any of the plots above if you have any questions! You could find all the plots and tables in the article in this report!"
},
{
"code": null,
"e": 8003,
"s": 7807,
"text": "Want to generate your own report on your LinkedIn data? The notebooks for this article could be found here. Be sure to add CSV files in the directory of the notebook and you are ready to analyze!"
},
{
"code": null,
"e": 8163,
"s": 8003,
"text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter."
}
] |
Jupyter Lab: Evolution of the Jupyter Notebook | by Parul Pandey | Towards Data Science
|
All good things (must) come to an end to make way for something better.
Data says there are more than three million Jupyter Notebooks available publicly on Github. There is roughly a similar number of private ones too. Even without this data, we are quite aware of the popularity of the notebooks in the Data Science domain. The possibility of writing codes, inspecting the results, getting rich outputs are some of the features that really made Jupyter Notebooks very popular. But as it is said that all good things (must) come to an end, so will our favourite Notebook too. JupyterLab will eventually replace the classic Jupyter Notebook but for good.
Some time back I published a guide on using Classic Jupyter Notebooks effectively. But as will be seen, JupyterLab is the next-generation user interface for Project Jupyter offering all the familiar building blocks of the classic Jupyter Notebook (notebook, terminal, text editor, file browser, rich outputs, etc.) in a flexible and a more powerful user interface. The basic idea of the Jupyter Lab is to bring all the building blocks that are in the classic notebook, plus some new stuff, under one roof.
InstallationInterfaceCreating and Saving FilesFlexible LayoutsEnhanced Notebook FunctionalitySupported File FormatsInteractive ComputingExtensionsConclusion
Installation
Interface
Creating and Saving Files
Flexible Layouts
Enhanced Notebook Functionality
Supported File Formats
Interactive Computing
Extensions
Conclusion
In case you are completely unfamiliar with Jupyter Lab, you can start reading the article right from Installation. But if you have already worked with them and want an advanced overview, skip the first four parts and jump straight to part 5 making sure that you are using the latest release.
JupyterLab can be installed using conda, pip or pipenv.
#condaconda install -c conda-forge jupyterlab#pippip install jupyterlab#pipenvpipenv install jupyterlabpipenv shell
Have a look at the official installation documentation for more details.
You can start the Jupyter by simply typing the following at the console:
jupyter lab
JupyterLab will open automatically in the browser with an interface resembling the one below. This means everything is in place and you are good to go.
Since I use both Python and R in Jupyter Lab, my worksheet has icons for both of them.
🔝
Let’s understand a bit about the interface before working with its various functionalities.
Menu Bar
The Menu Bar has the top-level menus that showcase the various actions that are available in Jupyter Lab.
Left Sidebar
This consists of the commonly-used tabs. The left sidebar can be collapsed or expanded by selecting Show Left Sidebar in the View menu or by clicking on the active sidebar tab.
You can view the running session from the Running palette while the Commands palette lets you search for all the commands that are available.
Main Work Area
This is the area where the actual activity takes place. It comprises of the notebooks, documents, consoles, terminals etc. Just double click or drag a file on to this area to start working. Workspaces can be saved on the server with named workspace URLs.
Also, you can switch between the classic Notebook view and the JupyterLab view by changing the lab to tree in the url of the Jupyter Lab.
🔝
In this section, we will quickly see how to work with files in Jupyter Lab.
Simply click on the + icon in the main menu. This opens a new Launcher tab in the main work area could enabling us to create a Notebook, Console, terminal or text editor. The same action can also be achieved by using the File tab. Once opened, the files can be renamed and even downloaded.
Opening files is a very straightforward process. Either double click on them or access them through the upper File Tab.
🔝
These were just the basics of Jupyter Lab , essentially to get started. Now let’s move on to the part where we discuss its real capabilities and what makes it superior to classic Notebooks.
The classic Jupyter Notebook also supports an inbuilt Text Editor and a Terminal but these options aren’t used much since they are mostly hidden from sight. Another reason is that all these components work as standalone features and not integrated.
Jupyter Lab tends to plug this pain area by integrating all the features into a single interactive and collaborative environment.
Notebooks
The notebook document format used in JupyterLab is the same as in the classic Jupyter Notebook. The existing notebooks should open correctly in JupyterLab and we can do our regular analysis in there.
Console
There are consoles for people who are used to a QT console type environment. These consoles enable us to run code interactively in a kernel.
Text Editor
The text editor makes it possible to edit the files. The text editor includes syntax highlighting, configurable indentation (tabs or spaces), key maps and basic theming. These settings can be found in the Settings menu.
Terminal
JupyterLab terminal provides full support for system shells (bash, tsch, etc.) on Mac/Linux and PowerShell on Windows. We can run anything in our system shell with a terminal, including programs such as vim or emacs.
Now, one would say that all these features were present in the classic notebook too so what makes Jupyter Lab different. The fact that it gives us a very flexible layout system which allows us to take these tabs, drag them side-by-side and resize them with almost unlimited flexibility is something that was missing earlier.
🔝
Jupyter lab is not a reimplementation of the notebook format but just a new front-end that exists on top of all of the existing architecture. However, this new front end implementation has made it possible to include features that we missed in the classic notebooks. Some of the features are:
The text editors now have the code autocompletion feature. However, as of now, it is only enabled when there is an attached console to the text editor.
There are themes available for the JupyterLab as a whole and for the Text Editors as well.
🔝
Jupyter Lab also supports other formats like :
Images: jpeg, png etc and Gifs
geojson
Vegalite files, geojson files,
PDF Documents
High-Performance CSV viewer
A Jupyter Lab can basically render arbitrarily large CSVs s which are typically rendered as unresponsive in Excel. It is not very interactive as yet but some improvements may be expected soon.
🔝
The real capabilities of Jupyter Lie in the fact that it supports interactive computing which is very useful in Data Science particularly.
I’ll be using the Lorenz differential equations notebook from the official Jupyter Github page. After running a few cells, we get the interactive Lorenz attractor as the output. Sometimes when we have an interactive output, it gets kind of frustrating having to scroll up and down to the code that generates it. As a solution to this problem, Jupyter Lab gives us an option to break the output into a new tab and we have a kind of pseudo dashboard where we can use the sliders and change the parameters.
Sometimes our notebook is too long and so we can have two views of the same(or different) notebooks in a single instance. This could be useful when we want to look at the top and bottom of the notebook at the same time.
We know the cells can be dragged within a notebook. However, the cells can also be dragged across different Notebooks. Also, the changes in one Notebook is reflected into the other as well.
It is rightly said that Code is read more often than it is written. Documentation is a very important aspect of programming and Jupyter Lab tends to make it easier. One of the problems that I really face when writing documentation in a markdown file is that I have to run the code in a different console to check if it is running perfectly and then include it in the file. Switching tabs, again and again, is annoying.
Jupyter Labs lets you combine the editor and console into a single view. So you can check your code and your documentation and preview the entire file at the same time.
🔝
JupyterLab has been designed as an essentially extensible environment. The extensions are really powerful tools that can really enhance a person’s productivity. JupyterLab extensions are npm packages (the standard package format in Javascript development). There are many community-developed extensions being built on GitHub. You can search for the GitHub topic jupyterlab-extension to find extensions.
In order to install JupyterLab extensions, you need to have Node.js installed which can either be installed from their website or as follows.
conda install -c conda-forge nodejsorbrew install node
New extensions can be installed by using the following command:
jupyter labextension install <my-extension>
where where my-extension is the name of a valid JupyterLab extension npm package on npm. Use the my-extension@version syntax to install a specific version of an extension, for example:
jupyter labextension install my-extension@1.2.3
For more details, please refer to the official documentation on extensions. Let’s talk about a few extensions which I use a lot and are really powerful:
Google Drive Extension
This extension adds a Google Drive file browser to the left side panel of JupyterLab. When you are logged into your Google account, you will have the files stored in it available to JupyterLab.
Installation
jupyter labextension install @jupyterlab/google-drive
Apart from installing the extension, you will also have to authenticate your JupyterLab deployment with Google. Go through the setup file or the link here for the process. You will get a client ID which you will have to manually enter.
Usage
Now, if someone shares a notebook or a markdown file, it will reflect in the shared with me folder in Jupyter Lab. We can open and edit it there itself.
Github Extension
It is a JupyterLab extension for accessing GitHub repositories. This extension allows us to select GitHub organizations and users, browse their repositories, and open the files in those repositories. If those files are notebooks, we can run them just as we would run any other notebook.
Installation
jupyter labextension install @jupyterlab/github
After installation, we need to get the credentials from GitHub. For more details please read the instructions here.
Usage
Git Extension
jupyterlab-git is a JupyterLab extension for version control using git.
Installation
To install perform the following steps:
jupyter labextension install @jupyterlab/gitpip install jupyterlab-gitjupyter serverextension enable --py jupyterlab_git
Usage
Drawio Plugin
Drawio plugin is a JupyterLab extension for standalone integration of drawio into Jupyterlab. draw.io is a free online diagram software for making flowcharts, process diagrams, org charts, UML, ER and network diagrams.
Installation
jupyter labextension install jupyterlab-drawio
Usage
These extensions really make the JupyterLab stand out. Having all the tools in a single workplace makes it very useful since one doesn’t have to switch between different environments to get the things done. Apart from the above extensions there are many others and feel free to try them out too.
🔝
JupyterLab is truly the next-generation web-based user interface. It is loaded with tools for interactive computing and well-designed interface that allows users to combine them in novel ways. It is really powerful and provides a great variety of robust tools which will make the Data Analysis process much smoother and definitely more productive.
|
[
{
"code": null,
"e": 244,
"s": 172,
"text": "All good things (must) come to an end to make way for something better."
},
{
"code": null,
"e": 826,
"s": 244,
"text": "Data says there are more than three million Jupyter Notebooks available publicly on Github. There is roughly a similar number of private ones too. Even without this data, we are quite aware of the popularity of the notebooks in the Data Science domain. The possibility of writing codes, inspecting the results, getting rich outputs are some of the features that really made Jupyter Notebooks very popular. But as it is said that all good things (must) come to an end, so will our favourite Notebook too. JupyterLab will eventually replace the classic Jupyter Notebook but for good."
},
{
"code": null,
"e": 1332,
"s": 826,
"text": "Some time back I published a guide on using Classic Jupyter Notebooks effectively. But as will be seen, JupyterLab is the next-generation user interface for Project Jupyter offering all the familiar building blocks of the classic Jupyter Notebook (notebook, terminal, text editor, file browser, rich outputs, etc.) in a flexible and a more powerful user interface. The basic idea of the Jupyter Lab is to bring all the building blocks that are in the classic notebook, plus some new stuff, under one roof."
},
{
"code": null,
"e": 1489,
"s": 1332,
"text": "InstallationInterfaceCreating and Saving FilesFlexible LayoutsEnhanced Notebook FunctionalitySupported File FormatsInteractive ComputingExtensionsConclusion"
},
{
"code": null,
"e": 1502,
"s": 1489,
"text": "Installation"
},
{
"code": null,
"e": 1512,
"s": 1502,
"text": "Interface"
},
{
"code": null,
"e": 1538,
"s": 1512,
"text": "Creating and Saving Files"
},
{
"code": null,
"e": 1555,
"s": 1538,
"text": "Flexible Layouts"
},
{
"code": null,
"e": 1587,
"s": 1555,
"text": "Enhanced Notebook Functionality"
},
{
"code": null,
"e": 1610,
"s": 1587,
"text": "Supported File Formats"
},
{
"code": null,
"e": 1632,
"s": 1610,
"text": "Interactive Computing"
},
{
"code": null,
"e": 1643,
"s": 1632,
"text": "Extensions"
},
{
"code": null,
"e": 1654,
"s": 1643,
"text": "Conclusion"
},
{
"code": null,
"e": 1946,
"s": 1654,
"text": "In case you are completely unfamiliar with Jupyter Lab, you can start reading the article right from Installation. But if you have already worked with them and want an advanced overview, skip the first four parts and jump straight to part 5 making sure that you are using the latest release."
},
{
"code": null,
"e": 2002,
"s": 1946,
"text": "JupyterLab can be installed using conda, pip or pipenv."
},
{
"code": null,
"e": 2118,
"s": 2002,
"text": "#condaconda install -c conda-forge jupyterlab#pippip install jupyterlab#pipenvpipenv install jupyterlabpipenv shell"
},
{
"code": null,
"e": 2191,
"s": 2118,
"text": "Have a look at the official installation documentation for more details."
},
{
"code": null,
"e": 2264,
"s": 2191,
"text": "You can start the Jupyter by simply typing the following at the console:"
},
{
"code": null,
"e": 2276,
"s": 2264,
"text": "jupyter lab"
},
{
"code": null,
"e": 2428,
"s": 2276,
"text": "JupyterLab will open automatically in the browser with an interface resembling the one below. This means everything is in place and you are good to go."
},
{
"code": null,
"e": 2515,
"s": 2428,
"text": "Since I use both Python and R in Jupyter Lab, my worksheet has icons for both of them."
},
{
"code": null,
"e": 2517,
"s": 2515,
"text": "🔝"
},
{
"code": null,
"e": 2609,
"s": 2517,
"text": "Let’s understand a bit about the interface before working with its various functionalities."
},
{
"code": null,
"e": 2618,
"s": 2609,
"text": "Menu Bar"
},
{
"code": null,
"e": 2724,
"s": 2618,
"text": "The Menu Bar has the top-level menus that showcase the various actions that are available in Jupyter Lab."
},
{
"code": null,
"e": 2737,
"s": 2724,
"text": "Left Sidebar"
},
{
"code": null,
"e": 2914,
"s": 2737,
"text": "This consists of the commonly-used tabs. The left sidebar can be collapsed or expanded by selecting Show Left Sidebar in the View menu or by clicking on the active sidebar tab."
},
{
"code": null,
"e": 3056,
"s": 2914,
"text": "You can view the running session from the Running palette while the Commands palette lets you search for all the commands that are available."
},
{
"code": null,
"e": 3071,
"s": 3056,
"text": "Main Work Area"
},
{
"code": null,
"e": 3326,
"s": 3071,
"text": "This is the area where the actual activity takes place. It comprises of the notebooks, documents, consoles, terminals etc. Just double click or drag a file on to this area to start working. Workspaces can be saved on the server with named workspace URLs."
},
{
"code": null,
"e": 3464,
"s": 3326,
"text": "Also, you can switch between the classic Notebook view and the JupyterLab view by changing the lab to tree in the url of the Jupyter Lab."
},
{
"code": null,
"e": 3466,
"s": 3464,
"text": "🔝"
},
{
"code": null,
"e": 3542,
"s": 3466,
"text": "In this section, we will quickly see how to work with files in Jupyter Lab."
},
{
"code": null,
"e": 3832,
"s": 3542,
"text": "Simply click on the + icon in the main menu. This opens a new Launcher tab in the main work area could enabling us to create a Notebook, Console, terminal or text editor. The same action can also be achieved by using the File tab. Once opened, the files can be renamed and even downloaded."
},
{
"code": null,
"e": 3952,
"s": 3832,
"text": "Opening files is a very straightforward process. Either double click on them or access them through the upper File Tab."
},
{
"code": null,
"e": 3954,
"s": 3952,
"text": "🔝"
},
{
"code": null,
"e": 4144,
"s": 3954,
"text": "These were just the basics of Jupyter Lab , essentially to get started. Now let’s move on to the part where we discuss its real capabilities and what makes it superior to classic Notebooks."
},
{
"code": null,
"e": 4393,
"s": 4144,
"text": "The classic Jupyter Notebook also supports an inbuilt Text Editor and a Terminal but these options aren’t used much since they are mostly hidden from sight. Another reason is that all these components work as standalone features and not integrated."
},
{
"code": null,
"e": 4523,
"s": 4393,
"text": "Jupyter Lab tends to plug this pain area by integrating all the features into a single interactive and collaborative environment."
},
{
"code": null,
"e": 4533,
"s": 4523,
"text": "Notebooks"
},
{
"code": null,
"e": 4733,
"s": 4533,
"text": "The notebook document format used in JupyterLab is the same as in the classic Jupyter Notebook. The existing notebooks should open correctly in JupyterLab and we can do our regular analysis in there."
},
{
"code": null,
"e": 4741,
"s": 4733,
"text": "Console"
},
{
"code": null,
"e": 4882,
"s": 4741,
"text": "There are consoles for people who are used to a QT console type environment. These consoles enable us to run code interactively in a kernel."
},
{
"code": null,
"e": 4894,
"s": 4882,
"text": "Text Editor"
},
{
"code": null,
"e": 5114,
"s": 4894,
"text": "The text editor makes it possible to edit the files. The text editor includes syntax highlighting, configurable indentation (tabs or spaces), key maps and basic theming. These settings can be found in the Settings menu."
},
{
"code": null,
"e": 5123,
"s": 5114,
"text": "Terminal"
},
{
"code": null,
"e": 5340,
"s": 5123,
"text": "JupyterLab terminal provides full support for system shells (bash, tsch, etc.) on Mac/Linux and PowerShell on Windows. We can run anything in our system shell with a terminal, including programs such as vim or emacs."
},
{
"code": null,
"e": 5665,
"s": 5340,
"text": "Now, one would say that all these features were present in the classic notebook too so what makes Jupyter Lab different. The fact that it gives us a very flexible layout system which allows us to take these tabs, drag them side-by-side and resize them with almost unlimited flexibility is something that was missing earlier."
},
{
"code": null,
"e": 5667,
"s": 5665,
"text": "🔝"
},
{
"code": null,
"e": 5960,
"s": 5667,
"text": "Jupyter lab is not a reimplementation of the notebook format but just a new front-end that exists on top of all of the existing architecture. However, this new front end implementation has made it possible to include features that we missed in the classic notebooks. Some of the features are:"
},
{
"code": null,
"e": 6112,
"s": 5960,
"text": "The text editors now have the code autocompletion feature. However, as of now, it is only enabled when there is an attached console to the text editor."
},
{
"code": null,
"e": 6203,
"s": 6112,
"text": "There are themes available for the JupyterLab as a whole and for the Text Editors as well."
},
{
"code": null,
"e": 6205,
"s": 6203,
"text": "🔝"
},
{
"code": null,
"e": 6252,
"s": 6205,
"text": "Jupyter Lab also supports other formats like :"
},
{
"code": null,
"e": 6283,
"s": 6252,
"text": "Images: jpeg, png etc and Gifs"
},
{
"code": null,
"e": 6291,
"s": 6283,
"text": "geojson"
},
{
"code": null,
"e": 6322,
"s": 6291,
"text": "Vegalite files, geojson files,"
},
{
"code": null,
"e": 6336,
"s": 6322,
"text": "PDF Documents"
},
{
"code": null,
"e": 6364,
"s": 6336,
"text": "High-Performance CSV viewer"
},
{
"code": null,
"e": 6557,
"s": 6364,
"text": "A Jupyter Lab can basically render arbitrarily large CSVs s which are typically rendered as unresponsive in Excel. It is not very interactive as yet but some improvements may be expected soon."
},
{
"code": null,
"e": 6559,
"s": 6557,
"text": "🔝"
},
{
"code": null,
"e": 6698,
"s": 6559,
"text": "The real capabilities of Jupyter Lie in the fact that it supports interactive computing which is very useful in Data Science particularly."
},
{
"code": null,
"e": 7202,
"s": 6698,
"text": "I’ll be using the Lorenz differential equations notebook from the official Jupyter Github page. After running a few cells, we get the interactive Lorenz attractor as the output. Sometimes when we have an interactive output, it gets kind of frustrating having to scroll up and down to the code that generates it. As a solution to this problem, Jupyter Lab gives us an option to break the output into a new tab and we have a kind of pseudo dashboard where we can use the sliders and change the parameters."
},
{
"code": null,
"e": 7422,
"s": 7202,
"text": "Sometimes our notebook is too long and so we can have two views of the same(or different) notebooks in a single instance. This could be useful when we want to look at the top and bottom of the notebook at the same time."
},
{
"code": null,
"e": 7612,
"s": 7422,
"text": "We know the cells can be dragged within a notebook. However, the cells can also be dragged across different Notebooks. Also, the changes in one Notebook is reflected into the other as well."
},
{
"code": null,
"e": 8031,
"s": 7612,
"text": "It is rightly said that Code is read more often than it is written. Documentation is a very important aspect of programming and Jupyter Lab tends to make it easier. One of the problems that I really face when writing documentation in a markdown file is that I have to run the code in a different console to check if it is running perfectly and then include it in the file. Switching tabs, again and again, is annoying."
},
{
"code": null,
"e": 8200,
"s": 8031,
"text": "Jupyter Labs lets you combine the editor and console into a single view. So you can check your code and your documentation and preview the entire file at the same time."
},
{
"code": null,
"e": 8202,
"s": 8200,
"text": "🔝"
},
{
"code": null,
"e": 8605,
"s": 8202,
"text": "JupyterLab has been designed as an essentially extensible environment. The extensions are really powerful tools that can really enhance a person’s productivity. JupyterLab extensions are npm packages (the standard package format in Javascript development). There are many community-developed extensions being built on GitHub. You can search for the GitHub topic jupyterlab-extension to find extensions."
},
{
"code": null,
"e": 8747,
"s": 8605,
"text": "In order to install JupyterLab extensions, you need to have Node.js installed which can either be installed from their website or as follows."
},
{
"code": null,
"e": 8802,
"s": 8747,
"text": "conda install -c conda-forge nodejsorbrew install node"
},
{
"code": null,
"e": 8866,
"s": 8802,
"text": "New extensions can be installed by using the following command:"
},
{
"code": null,
"e": 8910,
"s": 8866,
"text": "jupyter labextension install <my-extension>"
},
{
"code": null,
"e": 9095,
"s": 8910,
"text": "where where my-extension is the name of a valid JupyterLab extension npm package on npm. Use the my-extension@version syntax to install a specific version of an extension, for example:"
},
{
"code": null,
"e": 9143,
"s": 9095,
"text": "jupyter labextension install my-extension@1.2.3"
},
{
"code": null,
"e": 9296,
"s": 9143,
"text": "For more details, please refer to the official documentation on extensions. Let’s talk about a few extensions which I use a lot and are really powerful:"
},
{
"code": null,
"e": 9319,
"s": 9296,
"text": "Google Drive Extension"
},
{
"code": null,
"e": 9513,
"s": 9319,
"text": "This extension adds a Google Drive file browser to the left side panel of JupyterLab. When you are logged into your Google account, you will have the files stored in it available to JupyterLab."
},
{
"code": null,
"e": 9526,
"s": 9513,
"text": "Installation"
},
{
"code": null,
"e": 9580,
"s": 9526,
"text": "jupyter labextension install @jupyterlab/google-drive"
},
{
"code": null,
"e": 9816,
"s": 9580,
"text": "Apart from installing the extension, you will also have to authenticate your JupyterLab deployment with Google. Go through the setup file or the link here for the process. You will get a client ID which you will have to manually enter."
},
{
"code": null,
"e": 9822,
"s": 9816,
"text": "Usage"
},
{
"code": null,
"e": 9975,
"s": 9822,
"text": "Now, if someone shares a notebook or a markdown file, it will reflect in the shared with me folder in Jupyter Lab. We can open and edit it there itself."
},
{
"code": null,
"e": 9992,
"s": 9975,
"text": "Github Extension"
},
{
"code": null,
"e": 10279,
"s": 9992,
"text": "It is a JupyterLab extension for accessing GitHub repositories. This extension allows us to select GitHub organizations and users, browse their repositories, and open the files in those repositories. If those files are notebooks, we can run them just as we would run any other notebook."
},
{
"code": null,
"e": 10292,
"s": 10279,
"text": "Installation"
},
{
"code": null,
"e": 10340,
"s": 10292,
"text": "jupyter labextension install @jupyterlab/github"
},
{
"code": null,
"e": 10456,
"s": 10340,
"text": "After installation, we need to get the credentials from GitHub. For more details please read the instructions here."
},
{
"code": null,
"e": 10462,
"s": 10456,
"text": "Usage"
},
{
"code": null,
"e": 10476,
"s": 10462,
"text": "Git Extension"
},
{
"code": null,
"e": 10548,
"s": 10476,
"text": "jupyterlab-git is a JupyterLab extension for version control using git."
},
{
"code": null,
"e": 10561,
"s": 10548,
"text": "Installation"
},
{
"code": null,
"e": 10601,
"s": 10561,
"text": "To install perform the following steps:"
},
{
"code": null,
"e": 10722,
"s": 10601,
"text": "jupyter labextension install @jupyterlab/gitpip install jupyterlab-gitjupyter serverextension enable --py jupyterlab_git"
},
{
"code": null,
"e": 10728,
"s": 10722,
"text": "Usage"
},
{
"code": null,
"e": 10742,
"s": 10728,
"text": "Drawio Plugin"
},
{
"code": null,
"e": 10961,
"s": 10742,
"text": "Drawio plugin is a JupyterLab extension for standalone integration of drawio into Jupyterlab. draw.io is a free online diagram software for making flowcharts, process diagrams, org charts, UML, ER and network diagrams."
},
{
"code": null,
"e": 10974,
"s": 10961,
"text": "Installation"
},
{
"code": null,
"e": 11021,
"s": 10974,
"text": "jupyter labextension install jupyterlab-drawio"
},
{
"code": null,
"e": 11027,
"s": 11021,
"text": "Usage"
},
{
"code": null,
"e": 11323,
"s": 11027,
"text": "These extensions really make the JupyterLab stand out. Having all the tools in a single workplace makes it very useful since one doesn’t have to switch between different environments to get the things done. Apart from the above extensions there are many others and feel free to try them out too."
},
{
"code": null,
"e": 11325,
"s": 11323,
"text": "🔝"
}
] |
map::empty() in C++ STL
|
In this article we will be discussing the working, syntax and examples of map::empty() function in C++ STL.
Maps are the associative container, which facilitates to store the elements formed by a combination of key value and mapped value in a specific order. In a map container the data is internally always sorted with the help of its associated keys. The values in the map container are accessed by its unique keys.
map::empty() function is an inbuilt function in C++ STL, which is defined in header file. empty() is used to check whether the associated map container is empty or not
This function checks if the size of the container is 0 then returns true, else if there are some values then it returns false.
map_name.empty();
The function accepts no parameter.
This function returns true if the map is empty and false if it is not.
std::map<int> mymap;
mymap.insert({‘a’, 10});
mymap.insert({‘b’, 20});
mymap.insert({‘c’, 30});
mymap.empty();
false
std::map<int> mymap;
mymap.empty();
true
Live Demo
#include <bits/stdc++.h>
using namespace std;
int main() {
map<int, int> TP_1;
TP_1[1] = 10;
TP_1[2] = 20;
TP_1[3] = 30;
TP_1[4] = 40;
if(TP_1.empty()) {
cout<<"Map is NULL";
} else {
cout<<"Map isn't NULL";
}
return 0;
}
Map isn't NULL
Live Demo
#include <bits/stdc++.h>
using namespace std;
int main() {
map<int, int> TP_1;
map<int, int> TP_2;
TP_1[1] = 10;
TP_1[2] = 20;
TP_1[3] = 30;
TP_1[4] = 40;
if(TP_1.empty()) {
cout<<"Map_1 is NULL";
} else {
cout<<"Map_1 isn't NULL";
}
if(TP_2.empty()) {
cout<<"\nMap_2 is NULL";
} else {
cout<<"Map_2 isn't NULL";
}
return 0;
}
Map_1 isn't NULL
Map_2 is NULL
|
[
{
"code": null,
"e": 1170,
"s": 1062,
"text": "In this article we will be discussing the working, syntax and examples of map::empty() function in C++ STL."
},
{
"code": null,
"e": 1480,
"s": 1170,
"text": "Maps are the associative container, which facilitates to store the elements formed by a combination of key value and mapped value in a specific order. In a map container the data is internally always sorted with the help of its associated keys. The values in the map container are accessed by its unique keys."
},
{
"code": null,
"e": 1649,
"s": 1480,
"text": "map::empty() function is an inbuilt function in C++ STL, which is defined in header file. empty() is used to check whether the associated map container is empty or not"
},
{
"code": null,
"e": 1776,
"s": 1649,
"text": "This function checks if the size of the container is 0 then returns true, else if there are some values then it returns false."
},
{
"code": null,
"e": 1794,
"s": 1776,
"text": "map_name.empty();"
},
{
"code": null,
"e": 1829,
"s": 1794,
"text": "The function accepts no parameter."
},
{
"code": null,
"e": 1900,
"s": 1829,
"text": "This function returns true if the map is empty and false if it is not."
},
{
"code": null,
"e": 2011,
"s": 1900,
"text": "std::map<int> mymap;\nmymap.insert({‘a’, 10});\nmymap.insert({‘b’, 20});\nmymap.insert({‘c’, 30});\nmymap.empty();"
},
{
"code": null,
"e": 2017,
"s": 2011,
"text": "false"
},
{
"code": null,
"e": 2053,
"s": 2017,
"text": "std::map<int> mymap;\nmymap.empty();"
},
{
"code": null,
"e": 2058,
"s": 2053,
"text": "true"
},
{
"code": null,
"e": 2069,
"s": 2058,
"text": " Live Demo"
},
{
"code": null,
"e": 2330,
"s": 2069,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nint main() {\n map<int, int> TP_1;\n TP_1[1] = 10;\n TP_1[2] = 20;\n TP_1[3] = 30;\n TP_1[4] = 40;\n if(TP_1.empty()) {\n cout<<\"Map is NULL\";\n } else {\n cout<<\"Map isn't NULL\";\n }\n return 0;\n}"
},
{
"code": null,
"e": 2345,
"s": 2330,
"text": "Map isn't NULL"
},
{
"code": null,
"e": 2356,
"s": 2345,
"text": " Live Demo"
},
{
"code": null,
"e": 2746,
"s": 2356,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nint main() {\n map<int, int> TP_1;\n map<int, int> TP_2;\n TP_1[1] = 10;\n TP_1[2] = 20;\n TP_1[3] = 30;\n TP_1[4] = 40;\n if(TP_1.empty()) {\n cout<<\"Map_1 is NULL\";\n } else {\n cout<<\"Map_1 isn't NULL\";\n }\n if(TP_2.empty()) {\n cout<<\"\\nMap_2 is NULL\";\n } else {\n cout<<\"Map_2 isn't NULL\";\n }\n return 0;\n}"
},
{
"code": null,
"e": 2777,
"s": 2746,
"text": "Map_1 isn't NULL\nMap_2 is NULL"
}
] |
Sum of the Longest Bloodline of a Tree (Sum of nodes on the longest path from root to leaf node) | Practice | GeeksforGeeks
|
Given a binary tree of size N. Your task is to complete the function sumOfLongRootToLeafPath(), that find the sum of all nodes on the longest path from root to leaf node.
If two or more paths compete for the longest path, then the path having maximum sum of nodes is being considered.
Example 1:
Input:
4
/ \
2 5
/ \ / \
7 1 2 3
/
6
Output: 13
Explanation:
4
/ \
2 5
/ \ / \
7 1 2 3
/
6
The highlighted nodes (4, 2, 1, 6) above are
part of the longest root to leaf path having
sum = (4 + 2 + 1 + 6) = 13
Example 2:
Input:
1
/ \
2 3
/ \ / \
4 5 6 7
Output: 11
Your Task:
You don't need to read input or print anything. Your task is to complete the function sumOfLongRootToLeafPath() which takes root node of the tree as input parameter and returns an integer denoting the sum of the longest root to leaf path of the tree. If the tree is empty, return 0.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)
Constraints:
1 <= Number of nodes <= 104
1 <= Data of a node <= 104
0
abhisoni1313 hours ago
void solve(Node* root , pair<int,int> sum , pair<int,int> &ans) { if(root == NULL ) { return ; }
int curr_data = root->data ; sum.first = sum.first + curr_data ; sum.second = sum.second + 1 ; if(root->left == NULL && root->right == NULL) { if(ans.second <= sum.second ) { ans = make_pair(sum.first , sum.second) ; } } solve(root->left , sum , ans) ; solve(root->right , sum , ans ) ; } int sumOfLongRootToLeafPath(Node *root) { //code here pair<int,int> ans ; ans = make_pair(0,0) ; pair<int,int> sum ; sum = make_pair(0,0) ; solve(root,sum, ans) ; return ans.first ; }
0
aishapervin03
This comment was deleted.
0
tirtha19025684 days ago
class Solution{
int sum = 0;
int len = 0;
public int sumOfLongRootToLeafPath(Node root)
{
if(root == null) return 0;
int currSum = 0;
int currLen = 0;
solve(root,currSum,currLen);
return sum;
}
void solve(Node root,int currSum,int currLen){
// leaf is reached
if(root == null){
if(currLen > len){
len = currLen;
sum = currSum;
}
else if(currLen == len){
sum = Math.max(sum,currSum);
}
return;
}
currSum = currSum + root.data;
solve(root.left,currSum,currLen+1);
solve(root.right,currSum,currLen+1);
}
0
guptatushar110411 week ago
vector<int>solve(Node*root) { if(root==NULL) return{0,0}; vector<int>a=solve(root->left); vector<int>b=solve(root->right); if(a[0]>b[0]) return {a[0]+1,a[1]+root->data}; if(a[0]<b[0]) return {b[0]+1,b[1]+root->data}; else return {a[0]+1,max(a[1],b[1])+root->data}; } int sumOfLongRootToLeafPath(Node *root) { //code here vector<int>ans=solve(root); return ans[1]; }
0
sourabhsuryawanshitigerindia3 weeks ago
C++ || Easy solution || Recursion method
class Solution{public: void solve(Node* root, int len, int &maxlen, int sum, int &maxsum){ // base case if(root == NULL){ if(len > maxlen){ maxlen = len; maxsum =sum; } else if(len == maxlen){ maxsum = max(maxsum, sum); } return; } sum = sum + root -> data; // recursive call solve(root -> left ,len+ 1, maxlen, sum, maxsum); solve(root ->right ,len+ 1, maxlen, sum, maxsum); } int sumOfLongRootToLeafPath(Node *root) { int len = 0; int maxlen = 0; int sum = 0; int maxsum =0; // call function solve(root, len, maxlen,sum, maxsum); return maxsum; }};
0
ruchitchudasama1231 month ago
class Solution
{
public:
void helper(Node* root,int &maxi,int &len,int sum,int level){
if(!root){
if(len<=level){
len=max(level,len);
maxi=max(maxi,sum);
}
return;
}
sum+=root->data;
// cout<<sum<<" "<<root->data<<endl;
// cout<<level<<" "<<len<<endl;
helper(root->left,maxi,len,sum,level+1);
helper(root->right,maxi,len,sum,level+1);
}
int sumOfLongRootToLeafPath(Node *root)
{
int maxi=INT_MIN,len=0;
int sum=0,level=0;
helper(root,maxi,len,sum,level);
return maxi;
}
};
0
2019kucp10851 month ago
//easy cpp code, 0.3s
void helper(Node* root,int len,int sum, int &ml, int &ms)
{
if(root==NULL) return;
if(root->left==NULL && root->right==NULL && sum+root->data>=ms && ml<=len)
{
ms= root->data+sum;
ml= len;
return;
}
helper(root->left,len+1,root->data+sum,ml,ms);
helper(root->right,len+1,root->data+sum,ml,ms);
}
int sumOfLongRootToLeafPath(Node *root)
{
int ml= INT_MIN;
int ms=0;
helper(root,0,0,ml,ms);
return ms;
}
+2
sfazal0001 month ago
int maxSum;int maxLevel;
int solve(node* root ,int level,int sum){ if(root == NULL) { return 0; } sum = sum + root->data; level = level +1; solve(root->left, level, sum); solve(root->right , level,sum); if(level> maxLevel) { maxLevel = level; maxSum = sum; } else if(maxLevel == level) { maxSum = max(maxSum , sum); }}
int MaxPathSum(node* root){ maxSum = INT_MIN; maxLevel = INT_MIN; int sum = 0; int level = 0; solve( root,level, sum); return maxSum;}
0
shrutibhargav402 months ago
class Solution{private: void solve(Node* root, int len, int& maxlen, int sum, int& maxsum){ if(root==NULL){ if(len > maxlen){ maxlen = len; maxsum = max(sum, maxsum); } else if(len == maxlen){ maxsum = max(sum, maxsum); } return; } sum = sum + root->data; solve(root->left, len+1, maxlen, sum, maxsum); solve(root->right, len+1, maxlen, sum, maxsum); } public: int sumOfLongRootToLeafPath(Node *root) { //code here int len = 0; int maxlen = 0; int sum = 0; int maxsum = INT_MIN; solve(root, len, maxlen, sum, maxsum); return maxsum; }};
0
vrajeshmodi992 months ago
void helper(Node*root,vector<pair<int,int>>&v,int level,int sum){
if(!root){
return;
}
if(!root->left && !root->right){
pair<int,int>p;
p = {level,sum+root->data};
v.push_back(p);
return;
}
if(root->left){
helper(root->left,v,level+1,sum+root->data);
}
if(root->right){
helper(root->right,v,level+1,sum+root->data);
}
}
int sumOfLongRootToLeafPath(Node *root)
{
vector<pair<int,int>>v;
helper(root,v,1,0);
sort(v.begin(),v.end());
int n = v.size();
int ans = v[n-1].second;
return ans;
}
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": 523,
"s": 238,
"text": "Given a binary tree of size N. Your task is to complete the function sumOfLongRootToLeafPath(), that find the sum of all nodes on the longest path from root to leaf node.\nIf two or more paths compete for the longest path, then the path having maximum sum of nodes is being considered."
},
{
"code": null,
"e": 534,
"s": 523,
"text": "Example 1:"
},
{
"code": null,
"e": 892,
"s": 534,
"text": "Input: \n 4 \n / \\ \n 2 5 \n / \\ / \\ \n 7 1 2 3 \n /\n 6\nOutput: 13\nExplanation:\n 4 \n / \\ \n 2 5 \n / \\ / \\ \n 7 1 2 3 \n /\n 6\n\nThe highlighted nodes (4, 2, 1, 6) above are \npart of the longest root to leaf path having\nsum = (4 + 2 + 1 + 6) = 13"
},
{
"code": null,
"e": 903,
"s": 892,
"text": "Example 2:"
},
{
"code": null,
"e": 997,
"s": 903,
"text": "Input: \n 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\nOutput: 11\n"
},
{
"code": null,
"e": 1291,
"s": 997,
"text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function sumOfLongRootToLeafPath() which takes root node of the tree as input parameter and returns an integer denoting the sum of the longest root to leaf path of the tree. If the tree is empty, return 0."
},
{
"code": null,
"e": 1353,
"s": 1291,
"text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)"
},
{
"code": null,
"e": 1421,
"s": 1353,
"text": "Constraints:\n1 <= Number of nodes <= 104\n1 <= Data of a node <= 104"
},
{
"code": null,
"e": 1423,
"s": 1421,
"text": "0"
},
{
"code": null,
"e": 1446,
"s": 1423,
"text": "abhisoni1313 hours ago"
},
{
"code": null,
"e": 1580,
"s": 1446,
"text": " void solve(Node* root , pair<int,int> sum , pair<int,int> &ans) { if(root == NULL ) { return ; }"
},
{
"code": null,
"e": 2271,
"s": 1580,
"text": " int curr_data = root->data ; sum.first = sum.first + curr_data ; sum.second = sum.second + 1 ; if(root->left == NULL && root->right == NULL) { if(ans.second <= sum.second ) { ans = make_pair(sum.first , sum.second) ; } } solve(root->left , sum , ans) ; solve(root->right , sum , ans ) ; } int sumOfLongRootToLeafPath(Node *root) { //code here pair<int,int> ans ; ans = make_pair(0,0) ; pair<int,int> sum ; sum = make_pair(0,0) ; solve(root,sum, ans) ; return ans.first ; }"
},
{
"code": null,
"e": 2273,
"s": 2271,
"text": "0"
},
{
"code": null,
"e": 2287,
"s": 2273,
"text": "aishapervin03"
},
{
"code": null,
"e": 2313,
"s": 2287,
"text": "This comment was deleted."
},
{
"code": null,
"e": 2315,
"s": 2313,
"text": "0"
},
{
"code": null,
"e": 2339,
"s": 2315,
"text": "tirtha19025684 days ago"
},
{
"code": null,
"e": 3087,
"s": 2339,
"text": "class Solution{\n int sum = 0;\n int len = 0;\n public int sumOfLongRootToLeafPath(Node root)\n {\n if(root == null) return 0;\n int currSum = 0;\n int currLen = 0;\n solve(root,currSum,currLen);\n return sum;\n }\n \n void solve(Node root,int currSum,int currLen){\n \n // leaf is reached \n if(root == null){\n if(currLen > len){\n len = currLen;\n sum = currSum;\n }\n else if(currLen == len){\n sum = Math.max(sum,currSum);\n }\n return;\n }\n \n currSum = currSum + root.data;\n \n solve(root.left,currSum,currLen+1);\n solve(root.right,currSum,currLen+1);\n \n }\n "
},
{
"code": null,
"e": 3089,
"s": 3087,
"text": "0"
},
{
"code": null,
"e": 3116,
"s": 3089,
"text": "guptatushar110411 week ago"
},
{
"code": null,
"e": 3591,
"s": 3116,
"text": "vector<int>solve(Node*root) { if(root==NULL) return{0,0}; vector<int>a=solve(root->left); vector<int>b=solve(root->right); if(a[0]>b[0]) return {a[0]+1,a[1]+root->data}; if(a[0]<b[0]) return {b[0]+1,b[1]+root->data}; else return {a[0]+1,max(a[1],b[1])+root->data}; } int sumOfLongRootToLeafPath(Node *root) { //code here vector<int>ans=solve(root); return ans[1]; }"
},
{
"code": null,
"e": 3593,
"s": 3591,
"text": "0"
},
{
"code": null,
"e": 3633,
"s": 3593,
"text": "sourabhsuryawanshitigerindia3 weeks ago"
},
{
"code": null,
"e": 3675,
"s": 3633,
"text": "C++ || Easy solution || Recursion method "
},
{
"code": null,
"e": 4444,
"s": 3675,
"text": "class Solution{public: void solve(Node* root, int len, int &maxlen, int sum, int &maxsum){ // base case if(root == NULL){ if(len > maxlen){ maxlen = len; maxsum =sum; } else if(len == maxlen){ maxsum = max(maxsum, sum); } return; } sum = sum + root -> data; // recursive call solve(root -> left ,len+ 1, maxlen, sum, maxsum); solve(root ->right ,len+ 1, maxlen, sum, maxsum); } int sumOfLongRootToLeafPath(Node *root) { int len = 0; int maxlen = 0; int sum = 0; int maxsum =0; // call function solve(root, len, maxlen,sum, maxsum); return maxsum; }};"
},
{
"code": null,
"e": 4446,
"s": 4444,
"text": "0"
},
{
"code": null,
"e": 4476,
"s": 4446,
"text": "ruchitchudasama1231 month ago"
},
{
"code": null,
"e": 5089,
"s": 4476,
"text": "class Solution\n{\npublic:\n\nvoid helper(Node* root,int &maxi,int &len,int sum,int level){\n \n if(!root){\n if(len<=level){\n len=max(level,len);\n maxi=max(maxi,sum);\n }\n return;\n }\n sum+=root->data; \n // cout<<sum<<\" \"<<root->data<<endl;\n // cout<<level<<\" \"<<len<<endl;\n helper(root->left,maxi,len,sum,level+1);\n helper(root->right,maxi,len,sum,level+1);\n \n}\n \n int sumOfLongRootToLeafPath(Node *root)\n {\n int maxi=INT_MIN,len=0;\n int sum=0,level=0;\n helper(root,maxi,len,sum,level);\n return maxi;\n }\n};"
},
{
"code": null,
"e": 5091,
"s": 5089,
"text": "0"
},
{
"code": null,
"e": 5115,
"s": 5091,
"text": "2019kucp10851 month ago"
},
{
"code": null,
"e": 5693,
"s": 5115,
"text": "//easy cpp code, 0.3s\nvoid helper(Node* root,int len,int sum, int &ml, int &ms)\n {\n if(root==NULL) return;\n \n if(root->left==NULL && root->right==NULL && sum+root->data>=ms && ml<=len)\n {\n ms= root->data+sum;\n ml= len;\n return;\n }\n helper(root->left,len+1,root->data+sum,ml,ms);\n helper(root->right,len+1,root->data+sum,ml,ms);\n }\n \n int sumOfLongRootToLeafPath(Node *root)\n {\n int ml= INT_MIN;\n int ms=0;\n helper(root,0,0,ml,ms);\n return ms;\n }"
},
{
"code": null,
"e": 5696,
"s": 5693,
"text": "+2"
},
{
"code": null,
"e": 5717,
"s": 5696,
"text": "sfazal0001 month ago"
},
{
"code": null,
"e": 5742,
"s": 5717,
"text": "int maxSum;int maxLevel;"
},
{
"code": null,
"e": 6096,
"s": 5742,
"text": "int solve(node* root ,int level,int sum){ if(root == NULL) { return 0; } sum = sum + root->data; level = level +1; solve(root->left, level, sum); solve(root->right , level,sum); if(level> maxLevel) { maxLevel = level; maxSum = sum; } else if(maxLevel == level) { maxSum = max(maxSum , sum); }}"
},
{
"code": null,
"e": 6258,
"s": 6098,
"text": "int MaxPathSum(node* root){ maxSum = INT_MIN; maxLevel = INT_MIN; int sum = 0; int level = 0; solve( root,level, sum); return maxSum;} "
},
{
"code": null,
"e": 6260,
"s": 6258,
"text": "0"
},
{
"code": null,
"e": 6288,
"s": 6260,
"text": "shrutibhargav402 months ago"
},
{
"code": null,
"e": 7012,
"s": 6288,
"text": "class Solution{private: void solve(Node* root, int len, int& maxlen, int sum, int& maxsum){ if(root==NULL){ if(len > maxlen){ maxlen = len; maxsum = max(sum, maxsum); } else if(len == maxlen){ maxsum = max(sum, maxsum); } return; } sum = sum + root->data; solve(root->left, len+1, maxlen, sum, maxsum); solve(root->right, len+1, maxlen, sum, maxsum); } public: int sumOfLongRootToLeafPath(Node *root) { //code here int len = 0; int maxlen = 0; int sum = 0; int maxsum = INT_MIN; solve(root, len, maxlen, sum, maxsum); return maxsum; }};"
},
{
"code": null,
"e": 7014,
"s": 7012,
"text": "0"
},
{
"code": null,
"e": 7040,
"s": 7014,
"text": "vrajeshmodi992 months ago"
},
{
"code": null,
"e": 7804,
"s": 7040,
"text": " void helper(Node*root,vector<pair<int,int>>&v,int level,int sum){\n \n if(!root){\n return;\n }\n if(!root->left && !root->right){\n pair<int,int>p;\n p = {level,sum+root->data};\n v.push_back(p);\n return;\n }\n if(root->left){\n helper(root->left,v,level+1,sum+root->data);\n }\n if(root->right){\n helper(root->right,v,level+1,sum+root->data);\n } \n \n }\n \n \n int sumOfLongRootToLeafPath(Node *root)\n {\n vector<pair<int,int>>v;\n helper(root,v,1,0);\n \n sort(v.begin(),v.end());\n int n = v.size();\n int ans = v[n-1].second;\n \n return ans;\n \n }"
},
{
"code": null,
"e": 7950,
"s": 7804,
"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": 7986,
"s": 7950,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 7996,
"s": 7986,
"text": "\nProblem\n"
},
{
"code": null,
"e": 8006,
"s": 7996,
"text": "\nContest\n"
},
{
"code": null,
"e": 8069,
"s": 8006,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 8217,
"s": 8069,
"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": 8425,
"s": 8217,
"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": 8531,
"s": 8425,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Array setChar() method in Java - GeeksforGeeks
|
30 Nov, 2018
The java.lang.reflect.Array.setChar() is an inbuilt method in Java and is used to change a specified char value to a specified index of a given object array.
Syntax:
Array.setChar(Object []array, int index, char value)
Parameter: This method takes three parameters:
array: This is an array of type Object which is to be updated.
index: This is the index of the array which is to be updated.
value: This is the char value that is to be set at the given index of the given array.
Return Value: This method has a void return type. Hence this doesn’t returns any value. The update reflects upon the Object array passed as the argument.
Exceptions: This method throws following exception:
NullPointerException– when the array is null.
IllegalArgumentException– when the given object array is not an Array.
ArrayIndexOutOfBoundsException– if the given index is not in the range of the size of the array.Below is the implementation of Array.setChar() method:Program 1:// Java code to demonstrate setChar()// method of Array class import java.lang.reflect.Array; public class GfG { // main method public static void main(String[] args) { // Declaring and defining char array char ch[] = { 'a', 'b', 'c', 'd', 'e' }; System.out.print("Before Set : "); // printing the array for (char x : ch) { System.out.print(x + " "); } char value = 'g'; // setChar method of class Array Array.setChar(ch, 1, value); System.out.print("\nAfter Set : "); // printing array for (char x : ch) { System.out.print(x + " "); } }}Output:Before Set : a b c d e
After Set : a g c d e
Program 2: To demonstrate java.lang.NullPointerException// Java code to demonstrate setChar()// method of Array class import java.lang.reflect.Array; public class GfG { // main method public static void main(String[] args) { // Declaring and defining char array to null char b[] = null; try { char c = 'a'; // Passing null array in parameter Array.setChar(b, 5, c); } catch (Exception e) { System.out.println("Exception : " + e); } }}Output:Exception : java.lang.NullPointerException
Program 3: To demonstrate java.lang.ArrayIndexOutOfBoundsException// Java code to demonstrate// setChar() method of Array class import java.lang.reflect.Array;public class GfG { // main method public static void main(String[] args) { // Declaring and defining char array char b[] = { 'a', 'b', 'c', 'd' }; try { char c = 'g'; // Passing index 5 as parameter // when the size is 4 instead Array.setChar(b, 5, c); } catch (Exception e) { System.out.println("Exception : " + e); } }}Output:Exception : java.lang.ArrayIndexOutOfBoundsException
Program 4: To demonstrate java.lang.IllegalArgumentException// Java code to demonstrate setChar()// method of Array class import java.lang.reflect.Array;public class GfG { // main method public static void main(String[] args) { // Declaring and defining char variable char b = 'b'; try { char c = 'g'; // Passing a variable as parameter // when an array is expected instead Array.setChar(b, 5, c); } catch (Exception e) { System.out.println("Exception : " + e); } }}Output:Exception : java.lang.IllegalArgumentException: Argument is not an array
My Personal Notes
arrow_drop_upSave
Below is the implementation of Array.setChar() method:
Program 1:
// Java code to demonstrate setChar()// method of Array class import java.lang.reflect.Array; public class GfG { // main method public static void main(String[] args) { // Declaring and defining char array char ch[] = { 'a', 'b', 'c', 'd', 'e' }; System.out.print("Before Set : "); // printing the array for (char x : ch) { System.out.print(x + " "); } char value = 'g'; // setChar method of class Array Array.setChar(ch, 1, value); System.out.print("\nAfter Set : "); // printing array for (char x : ch) { System.out.print(x + " "); } }}
Before Set : a b c d e
After Set : a g c d e
Program 2: To demonstrate java.lang.NullPointerException
// Java code to demonstrate setChar()// method of Array class import java.lang.reflect.Array; public class GfG { // main method public static void main(String[] args) { // Declaring and defining char array to null char b[] = null; try { char c = 'a'; // Passing null array in parameter Array.setChar(b, 5, c); } catch (Exception e) { System.out.println("Exception : " + e); } }}
Exception : java.lang.NullPointerException
Program 3: To demonstrate java.lang.ArrayIndexOutOfBoundsException
// Java code to demonstrate// setChar() method of Array class import java.lang.reflect.Array;public class GfG { // main method public static void main(String[] args) { // Declaring and defining char array char b[] = { 'a', 'b', 'c', 'd' }; try { char c = 'g'; // Passing index 5 as parameter // when the size is 4 instead Array.setChar(b, 5, c); } catch (Exception e) { System.out.println("Exception : " + e); } }}
Exception : java.lang.ArrayIndexOutOfBoundsException
Program 4: To demonstrate java.lang.IllegalArgumentException
// Java code to demonstrate setChar()// method of Array class import java.lang.reflect.Array;public class GfG { // main method public static void main(String[] args) { // Declaring and defining char variable char b = 'b'; try { char c = 'g'; // Passing a variable as parameter // when an array is expected instead Array.setChar(b, 5, c); } catch (Exception e) { System.out.println("Exception : " + e); } }}
Exception : java.lang.IllegalArgumentException: Argument is not an array
Java-Arrays
Java-Functions
Java-lang package
java-lang-reflect-package
java-reflection-array
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
Initialize an ArrayList in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
LinkedList in Java
Collections in Java
|
[
{
"code": null,
"e": 23931,
"s": 23903,
"text": "\n30 Nov, 2018"
},
{
"code": null,
"e": 24089,
"s": 23931,
"text": "The java.lang.reflect.Array.setChar() is an inbuilt method in Java and is used to change a specified char value to a specified index of a given object array."
},
{
"code": null,
"e": 24097,
"s": 24089,
"text": "Syntax:"
},
{
"code": null,
"e": 24150,
"s": 24097,
"text": "Array.setChar(Object []array, int index, char value)"
},
{
"code": null,
"e": 24197,
"s": 24150,
"text": "Parameter: This method takes three parameters:"
},
{
"code": null,
"e": 24260,
"s": 24197,
"text": "array: This is an array of type Object which is to be updated."
},
{
"code": null,
"e": 24322,
"s": 24260,
"text": "index: This is the index of the array which is to be updated."
},
{
"code": null,
"e": 24409,
"s": 24322,
"text": "value: This is the char value that is to be set at the given index of the given array."
},
{
"code": null,
"e": 24563,
"s": 24409,
"text": "Return Value: This method has a void return type. Hence this doesn’t returns any value. The update reflects upon the Object array passed as the argument."
},
{
"code": null,
"e": 24615,
"s": 24563,
"text": "Exceptions: This method throws following exception:"
},
{
"code": null,
"e": 24661,
"s": 24615,
"text": "NullPointerException– when the array is null."
},
{
"code": null,
"e": 24732,
"s": 24661,
"text": "IllegalArgumentException– when the given object array is not an Array."
},
{
"code": null,
"e": 27566,
"s": 24732,
"text": "ArrayIndexOutOfBoundsException– if the given index is not in the range of the size of the array.Below is the implementation of Array.setChar() method:Program 1:// Java code to demonstrate setChar()// method of Array class import java.lang.reflect.Array; public class GfG { // main method public static void main(String[] args) { // Declaring and defining char array char ch[] = { 'a', 'b', 'c', 'd', 'e' }; System.out.print(\"Before Set : \"); // printing the array for (char x : ch) { System.out.print(x + \" \"); } char value = 'g'; // setChar method of class Array Array.setChar(ch, 1, value); System.out.print(\"\\nAfter Set : \"); // printing array for (char x : ch) { System.out.print(x + \" \"); } }}Output:Before Set : a b c d e \nAfter Set : a g c d e\nProgram 2: To demonstrate java.lang.NullPointerException// Java code to demonstrate setChar()// method of Array class import java.lang.reflect.Array; public class GfG { // main method public static void main(String[] args) { // Declaring and defining char array to null char b[] = null; try { char c = 'a'; // Passing null array in parameter Array.setChar(b, 5, c); } catch (Exception e) { System.out.println(\"Exception : \" + e); } }}Output:Exception : java.lang.NullPointerException\nProgram 3: To demonstrate java.lang.ArrayIndexOutOfBoundsException// Java code to demonstrate// setChar() method of Array class import java.lang.reflect.Array;public class GfG { // main method public static void main(String[] args) { // Declaring and defining char array char b[] = { 'a', 'b', 'c', 'd' }; try { char c = 'g'; // Passing index 5 as parameter // when the size is 4 instead Array.setChar(b, 5, c); } catch (Exception e) { System.out.println(\"Exception : \" + e); } }}Output:Exception : java.lang.ArrayIndexOutOfBoundsException\nProgram 4: To demonstrate java.lang.IllegalArgumentException// Java code to demonstrate setChar()// method of Array class import java.lang.reflect.Array;public class GfG { // main method public static void main(String[] args) { // Declaring and defining char variable char b = 'b'; try { char c = 'g'; // Passing a variable as parameter // when an array is expected instead Array.setChar(b, 5, c); } catch (Exception e) { System.out.println(\"Exception : \" + e); } }}Output:Exception : java.lang.IllegalArgumentException: Argument is not an array\nMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 27621,
"s": 27566,
"text": "Below is the implementation of Array.setChar() method:"
},
{
"code": null,
"e": 27632,
"s": 27621,
"text": "Program 1:"
},
{
"code": "// Java code to demonstrate setChar()// method of Array class import java.lang.reflect.Array; public class GfG { // main method public static void main(String[] args) { // Declaring and defining char array char ch[] = { 'a', 'b', 'c', 'd', 'e' }; System.out.print(\"Before Set : \"); // printing the array for (char x : ch) { System.out.print(x + \" \"); } char value = 'g'; // setChar method of class Array Array.setChar(ch, 1, value); System.out.print(\"\\nAfter Set : \"); // printing array for (char x : ch) { System.out.print(x + \" \"); } }}",
"e": 28312,
"s": 27632,
"text": null
},
{
"code": null,
"e": 28359,
"s": 28312,
"text": "Before Set : a b c d e \nAfter Set : a g c d e\n"
},
{
"code": null,
"e": 28416,
"s": 28359,
"text": "Program 2: To demonstrate java.lang.NullPointerException"
},
{
"code": "// Java code to demonstrate setChar()// method of Array class import java.lang.reflect.Array; public class GfG { // main method public static void main(String[] args) { // Declaring and defining char array to null char b[] = null; try { char c = 'a'; // Passing null array in parameter Array.setChar(b, 5, c); } catch (Exception e) { System.out.println(\"Exception : \" + e); } }}",
"e": 28901,
"s": 28416,
"text": null
},
{
"code": null,
"e": 28945,
"s": 28901,
"text": "Exception : java.lang.NullPointerException\n"
},
{
"code": null,
"e": 29012,
"s": 28945,
"text": "Program 3: To demonstrate java.lang.ArrayIndexOutOfBoundsException"
},
{
"code": "// Java code to demonstrate// setChar() method of Array class import java.lang.reflect.Array;public class GfG { // main method public static void main(String[] args) { // Declaring and defining char array char b[] = { 'a', 'b', 'c', 'd' }; try { char c = 'g'; // Passing index 5 as parameter // when the size is 4 instead Array.setChar(b, 5, c); } catch (Exception e) { System.out.println(\"Exception : \" + e); } }}",
"e": 29541,
"s": 29012,
"text": null
},
{
"code": null,
"e": 29595,
"s": 29541,
"text": "Exception : java.lang.ArrayIndexOutOfBoundsException\n"
},
{
"code": null,
"e": 29656,
"s": 29595,
"text": "Program 4: To demonstrate java.lang.IllegalArgumentException"
},
{
"code": "// Java code to demonstrate setChar()// method of Array class import java.lang.reflect.Array;public class GfG { // main method public static void main(String[] args) { // Declaring and defining char variable char b = 'b'; try { char c = 'g'; // Passing a variable as parameter // when an array is expected instead Array.setChar(b, 5, c); } catch (Exception e) { System.out.println(\"Exception : \" + e); } }}",
"e": 30179,
"s": 29656,
"text": null
},
{
"code": null,
"e": 30253,
"s": 30179,
"text": "Exception : java.lang.IllegalArgumentException: Argument is not an array\n"
},
{
"code": null,
"e": 30265,
"s": 30253,
"text": "Java-Arrays"
},
{
"code": null,
"e": 30280,
"s": 30265,
"text": "Java-Functions"
},
{
"code": null,
"e": 30298,
"s": 30280,
"text": "Java-lang package"
},
{
"code": null,
"e": 30324,
"s": 30298,
"text": "java-lang-reflect-package"
},
{
"code": null,
"e": 30346,
"s": 30324,
"text": "java-reflection-array"
},
{
"code": null,
"e": 30351,
"s": 30346,
"text": "Java"
},
{
"code": null,
"e": 30356,
"s": 30351,
"text": "Java"
},
{
"code": null,
"e": 30454,
"s": 30356,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30463,
"s": 30454,
"text": "Comments"
},
{
"code": null,
"e": 30476,
"s": 30463,
"text": "Old Comments"
},
{
"code": null,
"e": 30527,
"s": 30476,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 30558,
"s": 30527,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 30577,
"s": 30558,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 30609,
"s": 30577,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 30627,
"s": 30609,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 30659,
"s": 30627,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 30679,
"s": 30659,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 30703,
"s": 30679,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 30722,
"s": 30703,
"text": "LinkedList in Java"
}
] |
How to change background color in R using ggplot2? - GeeksforGeeks
|
04 Jul, 2021
In this article, we will discuss how to change the background color of a ggplot2 plot in R Programming Language.
To do so first we will create a basic ggplot2 plot.
Step 1: Create sample data for the plot.
sample_data <- data.frame(x = 1:10, y = 1:10)
Step 2: Load the package ggplot2.
library("ggplot2")
Step 3: Draw a basic ggplot2 plot without any color customization.
ggplot(sample_data, aes(x, y)) + geom_point()
R
# load ggplot2library("ggplot2") # Create Sample datasample_data <- data.frame(x = 1:10, y = 1:10) # Draw plot with ggplot2ggplot(sample_data, aes(x, y)) + geom_point()
Output:
Basic ggplot2 plot
We will use the argument panel.background of ggplot2 to change the background color of panel of plot.
ggplot(sample_data, aes(x, y)) + geom_point()+ theme(panel.background = element_rect(fill = “#00ab75”)
R
# load ggplot2library("ggplot2") # Create Sample datasample_data <- data.frame(x = 1:10, y = 1:10) # Draw plot with changed theme using # panel.background parameterggplot(sample_data, aes(x, y)) + geom_point()+theme(panel.background = element_rect(fill = "#00ab75" ))
Output:
Plot with panel background color green
We will use the argument plot.background of ggplot2 to change the background color of the plot.
ggplot(sample_data, aes(x, y)) + geom_point()+ theme(plot.background = element_rect(fill = “#00ab75”))
R
# load ggplot2library("ggplot2") # Create Sample datasample_data <- data.frame(x = 1:10, y = 1:10) # Draw plot with changed theme using # plot.background parameterggplot(sample_data, aes(x, y)) + geom_point()+theme(plot.background = element_rect(fill = "#00ab75" ))
Output:
Plot with background color green
We have some pre-built themes in ggplot2 that can be used to change the complete theme in ggplot2. Themes available in ggplot are,
theme_gray
theme_bw
theme_linedraw
theme_light
theme_dark
theme_minimal
theme_classic
theme_void
theme_test
Syntax:
ggplot(sample_data, aes(x, y)) + geom_point()+ theme_dark()
R
# load ggplot2library("ggplot2") # Create Sample datasample_data <- data.frame(x = 1:10, y = 1:10) # Draw plot with changed theme using # different prebuilt themesggplot(sample_data, aes(x, y)) + geom_point()+theme_dark()
Output:
Plot with dark theme in ggplot2
Picked
R-ggplot
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": 24877,
"s": 24849,
"text": "\n04 Jul, 2021"
},
{
"code": null,
"e": 24990,
"s": 24877,
"text": "In this article, we will discuss how to change the background color of a ggplot2 plot in R Programming Language."
},
{
"code": null,
"e": 25042,
"s": 24990,
"text": "To do so first we will create a basic ggplot2 plot."
},
{
"code": null,
"e": 25083,
"s": 25042,
"text": "Step 1: Create sample data for the plot."
},
{
"code": null,
"e": 25129,
"s": 25083,
"text": "sample_data <- data.frame(x = 1:10, y = 1:10)"
},
{
"code": null,
"e": 25163,
"s": 25129,
"text": "Step 2: Load the package ggplot2."
},
{
"code": null,
"e": 25182,
"s": 25163,
"text": "library(\"ggplot2\")"
},
{
"code": null,
"e": 25249,
"s": 25182,
"text": "Step 3: Draw a basic ggplot2 plot without any color customization."
},
{
"code": null,
"e": 25295,
"s": 25249,
"text": "ggplot(sample_data, aes(x, y)) + geom_point()"
},
{
"code": null,
"e": 25297,
"s": 25295,
"text": "R"
},
{
"code": "# load ggplot2library(\"ggplot2\") # Create Sample datasample_data <- data.frame(x = 1:10, y = 1:10) # Draw plot with ggplot2ggplot(sample_data, aes(x, y)) + geom_point()",
"e": 25468,
"s": 25297,
"text": null
},
{
"code": null,
"e": 25476,
"s": 25468,
"text": "Output:"
},
{
"code": null,
"e": 25495,
"s": 25476,
"text": "Basic ggplot2 plot"
},
{
"code": null,
"e": 25597,
"s": 25495,
"text": "We will use the argument panel.background of ggplot2 to change the background color of panel of plot."
},
{
"code": null,
"e": 25700,
"s": 25597,
"text": "ggplot(sample_data, aes(x, y)) + geom_point()+ theme(panel.background = element_rect(fill = “#00ab75”)"
},
{
"code": null,
"e": 25702,
"s": 25700,
"text": "R"
},
{
"code": "# load ggplot2library(\"ggplot2\") # Create Sample datasample_data <- data.frame(x = 1:10, y = 1:10) # Draw plot with changed theme using # panel.background parameterggplot(sample_data, aes(x, y)) + geom_point()+theme(panel.background = element_rect(fill = \"#00ab75\" ))",
"e": 25972,
"s": 25702,
"text": null
},
{
"code": null,
"e": 25980,
"s": 25972,
"text": "Output:"
},
{
"code": null,
"e": 26019,
"s": 25980,
"text": "Plot with panel background color green"
},
{
"code": null,
"e": 26115,
"s": 26019,
"text": "We will use the argument plot.background of ggplot2 to change the background color of the plot."
},
{
"code": null,
"e": 26218,
"s": 26115,
"text": "ggplot(sample_data, aes(x, y)) + geom_point()+ theme(plot.background = element_rect(fill = “#00ab75”))"
},
{
"code": null,
"e": 26220,
"s": 26218,
"text": "R"
},
{
"code": "# load ggplot2library(\"ggplot2\") # Create Sample datasample_data <- data.frame(x = 1:10, y = 1:10) # Draw plot with changed theme using # plot.background parameterggplot(sample_data, aes(x, y)) + geom_point()+theme(plot.background = element_rect(fill = \"#00ab75\" ))",
"e": 26488,
"s": 26220,
"text": null
},
{
"code": null,
"e": 26496,
"s": 26488,
"text": "Output:"
},
{
"code": null,
"e": 26529,
"s": 26496,
"text": "Plot with background color green"
},
{
"code": null,
"e": 26660,
"s": 26529,
"text": "We have some pre-built themes in ggplot2 that can be used to change the complete theme in ggplot2. Themes available in ggplot are,"
},
{
"code": null,
"e": 26671,
"s": 26660,
"text": "theme_gray"
},
{
"code": null,
"e": 26680,
"s": 26671,
"text": "theme_bw"
},
{
"code": null,
"e": 26695,
"s": 26680,
"text": "theme_linedraw"
},
{
"code": null,
"e": 26707,
"s": 26695,
"text": "theme_light"
},
{
"code": null,
"e": 26718,
"s": 26707,
"text": "theme_dark"
},
{
"code": null,
"e": 26732,
"s": 26718,
"text": "theme_minimal"
},
{
"code": null,
"e": 26746,
"s": 26732,
"text": "theme_classic"
},
{
"code": null,
"e": 26757,
"s": 26746,
"text": "theme_void"
},
{
"code": null,
"e": 26768,
"s": 26757,
"text": "theme_test"
},
{
"code": null,
"e": 26776,
"s": 26768,
"text": "Syntax:"
},
{
"code": null,
"e": 26836,
"s": 26776,
"text": "ggplot(sample_data, aes(x, y)) + geom_point()+ theme_dark()"
},
{
"code": null,
"e": 26838,
"s": 26836,
"text": "R"
},
{
"code": "# load ggplot2library(\"ggplot2\") # Create Sample datasample_data <- data.frame(x = 1:10, y = 1:10) # Draw plot with changed theme using # different prebuilt themesggplot(sample_data, aes(x, y)) + geom_point()+theme_dark()",
"e": 27062,
"s": 26838,
"text": null
},
{
"code": null,
"e": 27070,
"s": 27062,
"text": "Output:"
},
{
"code": null,
"e": 27102,
"s": 27070,
"text": "Plot with dark theme in ggplot2"
},
{
"code": null,
"e": 27109,
"s": 27102,
"text": "Picked"
},
{
"code": null,
"e": 27118,
"s": 27109,
"text": "R-ggplot"
},
{
"code": null,
"e": 27129,
"s": 27118,
"text": "R Language"
},
{
"code": null,
"e": 27227,
"s": 27129,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27236,
"s": 27227,
"text": "Comments"
},
{
"code": null,
"e": 27249,
"s": 27236,
"text": "Old Comments"
},
{
"code": null,
"e": 27301,
"s": 27249,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 27339,
"s": 27301,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 27374,
"s": 27339,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 27432,
"s": 27374,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 27481,
"s": 27432,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 27524,
"s": 27481,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 27574,
"s": 27524,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 27591,
"s": 27574,
"text": "R - if statement"
},
{
"code": null,
"e": 27628,
"s": 27591,
"text": "How to import an Excel File into R ?"
}
] |
Python - globals() function - GeeksforGeeks
|
18 Nov, 2020
globals() function in Python returns the dictionary of current global symbol table.
Symbol table: Symbol table is a data structure which contains all necessary information about the program. These include variable names, methods, classes, etc.Global symbol table stores all information related to the global scope of the program, and is accessed in Python using globals() method.
The functions, variables which are not associated with any class or function are stored in global scope.
Syntax: globals()
Parameters: No parameters required.
Code #1:
# Python3 program to demonstrate global() function # global variablea = 5 def func(): c = 10 d = c + a # Calling globals() globals()['a'] = d print (d) # Driver Code func()
Output:
15
Code #2:
# Python3 program to demonstrate global() function # global variablename = 'gautam' print('Before modification:', name) # Calling global()globals()['name'] = 'gautam karakoti'print('After modification:', name)
Output:
Before modification: gautam
After modification: gautam karakoti
Note: We can also change the value of global variables by using globals() function. The changed value also updated in the symbol table.
Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
|
[
{
"code": null,
"e": 24502,
"s": 24474,
"text": "\n18 Nov, 2020"
},
{
"code": null,
"e": 24586,
"s": 24502,
"text": "globals() function in Python returns the dictionary of current global symbol table."
},
{
"code": null,
"e": 24882,
"s": 24586,
"text": "Symbol table: Symbol table is a data structure which contains all necessary information about the program. These include variable names, methods, classes, etc.Global symbol table stores all information related to the global scope of the program, and is accessed in Python using globals() method."
},
{
"code": null,
"e": 24987,
"s": 24882,
"text": "The functions, variables which are not associated with any class or function are stored in global scope."
},
{
"code": null,
"e": 25042,
"s": 24987,
"text": "Syntax: globals()\n\nParameters: No parameters required."
},
{
"code": null,
"e": 25051,
"s": 25042,
"text": "Code #1:"
},
{
"code": "# Python3 program to demonstrate global() function # global variablea = 5 def func(): c = 10 d = c + a # Calling globals() globals()['a'] = d print (d) # Driver Code func()",
"e": 25255,
"s": 25051,
"text": null
},
{
"code": null,
"e": 25263,
"s": 25255,
"text": "Output:"
},
{
"code": null,
"e": 25267,
"s": 25263,
"text": "15\n"
},
{
"code": null,
"e": 25276,
"s": 25267,
"text": "Code #2:"
},
{
"code": "# Python3 program to demonstrate global() function # global variablename = 'gautam' print('Before modification:', name) # Calling global()globals()['name'] = 'gautam karakoti'print('After modification:', name)",
"e": 25489,
"s": 25276,
"text": null
},
{
"code": null,
"e": 25497,
"s": 25489,
"text": "Output:"
},
{
"code": null,
"e": 25562,
"s": 25497,
"text": "Before modification: gautam\nAfter modification: gautam karakoti\n"
},
{
"code": null,
"e": 25698,
"s": 25562,
"text": "Note: We can also change the value of global variables by using globals() function. The changed value also updated in the symbol table."
},
{
"code": null,
"e": 25724,
"s": 25698,
"text": "Python-Built-in-functions"
},
{
"code": null,
"e": 25731,
"s": 25724,
"text": "Python"
},
{
"code": null,
"e": 25829,
"s": 25731,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25847,
"s": 25829,
"text": "Python Dictionary"
},
{
"code": null,
"e": 25882,
"s": 25847,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 25904,
"s": 25882,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 25936,
"s": 25904,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25966,
"s": 25936,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26008,
"s": 25966,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26034,
"s": 26008,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26077,
"s": 26034,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 26114,
"s": 26077,
"text": "Create a Pandas DataFrame from Lists"
}
] |
The Search for Categorical Correlation | by Shaked Zychlinski | Towards Data Science
|
All the code appearing in this post is available as part of the dython library on my GitHub page.For any code related questions, please open an issue on the library’s GitHub page.
Not long ago I stumbled across a data-set of mushrooms on Kaggle, where over 20 different features of edible and poisonous mushrooms were collected and sorted into categories. The idea of seeking patterns that might point on how safe it is to eat a random mushroom seemed like a nice challenge — I even found myself creating a whole storyline of a lost man in the woods behind the kernel I published later on.
While going through other users’ kernels, it was easy to see that Random Forests and other simple methods reach extremely high accuracy without too much effort, so I saw no reason doing so too — I’ve decided to see if can find by myself which features point towards which mushroom I can safely eat, if I’ll ever need to. I realized what I’m actually looking for is the correlation between the features and the mushroom’s type — but that’s a problem, as the features are all categorical, and correlation isn’t defined in that case.
Before we can discuss about what correlation is not, let’s talk about what it is. In human language, correlation is the measure of how two features are, well, correlated; just like the month-of-the-year is correlated with the average daily temperature, and the hour-of-the-day is correlated with the amount of light outdoors. Formalizing this mathematically, the definition of correlation usually used is Pearson’s R for a data sample (which results in a value in the range [-1,1]):
But, as can be seen from the above equation, Pearson’s R isn’t defined when the data is categorical; let’s assume that x is a color feature — how do you subtract yellow from the average of colors? We need something else here.
One common option to handle this scenario is by first using one-hot encoding, and break each possible option of each categorical feature to 0-or-1 features. This will then allow the use of correlation, but it can easily become too complex to analyse. For example, one-hot encoding converts the 22 categorical features of the mushrooms data-set to a 112-features data-set, and when plotting the correlation table as a heat-map, we get something like this:
This is not something that can be easily used for gaining new insights. So we still need something else.
What we need is something that will look like correlation, but will work with categorical values — or more formally, we’re looking for a measure of association between two categorical features. Introducing: Cramér’s V. It is based on a nominal variation of Pearson’s Chi-Square Test, and comes built-in with some great benefits:
Similarly to correlation, the output is in the range of [0,1], where 0 means no association and 1 is full association. (Unlike correlation, there are no negative values, as there’s no such thing as a negative association. Either there is, or there isn’t)Like correlation, Cramer’s V is symmetrical — it is insensitive to swapping x and y
Similarly to correlation, the output is in the range of [0,1], where 0 means no association and 1 is full association. (Unlike correlation, there are no negative values, as there’s no such thing as a negative association. Either there is, or there isn’t)
Like correlation, Cramer’s V is symmetrical — it is insensitive to swapping x and y
And what was even better — someone already implemented that as a Python function. And here’s my edited version of the original:
def cramers_v(x, y): confusion_matrix = pd.crosstab(x,y) chi2 = ss.chi2_contingency(confusion_matrix)[0] n = confusion_matrix.sum().sum() phi2 = chi2/n r,k = confusion_matrix.shape phi2corr = max(0, phi2-((k-1)*(r-1))/(n-1)) rcorr = r-((r-1)**2)/(n-1) kcorr = k-((k-1)**2)/(n-1) return np.sqrt(phi2corr/min((kcorr-1),(rcorr-1)))
When applied to the mushrooms data-set, it looks like this:
Well isn’t that pretty? Just by looking at this heat-map we can see that the odor is highly associated with the class (edible/poisonous) of the mushroom, and that the gill-attachment feature is highly associated with three others.
Thinking over the output of Cramer’s V, I realized I’m losing valuable information due to the symmetry of it. To better demonstrate that, consider the following data-set:
We can see that if the value of x is known, the value of y still can’t be determined, but if the value of y is known — then the value of x is guaranteed. This valuable information is lost when using Cramer’s V due to its symmetry, so to preserve it we need an asymmetric measure of association between categorical features. And this is exactly what Theil’s U is.
Theil’s U, also referred to as the Uncertainty Coefficient, is based on the conditional entropy between x and y — or in human language, given the value of x, how many possible states does y have, and how often do they occur. Just like Cramer’s V, the output value is on the range of [0,1], with the same interpretations as before — but unlike Cramer’s V, it is asymmetric, meaning U(x,y)≠U(y,x) (while V(x,y)=V(y,x), where V is Cramer’s V). Using Theil’s U in the simple case above will let us find out that knowing y means we know x, but not vice-versa.
Implementing the formula as a Python function yields this (full code with the conditional_entropy function can be found on my Github page — link at the top of the post):
def theils_u(x, y): s_xy = conditional_entropy(x,y) x_counter = Counter(x) total_occurrences = sum(x_counter.values()) p_x = list(map(lambda n: n/total_occurrences, x_counter.values())) s_x = ss.entropy(p_x) if s_x == 0: return 1 else: return (s_x - s_xy) / s_x
Applying this to the mushrooms data-set:
This new calculation shed much more light on the associations we’ve seen from Cramer’s V — for example, we now see that while knowing the odor gives a lot of information over the mushroom’s class, this is not in the case the other way around. Theil’s U indeed gives us much more information on the true relations between the different features.
So now we have a way to measure the correlation between two continuous features, and two ways of measuring association between two categorical features. But what about a pair of a continuous feature and a categorical feature? For this, we can use the Correlation Ratio (often marked using the greek letter eta). Mathematically, it is defined as the weighted variance of the mean of each category divided by the variance of all samples; in human language, the Correlation Ratio answers the following question: Given a continuous number, how well can you know to which category it belongs to? Just like the two coefficients we’ve seen before, here too the output is on the range of [0,1].
Implementation in Python looks like this:
def correlation_ratio(categories, measurements): fcat, _ = pd.factorize(categories) cat_num = np.max(fcat)+1 y_avg_array = np.zeros(cat_num) n_array = np.zeros(cat_num) for i in range(0,cat_num): cat_measures = measurements[np.argwhere(fcat == i).flatten()] n_array[i] = len(cat_measures) y_avg_array[i] = np.average(cat_measures) y_total_avg = np.sum(np.multiply(y_avg_array,n_array))/np.sum(n_array) numerator = np.sum(np.multiply(n_array,np.power(np.subtract(y_avg_array,y_total_avg),2))) denominator = np.sum(np.power(np.subtract(measurements,y_total_avg),2)) if numerator == 0: eta = 0.0 else: eta = np.sqrt(numerator/denominator) return eta
I believe I can declare the search for a measure of association for categorical features a successful one, especially as certain requirements — such as the need for an asymmetric measure — were not expected when starting. These three new metrics are very useful when exploring a data-set which contains categorical features, and helped me gain more insights on data-sets I’ve explored. I can only hope this will be useful to you as it was to me, and if not — well, at least you now know how to identify edible mushrooms.
|
[
{
"code": null,
"e": 352,
"s": 172,
"text": "All the code appearing in this post is available as part of the dython library on my GitHub page.For any code related questions, please open an issue on the library’s GitHub page."
},
{
"code": null,
"e": 762,
"s": 352,
"text": "Not long ago I stumbled across a data-set of mushrooms on Kaggle, where over 20 different features of edible and poisonous mushrooms were collected and sorted into categories. The idea of seeking patterns that might point on how safe it is to eat a random mushroom seemed like a nice challenge — I even found myself creating a whole storyline of a lost man in the woods behind the kernel I published later on."
},
{
"code": null,
"e": 1293,
"s": 762,
"text": "While going through other users’ kernels, it was easy to see that Random Forests and other simple methods reach extremely high accuracy without too much effort, so I saw no reason doing so too — I’ve decided to see if can find by myself which features point towards which mushroom I can safely eat, if I’ll ever need to. I realized what I’m actually looking for is the correlation between the features and the mushroom’s type — but that’s a problem, as the features are all categorical, and correlation isn’t defined in that case."
},
{
"code": null,
"e": 1776,
"s": 1293,
"text": "Before we can discuss about what correlation is not, let’s talk about what it is. In human language, correlation is the measure of how two features are, well, correlated; just like the month-of-the-year is correlated with the average daily temperature, and the hour-of-the-day is correlated with the amount of light outdoors. Formalizing this mathematically, the definition of correlation usually used is Pearson’s R for a data sample (which results in a value in the range [-1,1]):"
},
{
"code": null,
"e": 2002,
"s": 1776,
"text": "But, as can be seen from the above equation, Pearson’s R isn’t defined when the data is categorical; let’s assume that x is a color feature — how do you subtract yellow from the average of colors? We need something else here."
},
{
"code": null,
"e": 2457,
"s": 2002,
"text": "One common option to handle this scenario is by first using one-hot encoding, and break each possible option of each categorical feature to 0-or-1 features. This will then allow the use of correlation, but it can easily become too complex to analyse. For example, one-hot encoding converts the 22 categorical features of the mushrooms data-set to a 112-features data-set, and when plotting the correlation table as a heat-map, we get something like this:"
},
{
"code": null,
"e": 2562,
"s": 2457,
"text": "This is not something that can be easily used for gaining new insights. So we still need something else."
},
{
"code": null,
"e": 2892,
"s": 2562,
"text": "What we need is something that will look like correlation, but will work with categorical values — or more formally, we’re looking for a measure of association between two categorical features. Introducing: Cramér’s V. It is based on a nominal variation of Pearson’s Chi-Square Test, and comes built-in with some great benefits:"
},
{
"code": null,
"e": 3230,
"s": 2892,
"text": "Similarly to correlation, the output is in the range of [0,1], where 0 means no association and 1 is full association. (Unlike correlation, there are no negative values, as there’s no such thing as a negative association. Either there is, or there isn’t)Like correlation, Cramer’s V is symmetrical — it is insensitive to swapping x and y"
},
{
"code": null,
"e": 3485,
"s": 3230,
"text": "Similarly to correlation, the output is in the range of [0,1], where 0 means no association and 1 is full association. (Unlike correlation, there are no negative values, as there’s no such thing as a negative association. Either there is, or there isn’t)"
},
{
"code": null,
"e": 3569,
"s": 3485,
"text": "Like correlation, Cramer’s V is symmetrical — it is insensitive to swapping x and y"
},
{
"code": null,
"e": 3697,
"s": 3569,
"text": "And what was even better — someone already implemented that as a Python function. And here’s my edited version of the original:"
},
{
"code": null,
"e": 4053,
"s": 3697,
"text": "def cramers_v(x, y): confusion_matrix = pd.crosstab(x,y) chi2 = ss.chi2_contingency(confusion_matrix)[0] n = confusion_matrix.sum().sum() phi2 = chi2/n r,k = confusion_matrix.shape phi2corr = max(0, phi2-((k-1)*(r-1))/(n-1)) rcorr = r-((r-1)**2)/(n-1) kcorr = k-((k-1)**2)/(n-1) return np.sqrt(phi2corr/min((kcorr-1),(rcorr-1)))"
},
{
"code": null,
"e": 4113,
"s": 4053,
"text": "When applied to the mushrooms data-set, it looks like this:"
},
{
"code": null,
"e": 4344,
"s": 4113,
"text": "Well isn’t that pretty? Just by looking at this heat-map we can see that the odor is highly associated with the class (edible/poisonous) of the mushroom, and that the gill-attachment feature is highly associated with three others."
},
{
"code": null,
"e": 4515,
"s": 4344,
"text": "Thinking over the output of Cramer’s V, I realized I’m losing valuable information due to the symmetry of it. To better demonstrate that, consider the following data-set:"
},
{
"code": null,
"e": 4878,
"s": 4515,
"text": "We can see that if the value of x is known, the value of y still can’t be determined, but if the value of y is known — then the value of x is guaranteed. This valuable information is lost when using Cramer’s V due to its symmetry, so to preserve it we need an asymmetric measure of association between categorical features. And this is exactly what Theil’s U is."
},
{
"code": null,
"e": 5434,
"s": 4878,
"text": "Theil’s U, also referred to as the Uncertainty Coefficient, is based on the conditional entropy between x and y — or in human language, given the value of x, how many possible states does y have, and how often do they occur. Just like Cramer’s V, the output value is on the range of [0,1], with the same interpretations as before — but unlike Cramer’s V, it is asymmetric, meaning U(x,y)≠U(y,x) (while V(x,y)=V(y,x), where V is Cramer’s V). Using Theil’s U in the simple case above will let us find out that knowing y means we know x, but not vice-versa."
},
{
"code": null,
"e": 5604,
"s": 5434,
"text": "Implementing the formula as a Python function yields this (full code with the conditional_entropy function can be found on my Github page — link at the top of the post):"
},
{
"code": null,
"e": 5901,
"s": 5604,
"text": "def theils_u(x, y): s_xy = conditional_entropy(x,y) x_counter = Counter(x) total_occurrences = sum(x_counter.values()) p_x = list(map(lambda n: n/total_occurrences, x_counter.values())) s_x = ss.entropy(p_x) if s_x == 0: return 1 else: return (s_x - s_xy) / s_x"
},
{
"code": null,
"e": 5942,
"s": 5901,
"text": "Applying this to the mushrooms data-set:"
},
{
"code": null,
"e": 6287,
"s": 5942,
"text": "This new calculation shed much more light on the associations we’ve seen from Cramer’s V — for example, we now see that while knowing the odor gives a lot of information over the mushroom’s class, this is not in the case the other way around. Theil’s U indeed gives us much more information on the true relations between the different features."
},
{
"code": null,
"e": 6974,
"s": 6287,
"text": "So now we have a way to measure the correlation between two continuous features, and two ways of measuring association between two categorical features. But what about a pair of a continuous feature and a categorical feature? For this, we can use the Correlation Ratio (often marked using the greek letter eta). Mathematically, it is defined as the weighted variance of the mean of each category divided by the variance of all samples; in human language, the Correlation Ratio answers the following question: Given a continuous number, how well can you know to which category it belongs to? Just like the two coefficients we’ve seen before, here too the output is on the range of [0,1]."
},
{
"code": null,
"e": 7016,
"s": 6974,
"text": "Implementation in Python looks like this:"
},
{
"code": null,
"e": 7731,
"s": 7016,
"text": "def correlation_ratio(categories, measurements): fcat, _ = pd.factorize(categories) cat_num = np.max(fcat)+1 y_avg_array = np.zeros(cat_num) n_array = np.zeros(cat_num) for i in range(0,cat_num): cat_measures = measurements[np.argwhere(fcat == i).flatten()] n_array[i] = len(cat_measures) y_avg_array[i] = np.average(cat_measures) y_total_avg = np.sum(np.multiply(y_avg_array,n_array))/np.sum(n_array) numerator = np.sum(np.multiply(n_array,np.power(np.subtract(y_avg_array,y_total_avg),2))) denominator = np.sum(np.power(np.subtract(measurements,y_total_avg),2)) if numerator == 0: eta = 0.0 else: eta = np.sqrt(numerator/denominator) return eta"
}
] |
Formatting code with Prettier - GeeksforGeeks
|
10 Dec, 2021
Prettier is an opinionated code formatter that will take all your code, removes the inconsistency in the codebase in styling the code, and ensures the output code should be formatted in the desired pattern by using the predefined styles in prettier. The reason for being used prettier is given below:
It helps to make proper alignment along with giving the space in between the words in the code that enhance the overall readability of the large-size code.
The reader can easily able to understand the structure that will give an idea of the logic of the code at a glance.
The length & width of the overall code is also reduced due to proper indentation of the code. An ordinarily spilling of the code across the right margin, that will require horizontal scrolling or can destroy the shape by wrapping up the line of text in an unstructured way.
Providing the error message if the code is not followed any syntax, will help us to make syntactically correct code.
It enforces the proper consistent styling of the codebase across the entire codebase. For this reason, the maintainability of the large-size code is much easier.
Languages supported by Prettier: JavaScript, TypeScript, JSX, Angular, Vue, CSS, HTML, JSON, GraphQL, and much more.
There are so many other reasons also there for using the Prettier but we will not be covering those reasons here.
But why use Prettier? It is generally considered good practice if a project has a common coding style guide, Due to this, it becomes easier for maintainers to maintain the codebase, for newcomers to adapt to those stylings which will also eventually result in having a great understanding of syntax. Even if you have your old codebase, you can run Prettier on your codebase which will reformat all your massive code files in a matter of seconds. Most importantly, it gives you the freedom to write code anyways you want as you can format it correctly immediately. If you’re worried about the acceptance rating then here are the possible stats given below:
Used by various big companies like Facebook, Spotify, Discord, PayPal, Dropbox, ESLint, and many more.
More than 40k+ stars on Github.
Has 13 Millions+ weekly downloads.
Installation Procedure: In order to implement the Prettier to our codebase, we need to follow certain steps.
Step 1: Install Prettier in your project by running the following command:
npm install -D prettier
Step 2: After adding Prettier as a devDependency, let’s create a file called `.prettierrc` which is a configuration file for Prettier, at the root of the project directory and just add curly braces `{}` in that file, so anyone will know that your project uses Prettier with the default configuration.
.prettierrc file at the root of the project
Step 3: Now, let’s add a command in our package.json’s “scripts” property to run Prettier.
"scripts": {
"format": "prettier --write \"src/**/*.{js,jsx}\""
},
`npm run format` command will format every `*.js` or `*.jsx` file in the “src/”, even if your “src/” folder contains multiple directories in it, this regex command will go down recursively on them and format them.
Output:
Editor Integration: You can get the most out of Prettier by using it with code editors, Prettier supports many editors like Emacs, Atom, VS Code, Sublime Text, Vim, etc. Follow the below steps to install Prettier in Visual studio code:
In the Extensions sidebar search extension “Prettier – Code formatter” and install it or you may download it through VS Marketplace Link.
Make Prettier your default code-formatter for this in Settings, search for this setting “editor.defaultFormatter” and set it to Prettier.
If you need Prettier to format your code automatically once it’s saved then search for this setting “editor.formatOnSave” and tick it to turn it on.
Sometimes, it may happen that some projects don’t use Prettier in such cases you need to disable this setting as it will format your code even if your project doesn’t have a Prettier setup. But we geeks do have a solution for that, In the setting, menu search for this setting “prettier.requireConfig” and tick it to turn it on, by doing so it will ensure that Prettier will only format the code if there is a Prettier config file (.prettierrc) present in the project directory.
ESLint Integration: If your Project uses ESLint, then you can have a setup where Prettier will be used for formatting purposes and ESLint will do the work of catching bugs and maintaining code quality. See this article for ESLint set up in your project.For integrating Prettier with ESLint follow the below steps:
Install eslint-config-prettier, which will turn off some ESLint rules that conflict while using Prettier
npm install -D eslint-config-prettier
Append “prettier” to the last in extends array in your `.eslintrc.*` file
{
"extends": [
"eslint:recommended",
"plugin:import/errors",
"plugin:react/recommended",
"plugin:jsx-a11y/recommended",
"prettier"
],
...
}
Conclusion: After installing Prettier and integrating it with our Code Editor and ESLint, we have a perfect development setup ready, where we don’t have to clutter our mind by worrying about styling the code, remembering the proper syntax, or any other formatting rules of projects while writing the code because ESLint and Prettier will take care of that and we can focus more on building our project.
rishabhsinha20
Blogathon-2021
Blogathon
Installation Guide
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Import JSON Data into SQL Server?
How to Install Tkinter in Windows?
SQL - Multiple Column Ordering
How to pass data into table from a form using React Components
How to Create a Table With Multiple Foreign Keys in SQL?
How to Install PIP on Windows ?
Installation of Node.js on Linux
How to install Jupyter Notebook on Windows?
How to Install OpenCV for Python on Windows?
How to Install FFmpeg on Windows?
|
[
{
"code": null,
"e": 24449,
"s": 24421,
"text": "\n10 Dec, 2021"
},
{
"code": null,
"e": 24750,
"s": 24449,
"text": "Prettier is an opinionated code formatter that will take all your code, removes the inconsistency in the codebase in styling the code, and ensures the output code should be formatted in the desired pattern by using the predefined styles in prettier. The reason for being used prettier is given below:"
},
{
"code": null,
"e": 24906,
"s": 24750,
"text": "It helps to make proper alignment along with giving the space in between the words in the code that enhance the overall readability of the large-size code."
},
{
"code": null,
"e": 25022,
"s": 24906,
"text": "The reader can easily able to understand the structure that will give an idea of the logic of the code at a glance."
},
{
"code": null,
"e": 25296,
"s": 25022,
"text": "The length & width of the overall code is also reduced due to proper indentation of the code. An ordinarily spilling of the code across the right margin, that will require horizontal scrolling or can destroy the shape by wrapping up the line of text in an unstructured way."
},
{
"code": null,
"e": 25413,
"s": 25296,
"text": "Providing the error message if the code is not followed any syntax, will help us to make syntactically correct code."
},
{
"code": null,
"e": 25575,
"s": 25413,
"text": "It enforces the proper consistent styling of the codebase across the entire codebase. For this reason, the maintainability of the large-size code is much easier."
},
{
"code": null,
"e": 25692,
"s": 25575,
"text": "Languages supported by Prettier: JavaScript, TypeScript, JSX, Angular, Vue, CSS, HTML, JSON, GraphQL, and much more."
},
{
"code": null,
"e": 25806,
"s": 25692,
"text": "There are so many other reasons also there for using the Prettier but we will not be covering those reasons here."
},
{
"code": null,
"e": 26462,
"s": 25806,
"text": "But why use Prettier? It is generally considered good practice if a project has a common coding style guide, Due to this, it becomes easier for maintainers to maintain the codebase, for newcomers to adapt to those stylings which will also eventually result in having a great understanding of syntax. Even if you have your old codebase, you can run Prettier on your codebase which will reformat all your massive code files in a matter of seconds. Most importantly, it gives you the freedom to write code anyways you want as you can format it correctly immediately. If you’re worried about the acceptance rating then here are the possible stats given below:"
},
{
"code": null,
"e": 26565,
"s": 26462,
"text": "Used by various big companies like Facebook, Spotify, Discord, PayPal, Dropbox, ESLint, and many more."
},
{
"code": null,
"e": 26597,
"s": 26565,
"text": "More than 40k+ stars on Github."
},
{
"code": null,
"e": 26632,
"s": 26597,
"text": "Has 13 Millions+ weekly downloads."
},
{
"code": null,
"e": 26741,
"s": 26632,
"text": "Installation Procedure: In order to implement the Prettier to our codebase, we need to follow certain steps."
},
{
"code": null,
"e": 26816,
"s": 26741,
"text": "Step 1: Install Prettier in your project by running the following command:"
},
{
"code": null,
"e": 26840,
"s": 26816,
"text": "npm install -D prettier"
},
{
"code": null,
"e": 27141,
"s": 26840,
"text": "Step 2: After adding Prettier as a devDependency, let’s create a file called `.prettierrc` which is a configuration file for Prettier, at the root of the project directory and just add curly braces `{}` in that file, so anyone will know that your project uses Prettier with the default configuration."
},
{
"code": null,
"e": 27185,
"s": 27141,
"text": ".prettierrc file at the root of the project"
},
{
"code": null,
"e": 27276,
"s": 27185,
"text": "Step 3: Now, let’s add a command in our package.json’s “scripts” property to run Prettier."
},
{
"code": null,
"e": 27351,
"s": 27276,
"text": " \"scripts\": {\n \"format\": \"prettier --write \\\"src/**/*.{js,jsx}\\\"\"\n },"
},
{
"code": null,
"e": 27565,
"s": 27351,
"text": "`npm run format` command will format every `*.js` or `*.jsx` file in the “src/”, even if your “src/” folder contains multiple directories in it, this regex command will go down recursively on them and format them."
},
{
"code": null,
"e": 27573,
"s": 27565,
"text": "Output:"
},
{
"code": null,
"e": 27809,
"s": 27573,
"text": "Editor Integration: You can get the most out of Prettier by using it with code editors, Prettier supports many editors like Emacs, Atom, VS Code, Sublime Text, Vim, etc. Follow the below steps to install Prettier in Visual studio code:"
},
{
"code": null,
"e": 27947,
"s": 27809,
"text": "In the Extensions sidebar search extension “Prettier – Code formatter” and install it or you may download it through VS Marketplace Link."
},
{
"code": null,
"e": 28085,
"s": 27947,
"text": "Make Prettier your default code-formatter for this in Settings, search for this setting “editor.defaultFormatter” and set it to Prettier."
},
{
"code": null,
"e": 28234,
"s": 28085,
"text": "If you need Prettier to format your code automatically once it’s saved then search for this setting “editor.formatOnSave” and tick it to turn it on."
},
{
"code": null,
"e": 28713,
"s": 28234,
"text": "Sometimes, it may happen that some projects don’t use Prettier in such cases you need to disable this setting as it will format your code even if your project doesn’t have a Prettier setup. But we geeks do have a solution for that, In the setting, menu search for this setting “prettier.requireConfig” and tick it to turn it on, by doing so it will ensure that Prettier will only format the code if there is a Prettier config file (.prettierrc) present in the project directory."
},
{
"code": null,
"e": 29027,
"s": 28713,
"text": "ESLint Integration: If your Project uses ESLint, then you can have a setup where Prettier will be used for formatting purposes and ESLint will do the work of catching bugs and maintaining code quality. See this article for ESLint set up in your project.For integrating Prettier with ESLint follow the below steps:"
},
{
"code": null,
"e": 29132,
"s": 29027,
"text": "Install eslint-config-prettier, which will turn off some ESLint rules that conflict while using Prettier"
},
{
"code": null,
"e": 29170,
"s": 29132,
"text": "npm install -D eslint-config-prettier"
},
{
"code": null,
"e": 29244,
"s": 29170,
"text": "Append “prettier” to the last in extends array in your `.eslintrc.*` file"
},
{
"code": null,
"e": 29434,
"s": 29244,
"text": "{\n \"extends\": [\n \"eslint:recommended\",\n \"plugin:import/errors\",\n \"plugin:react/recommended\",\n \"plugin:jsx-a11y/recommended\",\n \"prettier\" \n ],\n ...\n}"
},
{
"code": null,
"e": 29837,
"s": 29434,
"text": "Conclusion: After installing Prettier and integrating it with our Code Editor and ESLint, we have a perfect development setup ready, where we don’t have to clutter our mind by worrying about styling the code, remembering the proper syntax, or any other formatting rules of projects while writing the code because ESLint and Prettier will take care of that and we can focus more on building our project."
},
{
"code": null,
"e": 29852,
"s": 29837,
"text": "rishabhsinha20"
},
{
"code": null,
"e": 29867,
"s": 29852,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 29877,
"s": 29867,
"text": "Blogathon"
},
{
"code": null,
"e": 29896,
"s": 29877,
"text": "Installation Guide"
},
{
"code": null,
"e": 29913,
"s": 29896,
"text": "Web Technologies"
},
{
"code": null,
"e": 30011,
"s": 29913,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30020,
"s": 30011,
"text": "Comments"
},
{
"code": null,
"e": 30033,
"s": 30020,
"text": "Old Comments"
},
{
"code": null,
"e": 30074,
"s": 30033,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 30109,
"s": 30074,
"text": "How to Install Tkinter in Windows?"
},
{
"code": null,
"e": 30140,
"s": 30109,
"text": "SQL - Multiple Column Ordering"
},
{
"code": null,
"e": 30203,
"s": 30140,
"text": "How to pass data into table from a form using React Components"
},
{
"code": null,
"e": 30260,
"s": 30203,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 30292,
"s": 30260,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30325,
"s": 30292,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30369,
"s": 30325,
"text": "How to install Jupyter Notebook on Windows?"
},
{
"code": null,
"e": 30414,
"s": 30369,
"text": "How to Install OpenCV for Python on Windows?"
}
] |
How to create a contingency table with sum on the margins from an R data frame?
|
The sum of rows and columns on the margins in a contingency table are always useful because they are used for different type of calculations such as odds ratio, probability etc. If an R data frame has factor columns then we can create a contingency table for that data frame and it can be done by using addmargins function.
Consider the below data frame −
Live Demo
x1<-sample(LETTERS[1:4],20,replace=TRUE)
x2<-sample(c("India","USA","China"),20,replace=TRUE)
df1<-data.frame(x1,x2)
df1
x1 x2
1 B China
2 B India
3 B India
4 D India
5 B India
6 D USA
7 D USA
8 A USA
9 D USA
10 C India
11 B China
12 D China
13 D China
14 A India
15 D USA
16 A China
17 D India
18 A China
19 B China
20 A India
Creating contingency table for x1 and x2 with sum on the margins −
>CT1<-addmargins(table(df1$x1,df1$x2),c(1,2))
>CT1
China India USA Sum
A 2 2 1 5
B 3 3 0 6
C 0 1 0 1
D 2 2 4 8
Sum 7 8 5 20
Let’s have a look at another example −
Live Demo
y1<-sample(c("John","Christina","Michael","Sona"),20,replace=TRUE)
y2<-sample(c("1","2","3","4"),20,replace=TRUE)
df2<-data.frame(y1,y2)
df2
y1 y2
1 Sona 2
2 John 3
3 John 4
4 Sona 2
5 Christina 4
6 Michael 2
7 Michael 4
8 John 1
9 John 4
10 John 1
11 Michael 3
12 Sona 1
13 Sona 2
14 Michael 2
15 Michael 2
16 Michael 1
17 Michael 3
18 Christina 1
19 Christina 4
20 Sona 1
Creating contingency table for y1 and y2 with sum on the margins −
>CT2<-addmargins(table(df2$y1,df2$y2),c(1,2))
>CT2
1 2 3 4 Sum
Christina 1 0 0 2 3
John 2 0 1 2 5
Michael 1 3 2 1 7
Sona 2 3 0 0 5
Sum 6 6 3 5 20
|
[
{
"code": null,
"e": 1386,
"s": 1062,
"text": "The sum of rows and columns on the margins in a contingency table are always useful because they are used for different type of calculations such as odds ratio, probability etc. If an R data frame has factor columns then we can create a contingency table for that data frame and it can be done by using addmargins function."
},
{
"code": null,
"e": 1418,
"s": 1386,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1429,
"s": 1418,
"text": " Live Demo"
},
{
"code": null,
"e": 1550,
"s": 1429,
"text": "x1<-sample(LETTERS[1:4],20,replace=TRUE)\nx2<-sample(c(\"India\",\"USA\",\"China\"),20,replace=TRUE)\ndf1<-data.frame(x1,x2)\ndf1"
},
{
"code": null,
"e": 1770,
"s": 1550,
"text": " x1 x2\n1 B China\n2 B India\n3 B India\n4 D India\n5 B India\n6 D USA\n7 D USA\n8 A USA\n9 D USA\n10 C India\n11 B China\n12 D China\n13 D China\n14 A India\n15 D USA\n16 A China\n17 D India\n18 A China\n19 B China\n20 A India"
},
{
"code": null,
"e": 1837,
"s": 1770,
"text": "Creating contingency table for x1 and x2 with sum on the margins −"
},
{
"code": null,
"e": 1889,
"s": 1837,
"text": ">CT1<-addmargins(table(df1$x1,df1$x2),c(1,2)) \n>CT1"
},
{
"code": null,
"e": 2016,
"s": 1889,
"text": " China India USA Sum\nA 2 2 1 5\nB 3 3 0 6\nC 0 1 0 1\nD 2 2 4 8\nSum 7 8 5 20"
},
{
"code": null,
"e": 2055,
"s": 2016,
"text": "Let’s have a look at another example −"
},
{
"code": null,
"e": 2066,
"s": 2055,
"text": " Live Demo"
},
{
"code": null,
"e": 2207,
"s": 2066,
"text": "y1<-sample(c(\"John\",\"Christina\",\"Michael\",\"Sona\"),20,replace=TRUE)\ny2<-sample(c(\"1\",\"2\",\"3\",\"4\"),20,replace=TRUE)\ndf2<-data.frame(y1,y2)\ndf2"
},
{
"code": null,
"e": 2544,
"s": 2207,
"text": " y1 y2\n1 Sona 2\n2 John 3\n3 John 4\n4 Sona 2\n5 Christina 4\n6 Michael 2\n7 Michael 4\n8 John 1\n9 John 4\n10 John 1\n11 Michael 3\n12 Sona 1\n13 Sona 2\n14 Michael 2\n15 Michael 2\n16 Michael 1\n17 Michael 3\n18 Christina 1\n19 Christina 4\n20 Sona 1"
},
{
"code": null,
"e": 2611,
"s": 2544,
"text": "Creating contingency table for y1 and y2 with sum on the margins −"
},
{
"code": null,
"e": 2663,
"s": 2611,
"text": ">CT2<-addmargins(table(df2$y1,df2$y2),c(1,2)) \n>CT2"
},
{
"code": null,
"e": 2814,
"s": 2663,
"text": " 1 2 3 4 Sum\nChristina 1 0 0 2 3\nJohn 2 0 1 2 5\nMichael 1 3 2 1 7\nSona 2 3 0 0 5\nSum 6 6 3 5 20"
}
] |
Building a Web Application to Deploy Machine Learning Models | by Joseph Lee Wei En | Towards Data Science
|
If you’ve been learning Deep Learning for a while now, you may have built some really cool models using your Jupyter notebook doing a range of things, from image recognition to language translation. You probably want to let your friends try out your models (or maybe even set up a company from this), but sending them a Jupyter notebook isn’t really what you had in mind. How do you build a Web Application to deploy your Machine Learning models?
The focus of this post is building a web app around our Machine Learning model for others to try. We will go through some Web programming techniques such as HTML and Flask, as well as deploying it on the Web on a Ubuntu server on DigitalOcean.
By the end of this tutorial, other people (from all over the world) will be able to try your simple image recognition software. Your web app will look something like this page I’ve built:
157.230.156.140
This is the front page of the Web app:
Once you’ve chosen a file (please choose a file below 500kb in size), you can click “Upload”. Suppose I chose the cat image that I used previously in my Notebook, I’ll be redirected to this page with my prediction:
To get something up quickly, we’ll skip a few best practices along the way; but hopefully, we’ll come back to it in later posts!
Prerequisite:
This post assumes familiarity with building your own image recognition model; you may refer to the guide here to get up to speed:
medium.com
Once you’ve completed the tutorial above, you should have a .h5 file with a model to classify images into 10 different classes (airplane, automobile, bird, cat, deer, dog, frog, horse, ship, and truck). If you have that model file, we can begin creating a Web app around it!
If at any point you want to see the full code for what we’ll be doing in this post, please see the GitHub here.
[Note: as this section relies on a third party service, DigitalOcean, the instructions might change over time]
The purpose of this post is to teach you how to deploy a simple Web application on the Web for others to try. For this, we need a Web server, which is like a computer that will send information (the webpage) to other computers who request for it. We will set up a Web server on DigitalOcean, and you may use my referral link here (or just go to the website directly):
m.do.co
In that link, create an account on the right panel:
DigitalOcean will then walk you through the steps in creating an account:
Once you click the link in the confirmation email, you will need to key in your billing information. After keying in your billing information, you will be led to this page to create your first project:
After keying in the project name and what your project is for, you can scroll down to the bottom and ignore the other questions. Click the nice blue Start banner at the bottom:
You should then reach this landing page:
The Web server we will need is called a “droplet” in DigitalOcean. Hover over the ‘plus’ below the heading ‘Create a Droplet’ and you’ll see this:
Now click on the blue ‘Create Droplet’ button. You should see this page:
The default (highlighted above) is Ubuntu, which is what this tutorial will be based on.
If you scroll down to Choose a plan, you can choose how powerful you want your Web server to be. The more expensive plans that you choose, you can process larger images and process them faster. I suggest picking the $10/month one, as we will need some memory to process images. However, the $5/month should be good enough to try this tutorial out:
If you scroll down further, you can also choose which physical data center you want your server to be on. I’ve chosen SF(2):
You can ignore the other options on this page for now. Scroll down to the very bottom, give your droplet a name and click the green “Create” button.
It will take a little while for your droplet to initialize, but once you’re down, you should see this as your front page:
Note that there are four numbers (157.230.156.140) which will be the IP address for our droplet. An IP address is like any web URL (like www.intuitivedeeplearning.com) so you can just enter it into your address bar. If you want a domain name for it so that others can type in English words into the address bar rather than a series of four numbers, you’ll have to purchase it and set up separately.
At this point, you’ll get an email like this:
Copy your password and then go back to the DigitalOcean console. If you click the three dots on the side of your droplet, a pop-up should appear.
Click on “Access console”. This will open up a window which will allow you to communicate to your Web server.
Now, type in the username and password you’ve got in your email. The username should be ‘root’. The password will not show, but if you click Cntrl-V and Enter, you should be able to get access in. The system will prompt you to change your password. Enter your current password (Cntrl-V, Enter) and then type in your new password twice.
Once you’re done, you should see a screen like this:
Now don’t be intimidated by the console. The console looks scary, but it really is a way to speak to the computer by typing very specific commands. For example, try asking what Python 3 version your server is using by typing
python3 --version
and clicking Enter. You should see something like this:
The computer then tells you the version of Python your server is using, which for me right now is Python 3.6.7.
Now, it’s time to create your first HTML file. HTML is a language which Web browsers understand, and it will turn the HTML code into the Web page you’re looking at right now. To create our files, we will need to use something like a text editor, like Notepad but on your server. We’ll be using an editor called nano for this tutorial.
Our first webpage will be called index.html which is the front page of your website. Now, type this command to your server:
nano index.html
In the console, it’ll look like this:
This command means to open up the file index.html with the editor nano. Since index.html doesn’t exist, it will create the file for you. You should see something like this on your screen now:
As the bottom suggests, this is a new file for you to type stuff in. You can type any sentence in to this Notepad-like app, for example:
This is my first Webpage!
Your console will look like this:
Now, we’ll exit out of this Notepad by clicking Cntrl-X. At the bottom, they will ask you if you wish to save your file:
You have to save your changes, so type ‘Y’. Now, they will ask you what your filename will be:
Just click Enter on your keyboard, and you’ll be done! Now, this might seem a bit less user-friendly than your standard Notepad, but just bear with it for a while.
You’ve now got a HTML file on your Webserver, all you need to do is to ‘open’ your Webserver. To do so, type this:
python3 -m http.server 80
‘80’ is the standard port which serves HTTP files. Your console should now look like this:
Now, your website is online! Go to the IP address for your droplet, which are the four numbers you see beside your droplet in DigitalOcean. You should be able to see your first webpage, which is the content you’ve written in index.html through the nano editor just now.
Congratulations — you’ve set up your first Web sever on DigitalOcean! To stop the Webpage and get back to typing commands, just press Cntrl-C. Now, we are ready to build our first Machine Learning Web app on our Web server!
Your Web app can be thought of as two parts — the “backend” and the “frontend”. Think of the “backend” application as the brains behind the operations — you might not see it, but the computations are all done here. This is where we define the logic of how an user will interact with your web application, and what happens to the user’s inputs. It is also where we will run our Machine Learning model. The “frontend” on the other hand, defines what the users see, touch and experience. This is like the face of your Web application and will be what your user interacts directly with.
In this section, we will define the backend — we’ll create the “brains” first, and then we’ll see how to fit in the “face” later. In particular, we will:
Load our Machine Learning model;Define what happens when he uploads the photo in the main homepage; andApply our Machine Learning model to the image and show the user the results in a separate “prediction” page.
Load our Machine Learning model;
Define what happens when he uploads the photo in the main homepage; and
Apply our Machine Learning model to the image and show the user the results in a separate “prediction” page.
In the next section, we will define how the user sees the two webpages — the homepage and the “prediction” page. But for now, let’s focus on the backend, and we’ll be using Flask as a framework to build it.
Flask is a simple web application framework that we can use to build the backend of web apps and get started quickly. In this tutorial, I will explain enough to create the web app around your Machine Learning model. Unfortunately, I will not be explaining every line of Flask code and structure; you can learn more about Flask here.
First, let’s install Flask. To do so, we first have to install pip3, which helps us to install other Python packages like Flask on our server. In your console, type
apt install python3-pip
Your console should look like this:
Once you click Enter, it will tell you the packages that will be installed. Type in “Y” to continue. Now that pip3 is installed, enter the command into your console:
pip3 install Flask
Your console should look like this:
While we’re installing Flask, be sure to install all the Python packages we had previously now on the server:
pip3 install keraspip3 install tensorflowpip3 install scikit-image
Now, we will organise our files in the server. We will createa Python file for our web backend, which we will call imgrec_webapp.py(using nano like we did earlier). We will then have two folders, one to store the uploaded images (which we will call uploads) and one to store the HTML files for your frontend (called templates). To create a folder, type mkdir folder_name into the console, where “folder_name” can be replaced by your desired name. So the two commands to type are:
mkdir uploadsmkdir templates
Now, we need to upload our model, my_cifar10_model.h5 into the server. Since the model is in my local computer, unfortunately, we can’t use the console to upload the model from my desktop. Instead, we will use Windows PowerShell. This is an app that you likely have installed already if you are using Windows:
When you’ve opened Windows Powershell, type in this command to upload your model, and be sure to replace the instructions in triangular brackets:
scp <where your model is stored>\my_cifar10_model.h5 <Droplet IP address>:~
In my case, I would type:
scp C:\Users\user\Desktop\my_cifar10_model.h5 root@157.230.156.140:~
If it is your first time connecting from Powershell, a prompt like this will appear. Simply click “yes”.
Type in your password, and once you’re done, it should look something like this:
And now your model is on the Droplet! Now, go back to the DigitalOcean console where you accessed your server previously. Alternatively, if you like the PowerShell interface, you can use PowerShell to connect to your server like this:
ssh root@<your Droplet IP>
In my case, it would be:
ssh root@157.230.156.140
And voila! You no longer need to go to DigitalOcean to get your server console. Once you’re in your console, type ls (which stands for list) to make sure that you’ve got all your files and folders:
Now that we’ve got everything set up, we can (finally) start coding our backend application. Open up the Python file you have created, imgrec_webapp.py. As usual, we will import some of the necessary functions that you will need later:
import osfrom flask import Flask, request, redirect, url_for, render_templatefrom werkzeug.utils import secure_filename
Then, we create an instance of a Flask app which just one line of code:
app = Flask(__name__)
We’ll add more to the Flask app later. For now, let’s load our Machine Learning model that we’ve already saved in our pre-requisite tutorial my_cifar10_model.h5. We call the following functions and load the model like this:
from keras.models import load_modelfrom keras.backend import set_sessionfrom skimage.transform import resizeimport matplotlib.pyplot as pltimport tensorflow as tfimport numpy as npprint("Loading model")global sesssess = tf.Session()set_session(sess)global modelmodel = load_model('my_cifar10_model.h5')global graphgraph = tf.get_default_graph()
Now that we’ve got our model running, let’s add to our Flask web app. The first thing we want to do is state what the web application will do when it hits a certain URL. To define that, we use the@app.route() function. For my main page, I will use the default URL (i.e. I won’t have any additional “suffixes” to my URL) and so my first parameter will be '/'. An user will interact with my main page in two ways:
Load the web page from the server into his browserUpload his image and send it to the server
Load the web page from the server into his browser
Upload his image and send it to the server
This requires two different methods of interacting with this page: Interaction #1 will use “GET” (a method primarily for an user to request data from a resource), while interaction #2 will use “POST” (a method primarily for an user to send data to a server to create or update a resource). The code block below therefore says that if I’m at interaction #2, save the file in my “uploads” folder and go to the “prediction” page (and pass in the parameter filename). If not, I’m at interaction #1 and just render the webpage “index.html”.
@app.route('/', methods=['GET', 'POST'])def main_page(): if request.method == 'POST': file = request.files['file'] filename = secure_filename(file.filename) file.save(os.path.join('uploads', filename)) return redirect(url_for('prediction', filename=filename)) return render_template('index.html')
Now, we have to create a “prediction” page to go to, and define what the Web app should do when an user is at that page. We use the @app.route()function again, and say that if an user is at the /prediction/<filename> subdirectory, pass in the <filename> into the Python function that I define for that page.
In this prediction page, I will:
Read the image based on the filename, and store it as my_imageResize the image to 32x32x3, which is the format that my model reads it in, and store it as my_image_reUsing the model, predict the probabilities that the image falls into the various classes, and put that under the variableprobabilitiesFind the label and the probability of the top three most probable classes, and put them under predictionsLoad the template of my webpage predict.html and give them the predictions in Step 4.
Read the image based on the filename, and store it as my_image
Resize the image to 32x32x3, which is the format that my model reads it in, and store it as my_image_re
Using the model, predict the probabilities that the image falls into the various classes, and put that under the variableprobabilities
Find the label and the probability of the top three most probable classes, and put them under predictions
Load the template of my webpage predict.html and give them the predictions in Step 4.
The five steps are reflected below:
@app.route('/prediction/<filename>')def prediction(filename): #Step 1 my_image = plt.imread(os.path.join('uploads', filename)) #Step 2 my_image_re = resize(my_image, (32,32,3)) #Step 3 with graph.as_default(): set_session(sess) probabilities = model.predict(np.array( [my_image_re,] ))[0,:] print(probabilities)#Step 4 number_to_class = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'] index = np.argsort(probabilities) predictions = { "class1":number_to_class[index[9]], "class2":number_to_class[index[8]], "class3":number_to_class[index[7]], "prob1":probabilities[index[9]], "prob2":probabilities[index[8]], "prob3":probabilities[index[7]], }#Step 5 return render_template('predict.html', predictions=predictions)
All this should be pretty familiar, if you need a refresher, please visit the tutorial:
medium.com
Lastly, we run the app with port 80, which is the standard port for accessing web pages. Type this at the end of your Python file:
app.run(host='0.0.0.0', port=80)
Now we have the backbones of our Web application. You might have noticed that we are still missing a few different pieces though. In particular, we’ve called on the HTML web pages like index.html and predict.html but we’ve not built them yet! We will do so in the next section.
Do also note that in this bare-bones tutorial, we’ve skipped many good practices. You may want to try incorporating some of these practices if you know how to (or Google it!):
Creating our Web app in an Anaconda environment (like we did in Anaconda Navigator previously)
Catching errors such as someone not uploading any file, or with a blank filename
Checking link extensions that people are uploading ‘.jpg’ files
When a user interacts with your web application, they do so via the web pages, which is what we will be building in this section. Go into the templates folder by typing in the console:
cd templates
Create the two template files we need, index.html and predict.html. If you type ls you should see those two files under templates:
We use a language called HyperText Markup Language (HTML), which just tells the browser how to render the content that you have. To generalise it a little bit, we tag the content with tags like “header” or “paragraph” and then we tell the browser how to display content with those type of tags. For example, if I want to tag the words “Hello” as a “header 1” type, I’ll write:
<h1>Hello</h1>
Usually, when you start the tag (i.e. <h1>), you have to close the tag as well to show where it ends (i.e. </h1>). We’ll learn as we go, so let’s start with index.html. To remind you how the page will look like, we are trying to build something like this:
The first thing we start index.html with is this line:
<!doctype html>
This tells the browser what kind of document type to expect (i.e. HTML). We then begin the document with a<html> tag, which we will close it at the very end. Now, we also define the head of the document, which contains the “meta-data” of the document. Here, I’ve defined the title and I’ve linked a Bootstrap stylesheet, where other people have already defined styles for the various tags. I can therefore leave large amounts of the styling to what others have coded for us, unless there are some aspects I need to customise.
<html><head> <title>Classify your Image!</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"></head>
Now, we define the body:
<body style="background-color:black"><div id="maintext" style="position:absolute; margin:auto; width:700px; height:200px; text-align:center; top:0; bottom: 0; left: 0; right: 0;"> <h1 class="text-light mb-2"> Upload your image to be classified! </h1> <h4 class="text-light mb-5">(Please upload images less than 500kb in size)</h4> <form method=post enctype=multipart/form-data> <p class="text-light"> <input type=file name=file> <input type=submit value=Upload> </p> </form></div></body></html>
First, I tell HTML that I want a background color of black. Then, I have a div container so that I can contain the following content together. I want the container to be in the middle of the page with a certain height and width and margins, so I define that in the style. Within my div container, I have three main content pieces:
Large header (h1) that says “Upload your image to be classified!” (Note: mb-2 in the style just says add a margin of “medium size” at the bottom)Small header (h4) that says “(Please upload images less than 500kb in size)”A “form” that allows me to upload a file and then submit that form. We use the POST method to submit the form (recall how we defined the backend?)
Large header (h1) that says “Upload your image to be classified!” (Note: mb-2 in the style just says add a margin of “medium size” at the bottom)
Small header (h4) that says “(Please upload images less than 500kb in size)”
A “form” that allows me to upload a file and then submit that form. We use the POST method to submit the form (recall how we defined the backend?)
Once I’ve defined these three content pieces within my div container, I close the body and html tags and I’m done! Do note that it is good practice to re-organizing your code into CSS files and HTML files so that we can separate the style from the content — for the purpose of this tutorial, we’ve taken some shortcuts!
Now, we move on to the predict.html page. Remember how the page is supposed to look like:
For the HTML code, the head is still the same as index.html, but there are a few new elements introduced in the body:
<!doctype html><html><head> <title>Your Prediction!</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"></head><body style="background-color:black"><div id="maintext" style="position:absolute; margin:auto; width:700px; height:300px; text-align:center; top:0; bottom: 0; left: 0; right: 0;"> <h1 class="text-light mb-5"> Your Prediction </h1> <p class="text-light"> My algorithm gave this prediction: </p> <table class="table-bordered text-light" style="width:100%"> <tr> <th>Rank</th> <th>Class</th> <th>Probability</th> </tr> <tr> <td>Most Likely:</td> <td>{{ predictions.class1 }}</td> <td>{{ predictions.prob1 }}</td> </tr> <tr> <td>2nd Most Likely:</td> <td>{{ predictions.class2 }}</td> <td>{{ predictions.prob2 }}</td> </tr> <tr> <td>3rd Most Likely:</td> <td>{{ predictions.class3 }}</td> <td>{{ predictions.prob3 }}</td> </tr> </table><a href="{{ url_for('main_page') }}"><button class="button mt-3">Try again?</button></a></div></body></html>
In my div container (which is the same as in index.html), I now have the following content:
A header (h1) that says “Your Prediction”A paragraph (p) that says “My algorithm gave this prediction:”A table with three columns and four rows. Each row in the table is tagged with <tr> . For each row, the headers are tagged with <th> and the text for each column is tagged with<td>. Note that the content for my predictions are not fixed — it depends on what my model gives me, which depends on what the user uploaded. This is where I need to interact with the backend. If you recall, in my prediction backend, the last line of the function is return render_template(‘predict.html’, predictions=predictions). This means that when I rendered the “predict.html”, I pass to my frontend the variables of predictions, and these variables will appear in my frontend wherever I call them using the double curly braces {{ ... }}. Therefore, {{ predictions.class1 }} will be automatically filled in with whatever the model predicted as the most probable class.A button to link me back to the main page. I use {{ url_for(‘main_page’) }} because main_page is the name of the function in my backend that defined the main page. Therefore, whatever the URL is will be filled in automatically here.
A header (h1) that says “Your Prediction”
A paragraph (p) that says “My algorithm gave this prediction:”
A table with three columns and four rows. Each row in the table is tagged with <tr> . For each row, the headers are tagged with <th> and the text for each column is tagged with<td>. Note that the content for my predictions are not fixed — it depends on what my model gives me, which depends on what the user uploaded. This is where I need to interact with the backend. If you recall, in my prediction backend, the last line of the function is return render_template(‘predict.html’, predictions=predictions). This means that when I rendered the “predict.html”, I pass to my frontend the variables of predictions, and these variables will appear in my frontend wherever I call them using the double curly braces {{ ... }}. Therefore, {{ predictions.class1 }} will be automatically filled in with whatever the model predicted as the most probable class.
A button to link me back to the main page. I use {{ url_for(‘main_page’) }} because main_page is the name of the function in my backend that defined the main page. Therefore, whatever the URL is will be filled in automatically here.
And there we have it! Again, it is good practice to re-organizing your code into CSS files and HTML files so that we can separate the style from the content. This way, if we want to consistently change the style of the div for example, we don’t need to go to both index.html and predict.html to change it.
Now, all there is left to do is to run the Web application. Go back to the console and type this:
python3 imgrec_webapp.py
You’ll see a whole bunch of warning messages, but you can ignore them. The most important thing is that at the end, you see this screen:
Now, you can enter your droplet’s IP address into your browser and click Enter.
You should see your application up and running, and you should be able to upload a small image and get a prediction! Do note that the first image will always take a lot longer, so be patient! It will be faster after that!
Consolidated Summary: In this post, we’ve written a web application around our image recognition model by:
Setting up on the cloud (DigitalOcean)
Creating the Web App Backend using Flask
Creating the Web App Frontend using HTML
Congratulations! You’ve built your very first web application. We are still quite far away from building a production-level web application, and we have not incorporated many necessary practices if we are to scale this up. But at least we have some semblance of a Web application running, and we can incorporate these practices to our base framework.
What’s Next: In our next Coding Companion Part 3 (link to be released), we will explore how to code up our own Recurrent Neural Networks (RNNs) to deal with natural language! Be sure to get an intuitive understanding of RNNs here:
Intuitive Deep Learning Part 3: RNNs for Natural Language Processing
Note: This story first appeared in Intuitive Deep Learning:
|
[
{
"code": null,
"e": 619,
"s": 172,
"text": "If you’ve been learning Deep Learning for a while now, you may have built some really cool models using your Jupyter notebook doing a range of things, from image recognition to language translation. You probably want to let your friends try out your models (or maybe even set up a company from this), but sending them a Jupyter notebook isn’t really what you had in mind. How do you build a Web Application to deploy your Machine Learning models?"
},
{
"code": null,
"e": 863,
"s": 619,
"text": "The focus of this post is building a web app around our Machine Learning model for others to try. We will go through some Web programming techniques such as HTML and Flask, as well as deploying it on the Web on a Ubuntu server on DigitalOcean."
},
{
"code": null,
"e": 1051,
"s": 863,
"text": "By the end of this tutorial, other people (from all over the world) will be able to try your simple image recognition software. Your web app will look something like this page I’ve built:"
},
{
"code": null,
"e": 1067,
"s": 1051,
"text": "157.230.156.140"
},
{
"code": null,
"e": 1106,
"s": 1067,
"text": "This is the front page of the Web app:"
},
{
"code": null,
"e": 1321,
"s": 1106,
"text": "Once you’ve chosen a file (please choose a file below 500kb in size), you can click “Upload”. Suppose I chose the cat image that I used previously in my Notebook, I’ll be redirected to this page with my prediction:"
},
{
"code": null,
"e": 1450,
"s": 1321,
"text": "To get something up quickly, we’ll skip a few best practices along the way; but hopefully, we’ll come back to it in later posts!"
},
{
"code": null,
"e": 1464,
"s": 1450,
"text": "Prerequisite:"
},
{
"code": null,
"e": 1594,
"s": 1464,
"text": "This post assumes familiarity with building your own image recognition model; you may refer to the guide here to get up to speed:"
},
{
"code": null,
"e": 1605,
"s": 1594,
"text": "medium.com"
},
{
"code": null,
"e": 1880,
"s": 1605,
"text": "Once you’ve completed the tutorial above, you should have a .h5 file with a model to classify images into 10 different classes (airplane, automobile, bird, cat, deer, dog, frog, horse, ship, and truck). If you have that model file, we can begin creating a Web app around it!"
},
{
"code": null,
"e": 1992,
"s": 1880,
"text": "If at any point you want to see the full code for what we’ll be doing in this post, please see the GitHub here."
},
{
"code": null,
"e": 2103,
"s": 1992,
"text": "[Note: as this section relies on a third party service, DigitalOcean, the instructions might change over time]"
},
{
"code": null,
"e": 2471,
"s": 2103,
"text": "The purpose of this post is to teach you how to deploy a simple Web application on the Web for others to try. For this, we need a Web server, which is like a computer that will send information (the webpage) to other computers who request for it. We will set up a Web server on DigitalOcean, and you may use my referral link here (or just go to the website directly):"
},
{
"code": null,
"e": 2479,
"s": 2471,
"text": "m.do.co"
},
{
"code": null,
"e": 2531,
"s": 2479,
"text": "In that link, create an account on the right panel:"
},
{
"code": null,
"e": 2605,
"s": 2531,
"text": "DigitalOcean will then walk you through the steps in creating an account:"
},
{
"code": null,
"e": 2807,
"s": 2605,
"text": "Once you click the link in the confirmation email, you will need to key in your billing information. After keying in your billing information, you will be led to this page to create your first project:"
},
{
"code": null,
"e": 2984,
"s": 2807,
"text": "After keying in the project name and what your project is for, you can scroll down to the bottom and ignore the other questions. Click the nice blue Start banner at the bottom:"
},
{
"code": null,
"e": 3025,
"s": 2984,
"text": "You should then reach this landing page:"
},
{
"code": null,
"e": 3172,
"s": 3025,
"text": "The Web server we will need is called a “droplet” in DigitalOcean. Hover over the ‘plus’ below the heading ‘Create a Droplet’ and you’ll see this:"
},
{
"code": null,
"e": 3245,
"s": 3172,
"text": "Now click on the blue ‘Create Droplet’ button. You should see this page:"
},
{
"code": null,
"e": 3334,
"s": 3245,
"text": "The default (highlighted above) is Ubuntu, which is what this tutorial will be based on."
},
{
"code": null,
"e": 3682,
"s": 3334,
"text": "If you scroll down to Choose a plan, you can choose how powerful you want your Web server to be. The more expensive plans that you choose, you can process larger images and process them faster. I suggest picking the $10/month one, as we will need some memory to process images. However, the $5/month should be good enough to try this tutorial out:"
},
{
"code": null,
"e": 3807,
"s": 3682,
"text": "If you scroll down further, you can also choose which physical data center you want your server to be on. I’ve chosen SF(2):"
},
{
"code": null,
"e": 3956,
"s": 3807,
"text": "You can ignore the other options on this page for now. Scroll down to the very bottom, give your droplet a name and click the green “Create” button."
},
{
"code": null,
"e": 4078,
"s": 3956,
"text": "It will take a little while for your droplet to initialize, but once you’re down, you should see this as your front page:"
},
{
"code": null,
"e": 4477,
"s": 4078,
"text": "Note that there are four numbers (157.230.156.140) which will be the IP address for our droplet. An IP address is like any web URL (like www.intuitivedeeplearning.com) so you can just enter it into your address bar. If you want a domain name for it so that others can type in English words into the address bar rather than a series of four numbers, you’ll have to purchase it and set up separately."
},
{
"code": null,
"e": 4523,
"s": 4477,
"text": "At this point, you’ll get an email like this:"
},
{
"code": null,
"e": 4669,
"s": 4523,
"text": "Copy your password and then go back to the DigitalOcean console. If you click the three dots on the side of your droplet, a pop-up should appear."
},
{
"code": null,
"e": 4779,
"s": 4669,
"text": "Click on “Access console”. This will open up a window which will allow you to communicate to your Web server."
},
{
"code": null,
"e": 5115,
"s": 4779,
"text": "Now, type in the username and password you’ve got in your email. The username should be ‘root’. The password will not show, but if you click Cntrl-V and Enter, you should be able to get access in. The system will prompt you to change your password. Enter your current password (Cntrl-V, Enter) and then type in your new password twice."
},
{
"code": null,
"e": 5168,
"s": 5115,
"text": "Once you’re done, you should see a screen like this:"
},
{
"code": null,
"e": 5393,
"s": 5168,
"text": "Now don’t be intimidated by the console. The console looks scary, but it really is a way to speak to the computer by typing very specific commands. For example, try asking what Python 3 version your server is using by typing"
},
{
"code": null,
"e": 5411,
"s": 5393,
"text": "python3 --version"
},
{
"code": null,
"e": 5467,
"s": 5411,
"text": "and clicking Enter. You should see something like this:"
},
{
"code": null,
"e": 5579,
"s": 5467,
"text": "The computer then tells you the version of Python your server is using, which for me right now is Python 3.6.7."
},
{
"code": null,
"e": 5914,
"s": 5579,
"text": "Now, it’s time to create your first HTML file. HTML is a language which Web browsers understand, and it will turn the HTML code into the Web page you’re looking at right now. To create our files, we will need to use something like a text editor, like Notepad but on your server. We’ll be using an editor called nano for this tutorial."
},
{
"code": null,
"e": 6038,
"s": 5914,
"text": "Our first webpage will be called index.html which is the front page of your website. Now, type this command to your server:"
},
{
"code": null,
"e": 6054,
"s": 6038,
"text": "nano index.html"
},
{
"code": null,
"e": 6092,
"s": 6054,
"text": "In the console, it’ll look like this:"
},
{
"code": null,
"e": 6284,
"s": 6092,
"text": "This command means to open up the file index.html with the editor nano. Since index.html doesn’t exist, it will create the file for you. You should see something like this on your screen now:"
},
{
"code": null,
"e": 6421,
"s": 6284,
"text": "As the bottom suggests, this is a new file for you to type stuff in. You can type any sentence in to this Notepad-like app, for example:"
},
{
"code": null,
"e": 6447,
"s": 6421,
"text": "This is my first Webpage!"
},
{
"code": null,
"e": 6481,
"s": 6447,
"text": "Your console will look like this:"
},
{
"code": null,
"e": 6602,
"s": 6481,
"text": "Now, we’ll exit out of this Notepad by clicking Cntrl-X. At the bottom, they will ask you if you wish to save your file:"
},
{
"code": null,
"e": 6697,
"s": 6602,
"text": "You have to save your changes, so type ‘Y’. Now, they will ask you what your filename will be:"
},
{
"code": null,
"e": 6861,
"s": 6697,
"text": "Just click Enter on your keyboard, and you’ll be done! Now, this might seem a bit less user-friendly than your standard Notepad, but just bear with it for a while."
},
{
"code": null,
"e": 6976,
"s": 6861,
"text": "You’ve now got a HTML file on your Webserver, all you need to do is to ‘open’ your Webserver. To do so, type this:"
},
{
"code": null,
"e": 7002,
"s": 6976,
"text": "python3 -m http.server 80"
},
{
"code": null,
"e": 7093,
"s": 7002,
"text": "‘80’ is the standard port which serves HTTP files. Your console should now look like this:"
},
{
"code": null,
"e": 7363,
"s": 7093,
"text": "Now, your website is online! Go to the IP address for your droplet, which are the four numbers you see beside your droplet in DigitalOcean. You should be able to see your first webpage, which is the content you’ve written in index.html through the nano editor just now."
},
{
"code": null,
"e": 7587,
"s": 7363,
"text": "Congratulations — you’ve set up your first Web sever on DigitalOcean! To stop the Webpage and get back to typing commands, just press Cntrl-C. Now, we are ready to build our first Machine Learning Web app on our Web server!"
},
{
"code": null,
"e": 8170,
"s": 7587,
"text": "Your Web app can be thought of as two parts — the “backend” and the “frontend”. Think of the “backend” application as the brains behind the operations — you might not see it, but the computations are all done here. This is where we define the logic of how an user will interact with your web application, and what happens to the user’s inputs. It is also where we will run our Machine Learning model. The “frontend” on the other hand, defines what the users see, touch and experience. This is like the face of your Web application and will be what your user interacts directly with."
},
{
"code": null,
"e": 8324,
"s": 8170,
"text": "In this section, we will define the backend — we’ll create the “brains” first, and then we’ll see how to fit in the “face” later. In particular, we will:"
},
{
"code": null,
"e": 8536,
"s": 8324,
"text": "Load our Machine Learning model;Define what happens when he uploads the photo in the main homepage; andApply our Machine Learning model to the image and show the user the results in a separate “prediction” page."
},
{
"code": null,
"e": 8569,
"s": 8536,
"text": "Load our Machine Learning model;"
},
{
"code": null,
"e": 8641,
"s": 8569,
"text": "Define what happens when he uploads the photo in the main homepage; and"
},
{
"code": null,
"e": 8750,
"s": 8641,
"text": "Apply our Machine Learning model to the image and show the user the results in a separate “prediction” page."
},
{
"code": null,
"e": 8957,
"s": 8750,
"text": "In the next section, we will define how the user sees the two webpages — the homepage and the “prediction” page. But for now, let’s focus on the backend, and we’ll be using Flask as a framework to build it."
},
{
"code": null,
"e": 9290,
"s": 8957,
"text": "Flask is a simple web application framework that we can use to build the backend of web apps and get started quickly. In this tutorial, I will explain enough to create the web app around your Machine Learning model. Unfortunately, I will not be explaining every line of Flask code and structure; you can learn more about Flask here."
},
{
"code": null,
"e": 9455,
"s": 9290,
"text": "First, let’s install Flask. To do so, we first have to install pip3, which helps us to install other Python packages like Flask on our server. In your console, type"
},
{
"code": null,
"e": 9479,
"s": 9455,
"text": "apt install python3-pip"
},
{
"code": null,
"e": 9515,
"s": 9479,
"text": "Your console should look like this:"
},
{
"code": null,
"e": 9681,
"s": 9515,
"text": "Once you click Enter, it will tell you the packages that will be installed. Type in “Y” to continue. Now that pip3 is installed, enter the command into your console:"
},
{
"code": null,
"e": 9700,
"s": 9681,
"text": "pip3 install Flask"
},
{
"code": null,
"e": 9736,
"s": 9700,
"text": "Your console should look like this:"
},
{
"code": null,
"e": 9846,
"s": 9736,
"text": "While we’re installing Flask, be sure to install all the Python packages we had previously now on the server:"
},
{
"code": null,
"e": 9913,
"s": 9846,
"text": "pip3 install keraspip3 install tensorflowpip3 install scikit-image"
},
{
"code": null,
"e": 10393,
"s": 9913,
"text": "Now, we will organise our files in the server. We will createa Python file for our web backend, which we will call imgrec_webapp.py(using nano like we did earlier). We will then have two folders, one to store the uploaded images (which we will call uploads) and one to store the HTML files for your frontend (called templates). To create a folder, type mkdir folder_name into the console, where “folder_name” can be replaced by your desired name. So the two commands to type are:"
},
{
"code": null,
"e": 10422,
"s": 10393,
"text": "mkdir uploadsmkdir templates"
},
{
"code": null,
"e": 10732,
"s": 10422,
"text": "Now, we need to upload our model, my_cifar10_model.h5 into the server. Since the model is in my local computer, unfortunately, we can’t use the console to upload the model from my desktop. Instead, we will use Windows PowerShell. This is an app that you likely have installed already if you are using Windows:"
},
{
"code": null,
"e": 10878,
"s": 10732,
"text": "When you’ve opened Windows Powershell, type in this command to upload your model, and be sure to replace the instructions in triangular brackets:"
},
{
"code": null,
"e": 10954,
"s": 10878,
"text": "scp <where your model is stored>\\my_cifar10_model.h5 <Droplet IP address>:~"
},
{
"code": null,
"e": 10980,
"s": 10954,
"text": "In my case, I would type:"
},
{
"code": null,
"e": 11049,
"s": 10980,
"text": "scp C:\\Users\\user\\Desktop\\my_cifar10_model.h5 root@157.230.156.140:~"
},
{
"code": null,
"e": 11154,
"s": 11049,
"text": "If it is your first time connecting from Powershell, a prompt like this will appear. Simply click “yes”."
},
{
"code": null,
"e": 11235,
"s": 11154,
"text": "Type in your password, and once you’re done, it should look something like this:"
},
{
"code": null,
"e": 11470,
"s": 11235,
"text": "And now your model is on the Droplet! Now, go back to the DigitalOcean console where you accessed your server previously. Alternatively, if you like the PowerShell interface, you can use PowerShell to connect to your server like this:"
},
{
"code": null,
"e": 11497,
"s": 11470,
"text": "ssh root@<your Droplet IP>"
},
{
"code": null,
"e": 11522,
"s": 11497,
"text": "In my case, it would be:"
},
{
"code": null,
"e": 11547,
"s": 11522,
"text": "ssh root@157.230.156.140"
},
{
"code": null,
"e": 11745,
"s": 11547,
"text": "And voila! You no longer need to go to DigitalOcean to get your server console. Once you’re in your console, type ls (which stands for list) to make sure that you’ve got all your files and folders:"
},
{
"code": null,
"e": 11981,
"s": 11745,
"text": "Now that we’ve got everything set up, we can (finally) start coding our backend application. Open up the Python file you have created, imgrec_webapp.py. As usual, we will import some of the necessary functions that you will need later:"
},
{
"code": null,
"e": 12101,
"s": 11981,
"text": "import osfrom flask import Flask, request, redirect, url_for, render_templatefrom werkzeug.utils import secure_filename"
},
{
"code": null,
"e": 12173,
"s": 12101,
"text": "Then, we create an instance of a Flask app which just one line of code:"
},
{
"code": null,
"e": 12195,
"s": 12173,
"text": "app = Flask(__name__)"
},
{
"code": null,
"e": 12419,
"s": 12195,
"text": "We’ll add more to the Flask app later. For now, let’s load our Machine Learning model that we’ve already saved in our pre-requisite tutorial my_cifar10_model.h5. We call the following functions and load the model like this:"
},
{
"code": null,
"e": 12764,
"s": 12419,
"text": "from keras.models import load_modelfrom keras.backend import set_sessionfrom skimage.transform import resizeimport matplotlib.pyplot as pltimport tensorflow as tfimport numpy as npprint(\"Loading model\")global sesssess = tf.Session()set_session(sess)global modelmodel = load_model('my_cifar10_model.h5')global graphgraph = tf.get_default_graph()"
},
{
"code": null,
"e": 13176,
"s": 12764,
"text": "Now that we’ve got our model running, let’s add to our Flask web app. The first thing we want to do is state what the web application will do when it hits a certain URL. To define that, we use the@app.route() function. For my main page, I will use the default URL (i.e. I won’t have any additional “suffixes” to my URL) and so my first parameter will be '/'. An user will interact with my main page in two ways:"
},
{
"code": null,
"e": 13269,
"s": 13176,
"text": "Load the web page from the server into his browserUpload his image and send it to the server"
},
{
"code": null,
"e": 13320,
"s": 13269,
"text": "Load the web page from the server into his browser"
},
{
"code": null,
"e": 13363,
"s": 13320,
"text": "Upload his image and send it to the server"
},
{
"code": null,
"e": 13899,
"s": 13363,
"text": "This requires two different methods of interacting with this page: Interaction #1 will use “GET” (a method primarily for an user to request data from a resource), while interaction #2 will use “POST” (a method primarily for an user to send data to a server to create or update a resource). The code block below therefore says that if I’m at interaction #2, save the file in my “uploads” folder and go to the “prediction” page (and pass in the parameter filename). If not, I’m at interaction #1 and just render the webpage “index.html”."
},
{
"code": null,
"e": 14230,
"s": 13899,
"text": "@app.route('/', methods=['GET', 'POST'])def main_page(): if request.method == 'POST': file = request.files['file'] filename = secure_filename(file.filename) file.save(os.path.join('uploads', filename)) return redirect(url_for('prediction', filename=filename)) return render_template('index.html')"
},
{
"code": null,
"e": 14538,
"s": 14230,
"text": "Now, we have to create a “prediction” page to go to, and define what the Web app should do when an user is at that page. We use the @app.route()function again, and say that if an user is at the /prediction/<filename> subdirectory, pass in the <filename> into the Python function that I define for that page."
},
{
"code": null,
"e": 14571,
"s": 14538,
"text": "In this prediction page, I will:"
},
{
"code": null,
"e": 15061,
"s": 14571,
"text": "Read the image based on the filename, and store it as my_imageResize the image to 32x32x3, which is the format that my model reads it in, and store it as my_image_reUsing the model, predict the probabilities that the image falls into the various classes, and put that under the variableprobabilitiesFind the label and the probability of the top three most probable classes, and put them under predictionsLoad the template of my webpage predict.html and give them the predictions in Step 4."
},
{
"code": null,
"e": 15124,
"s": 15061,
"text": "Read the image based on the filename, and store it as my_image"
},
{
"code": null,
"e": 15228,
"s": 15124,
"text": "Resize the image to 32x32x3, which is the format that my model reads it in, and store it as my_image_re"
},
{
"code": null,
"e": 15363,
"s": 15228,
"text": "Using the model, predict the probabilities that the image falls into the various classes, and put that under the variableprobabilities"
},
{
"code": null,
"e": 15469,
"s": 15363,
"text": "Find the label and the probability of the top three most probable classes, and put them under predictions"
},
{
"code": null,
"e": 15555,
"s": 15469,
"text": "Load the template of my webpage predict.html and give them the predictions in Step 4."
},
{
"code": null,
"e": 15591,
"s": 15555,
"text": "The five steps are reflected below:"
},
{
"code": null,
"e": 16451,
"s": 15591,
"text": "@app.route('/prediction/<filename>')def prediction(filename): #Step 1 my_image = plt.imread(os.path.join('uploads', filename)) #Step 2 my_image_re = resize(my_image, (32,32,3)) #Step 3 with graph.as_default(): set_session(sess) probabilities = model.predict(np.array( [my_image_re,] ))[0,:] print(probabilities)#Step 4 number_to_class = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'] index = np.argsort(probabilities) predictions = { \"class1\":number_to_class[index[9]], \"class2\":number_to_class[index[8]], \"class3\":number_to_class[index[7]], \"prob1\":probabilities[index[9]], \"prob2\":probabilities[index[8]], \"prob3\":probabilities[index[7]], }#Step 5 return render_template('predict.html', predictions=predictions)"
},
{
"code": null,
"e": 16539,
"s": 16451,
"text": "All this should be pretty familiar, if you need a refresher, please visit the tutorial:"
},
{
"code": null,
"e": 16550,
"s": 16539,
"text": "medium.com"
},
{
"code": null,
"e": 16681,
"s": 16550,
"text": "Lastly, we run the app with port 80, which is the standard port for accessing web pages. Type this at the end of your Python file:"
},
{
"code": null,
"e": 16714,
"s": 16681,
"text": "app.run(host='0.0.0.0', port=80)"
},
{
"code": null,
"e": 16992,
"s": 16714,
"text": "Now we have the backbones of our Web application. You might have noticed that we are still missing a few different pieces though. In particular, we’ve called on the HTML web pages like index.html and predict.html but we’ve not built them yet! We will do so in the next section."
},
{
"code": null,
"e": 17168,
"s": 16992,
"text": "Do also note that in this bare-bones tutorial, we’ve skipped many good practices. You may want to try incorporating some of these practices if you know how to (or Google it!):"
},
{
"code": null,
"e": 17263,
"s": 17168,
"text": "Creating our Web app in an Anaconda environment (like we did in Anaconda Navigator previously)"
},
{
"code": null,
"e": 17344,
"s": 17263,
"text": "Catching errors such as someone not uploading any file, or with a blank filename"
},
{
"code": null,
"e": 17408,
"s": 17344,
"text": "Checking link extensions that people are uploading ‘.jpg’ files"
},
{
"code": null,
"e": 17593,
"s": 17408,
"text": "When a user interacts with your web application, they do so via the web pages, which is what we will be building in this section. Go into the templates folder by typing in the console:"
},
{
"code": null,
"e": 17606,
"s": 17593,
"text": "cd templates"
},
{
"code": null,
"e": 17737,
"s": 17606,
"text": "Create the two template files we need, index.html and predict.html. If you type ls you should see those two files under templates:"
},
{
"code": null,
"e": 18114,
"s": 17737,
"text": "We use a language called HyperText Markup Language (HTML), which just tells the browser how to render the content that you have. To generalise it a little bit, we tag the content with tags like “header” or “paragraph” and then we tell the browser how to display content with those type of tags. For example, if I want to tag the words “Hello” as a “header 1” type, I’ll write:"
},
{
"code": null,
"e": 18129,
"s": 18114,
"text": "<h1>Hello</h1>"
},
{
"code": null,
"e": 18385,
"s": 18129,
"text": "Usually, when you start the tag (i.e. <h1>), you have to close the tag as well to show where it ends (i.e. </h1>). We’ll learn as we go, so let’s start with index.html. To remind you how the page will look like, we are trying to build something like this:"
},
{
"code": null,
"e": 18440,
"s": 18385,
"text": "The first thing we start index.html with is this line:"
},
{
"code": null,
"e": 18456,
"s": 18440,
"text": "<!doctype html>"
},
{
"code": null,
"e": 18982,
"s": 18456,
"text": "This tells the browser what kind of document type to expect (i.e. HTML). We then begin the document with a<html> tag, which we will close it at the very end. Now, we also define the head of the document, which contains the “meta-data” of the document. Here, I’ve defined the title and I’ve linked a Bootstrap stylesheet, where other people have already defined styles for the various tags. I can therefore leave large amounts of the styling to what others have coded for us, unless there are some aspects I need to customise."
},
{
"code": null,
"e": 19253,
"s": 18982,
"text": "<html><head> <title>Classify your Image!</title> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\"></head>"
},
{
"code": null,
"e": 19278,
"s": 19253,
"text": "Now, we define the body:"
},
{
"code": null,
"e": 19801,
"s": 19278,
"text": "<body style=\"background-color:black\"><div id=\"maintext\" style=\"position:absolute; margin:auto; width:700px; height:200px; text-align:center; top:0; bottom: 0; left: 0; right: 0;\"> <h1 class=\"text-light mb-2\"> Upload your image to be classified! </h1> <h4 class=\"text-light mb-5\">(Please upload images less than 500kb in size)</h4> <form method=post enctype=multipart/form-data> <p class=\"text-light\"> <input type=file name=file> <input type=submit value=Upload> </p> </form></div></body></html>"
},
{
"code": null,
"e": 20132,
"s": 19801,
"text": "First, I tell HTML that I want a background color of black. Then, I have a div container so that I can contain the following content together. I want the container to be in the middle of the page with a certain height and width and margins, so I define that in the style. Within my div container, I have three main content pieces:"
},
{
"code": null,
"e": 20500,
"s": 20132,
"text": "Large header (h1) that says “Upload your image to be classified!” (Note: mb-2 in the style just says add a margin of “medium size” at the bottom)Small header (h4) that says “(Please upload images less than 500kb in size)”A “form” that allows me to upload a file and then submit that form. We use the POST method to submit the form (recall how we defined the backend?)"
},
{
"code": null,
"e": 20646,
"s": 20500,
"text": "Large header (h1) that says “Upload your image to be classified!” (Note: mb-2 in the style just says add a margin of “medium size” at the bottom)"
},
{
"code": null,
"e": 20723,
"s": 20646,
"text": "Small header (h4) that says “(Please upload images less than 500kb in size)”"
},
{
"code": null,
"e": 20870,
"s": 20723,
"text": "A “form” that allows me to upload a file and then submit that form. We use the POST method to submit the form (recall how we defined the backend?)"
},
{
"code": null,
"e": 21190,
"s": 20870,
"text": "Once I’ve defined these three content pieces within my div container, I close the body and html tags and I’m done! Do note that it is good practice to re-organizing your code into CSS files and HTML files so that we can separate the style from the content — for the purpose of this tutorial, we’ve taken some shortcuts!"
},
{
"code": null,
"e": 21280,
"s": 21190,
"text": "Now, we move on to the predict.html page. Remember how the page is supposed to look like:"
},
{
"code": null,
"e": 21398,
"s": 21280,
"text": "For the HTML code, the head is still the same as index.html, but there are a few new elements introduced in the body:"
},
{
"code": null,
"e": 22992,
"s": 21398,
"text": "<!doctype html><html><head> <title>Your Prediction!</title> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\"></head><body style=\"background-color:black\"><div id=\"maintext\" style=\"position:absolute; margin:auto; width:700px; height:300px; text-align:center; top:0; bottom: 0; left: 0; right: 0;\"> <h1 class=\"text-light mb-5\"> Your Prediction </h1> <p class=\"text-light\"> My algorithm gave this prediction: </p> <table class=\"table-bordered text-light\" style=\"width:100%\"> <tr> <th>Rank</th> <th>Class</th> <th>Probability</th> </tr> <tr> <td>Most Likely:</td> <td>{{ predictions.class1 }}</td> <td>{{ predictions.prob1 }}</td> </tr> <tr> <td>2nd Most Likely:</td> <td>{{ predictions.class2 }}</td> <td>{{ predictions.prob2 }}</td> </tr> <tr> <td>3rd Most Likely:</td> <td>{{ predictions.class3 }}</td> <td>{{ predictions.prob3 }}</td> </tr> </table><a href=\"{{ url_for('main_page') }}\"><button class=\"button mt-3\">Try again?</button></a></div></body></html>"
},
{
"code": null,
"e": 23084,
"s": 22992,
"text": "In my div container (which is the same as in index.html), I now have the following content:"
},
{
"code": null,
"e": 24270,
"s": 23084,
"text": "A header (h1) that says “Your Prediction”A paragraph (p) that says “My algorithm gave this prediction:”A table with three columns and four rows. Each row in the table is tagged with <tr> . For each row, the headers are tagged with <th> and the text for each column is tagged with<td>. Note that the content for my predictions are not fixed — it depends on what my model gives me, which depends on what the user uploaded. This is where I need to interact with the backend. If you recall, in my prediction backend, the last line of the function is return render_template(‘predict.html’, predictions=predictions). This means that when I rendered the “predict.html”, I pass to my frontend the variables of predictions, and these variables will appear in my frontend wherever I call them using the double curly braces {{ ... }}. Therefore, {{ predictions.class1 }} will be automatically filled in with whatever the model predicted as the most probable class.A button to link me back to the main page. I use {{ url_for(‘main_page’) }} because main_page is the name of the function in my backend that defined the main page. Therefore, whatever the URL is will be filled in automatically here."
},
{
"code": null,
"e": 24312,
"s": 24270,
"text": "A header (h1) that says “Your Prediction”"
},
{
"code": null,
"e": 24375,
"s": 24312,
"text": "A paragraph (p) that says “My algorithm gave this prediction:”"
},
{
"code": null,
"e": 25226,
"s": 24375,
"text": "A table with three columns and four rows. Each row in the table is tagged with <tr> . For each row, the headers are tagged with <th> and the text for each column is tagged with<td>. Note that the content for my predictions are not fixed — it depends on what my model gives me, which depends on what the user uploaded. This is where I need to interact with the backend. If you recall, in my prediction backend, the last line of the function is return render_template(‘predict.html’, predictions=predictions). This means that when I rendered the “predict.html”, I pass to my frontend the variables of predictions, and these variables will appear in my frontend wherever I call them using the double curly braces {{ ... }}. Therefore, {{ predictions.class1 }} will be automatically filled in with whatever the model predicted as the most probable class."
},
{
"code": null,
"e": 25459,
"s": 25226,
"text": "A button to link me back to the main page. I use {{ url_for(‘main_page’) }} because main_page is the name of the function in my backend that defined the main page. Therefore, whatever the URL is will be filled in automatically here."
},
{
"code": null,
"e": 25765,
"s": 25459,
"text": "And there we have it! Again, it is good practice to re-organizing your code into CSS files and HTML files so that we can separate the style from the content. This way, if we want to consistently change the style of the div for example, we don’t need to go to both index.html and predict.html to change it."
},
{
"code": null,
"e": 25863,
"s": 25765,
"text": "Now, all there is left to do is to run the Web application. Go back to the console and type this:"
},
{
"code": null,
"e": 25888,
"s": 25863,
"text": "python3 imgrec_webapp.py"
},
{
"code": null,
"e": 26025,
"s": 25888,
"text": "You’ll see a whole bunch of warning messages, but you can ignore them. The most important thing is that at the end, you see this screen:"
},
{
"code": null,
"e": 26105,
"s": 26025,
"text": "Now, you can enter your droplet’s IP address into your browser and click Enter."
},
{
"code": null,
"e": 26327,
"s": 26105,
"text": "You should see your application up and running, and you should be able to upload a small image and get a prediction! Do note that the first image will always take a lot longer, so be patient! It will be faster after that!"
},
{
"code": null,
"e": 26434,
"s": 26327,
"text": "Consolidated Summary: In this post, we’ve written a web application around our image recognition model by:"
},
{
"code": null,
"e": 26473,
"s": 26434,
"text": "Setting up on the cloud (DigitalOcean)"
},
{
"code": null,
"e": 26514,
"s": 26473,
"text": "Creating the Web App Backend using Flask"
},
{
"code": null,
"e": 26555,
"s": 26514,
"text": "Creating the Web App Frontend using HTML"
},
{
"code": null,
"e": 26906,
"s": 26555,
"text": "Congratulations! You’ve built your very first web application. We are still quite far away from building a production-level web application, and we have not incorporated many necessary practices if we are to scale this up. But at least we have some semblance of a Web application running, and we can incorporate these practices to our base framework."
},
{
"code": null,
"e": 27137,
"s": 26906,
"text": "What’s Next: In our next Coding Companion Part 3 (link to be released), we will explore how to code up our own Recurrent Neural Networks (RNNs) to deal with natural language! Be sure to get an intuitive understanding of RNNs here:"
},
{
"code": null,
"e": 27206,
"s": 27137,
"text": "Intuitive Deep Learning Part 3: RNNs for Natural Language Processing"
}
] |
C library function - time()
|
The C library function time_t time(time_t *seconds) returns the time since the Epoch (00:00:00 UTC, January 1, 1970), measured in seconds. If seconds is not NULL, the return value is also stored in variable seconds.
Following is the declaration for time() function.
time_t time(time_t *t)
seconds − This is the pointer to an object of type time_t, where the seconds value will be stored.
seconds − This is the pointer to an object of type time_t, where the seconds value will be stored.
The current calendar time as a time_t object.
The following example shows the usage of time() function.
#include <stdio.h>
#include <time.h>
int main () {
time_t seconds;
seconds = time(NULL);
printf("Hours since January 1, 1970 = %ld\n", seconds/3600);
return(0);
}
Let us compile and run the above program that will produce the following result −
Hours since January 1, 1970 = 393923
12 Lectures
2 hours
Nishant Malik
12 Lectures
2.5 hours
Nishant Malik
48 Lectures
6.5 hours
Asif Hussain
12 Lectures
2 hours
Richa Maheshwari
20 Lectures
3.5 hours
Vandana Annavaram
44 Lectures
1 hours
Amit Diwan
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2223,
"s": 2007,
"text": "The C library function time_t time(time_t *seconds) returns the time since the Epoch (00:00:00 UTC, January 1, 1970), measured in seconds. If seconds is not NULL, the return value is also stored in variable seconds."
},
{
"code": null,
"e": 2273,
"s": 2223,
"text": "Following is the declaration for time() function."
},
{
"code": null,
"e": 2296,
"s": 2273,
"text": "time_t time(time_t *t)"
},
{
"code": null,
"e": 2395,
"s": 2296,
"text": "seconds − This is the pointer to an object of type time_t, where the seconds value will be stored."
},
{
"code": null,
"e": 2494,
"s": 2395,
"text": "seconds − This is the pointer to an object of type time_t, where the seconds value will be stored."
},
{
"code": null,
"e": 2540,
"s": 2494,
"text": "The current calendar time as a time_t object."
},
{
"code": null,
"e": 2598,
"s": 2540,
"text": "The following example shows the usage of time() function."
},
{
"code": null,
"e": 2778,
"s": 2598,
"text": "#include <stdio.h>\n#include <time.h>\n\nint main () {\n time_t seconds;\n\n seconds = time(NULL);\n printf(\"Hours since January 1, 1970 = %ld\\n\", seconds/3600);\n \n return(0);\n}"
},
{
"code": null,
"e": 2860,
"s": 2778,
"text": "Let us compile and run the above program that will produce the following result −"
},
{
"code": null,
"e": 2898,
"s": 2860,
"text": "Hours since January 1, 1970 = 393923\n"
},
{
"code": null,
"e": 2931,
"s": 2898,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2946,
"s": 2931,
"text": " Nishant Malik"
},
{
"code": null,
"e": 2981,
"s": 2946,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2996,
"s": 2981,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3031,
"s": 2996,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3045,
"s": 3031,
"text": " Asif Hussain"
},
{
"code": null,
"e": 3078,
"s": 3045,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3096,
"s": 3078,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 3131,
"s": 3096,
"text": "\n 20 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3150,
"s": 3131,
"text": " Vandana Annavaram"
},
{
"code": null,
"e": 3183,
"s": 3150,
"text": "\n 44 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3195,
"s": 3183,
"text": " Amit Diwan"
},
{
"code": null,
"e": 3202,
"s": 3195,
"text": " Print"
},
{
"code": null,
"e": 3213,
"s": 3202,
"text": " Add Notes"
}
] |
Convert array into Zig-Zag fashion - GeeksforGeeks
|
05 May, 2022
Given an array of DISTINCT elements, rearrange the elements of array in zig-zag fashion in O(n) time. The converted array should be in form a < b > c < d > e < f.
Example:
Input: arr[] = {4, 3, 7, 8, 6, 2, 1} Output: arr[] = {3, 7, 4, 8, 2, 6, 1}
Input: arr[] = {1, 4, 3, 2} Output: arr[] = {1, 4, 2, 3}
A Simple Solution is to first sort the array. After sorting, exclude the first element, swap the remaining elements in pairs. (i.e. keep arr[0] as it is, swap arr[1] and arr[2], swap arr[3] and arr[4], and so on). Time complexity: O(N log N) since we need to sort the array first.
We can convert in O(n) time using an efficient approach. The idea is to use a modified one pass of bubble sort.
Maintain a flag for representing which order(i.e. < or >) currently we need.
If the current two elements are not in that order then swap those elements otherwise not.
Let us see the main logic using three consecutive elements A, B, C.
Suppose we are processing B and C currently and the current relation is ‘<‘, but we have B > C. Since current relation is ‘<‘ previous relation must be ‘>’ i.e., A must be greater than B. So, the relation is A > B and B > C. We can deduce A > C. So if we swap B and C then the relation is A > C and C < B. Finally we get the desired order A C B Refer this for more explanation.
Below image is a dry run of the above approach:
Below is the implementation of above approach:
C++
Java
Python
C#
Javascript
// C++ program to sort an array in Zig-Zag form#include <iostream>using namespace std; // Program for zig-zag conversion of arrayvoid zigZag(int arr[], int n){ // Flag true indicates relation "<" is expected, // else ">" is expected. The first expected relation // is "<" bool flag = true; for (int i=0; i<=n-2; i++) { if (flag) /* "<" relation expected */ { /* If we have a situation like A > B > C, we get A > C < B by swapping B and C */ if (arr[i] > arr[i+1]) swap(arr[i], arr[i+1]); } else /* ">" relation expected */ { /* If we have a situation like A < B < C, we get A < C > B by swapping B and C */ if (arr[i] < arr[i+1]) swap(arr[i], arr[i+1]); } flag = !flag; /* flip flag */ }} // Driver programint main(){ int arr[] = {4, 3, 7, 8, 6, 2, 1}; int n = sizeof(arr)/sizeof(arr[0]); zigZag(arr, n); for (int i=0; i<n; i++) cout << arr[i] << " "; return 0;}
// Java program to sort an array in Zig-Zag formimport java.util.Arrays; class Test{ static int arr[] = new int[]{4, 3, 7, 8, 6, 2, 1}; // Method for zig-zag conversion of array static void zigZag() { // Flag true indicates relation "<" is expected, // else ">" is expected. The first expected relation // is "<" boolean flag = true; int temp =0; for (int i=0; i<=arr.length-2; i++) { if (flag) /* "<" relation expected */ { /* If we have a situation like A > B > C, we get A > C < B by swapping B and C */ if (arr[i] > arr[i+1]) { // swap temp = arr[i]; arr[i] = arr[i+1]; arr[i+1] = temp; } } else /* ">" relation expected */ { /* If we have a situation like A < B < C, we get A < C > B by swapping B and C */ if (arr[i] < arr[i+1]) { // swap temp = arr[i]; arr[i] = arr[i+1]; arr[i+1] = temp; } } flag = !flag; /* flip flag */ } } // Driver method to test the above function public static void main(String[] args) { zigZag(); System.out.println(Arrays.toString(arr)); }}
# Python program to sort an array in Zig-Zag form # Program for zig-zag conversion of arraydef zigZag(arr, n): # Flag true indicates relation "<" is expected, # else ">" is expected. The first expected relation # is "<" flag = True for i in range(n-1): # "<" relation expected if flag is True: # If we have a situation like A > B > C, # we get A > C < B # by swapping B and C if arr[i] > arr[i+1]: arr[i],arr[i+1] = arr[i+1],arr[i] # ">" relation expected else: # If we have a situation like A < B < C, # we get A < C > B # by swapping B and C if arr[i] < arr[i+1]: arr[i],arr[i+1] = arr[i+1],arr[i] flag = bool(1 - flag) print(arr) # Driver programarr = [4, 3, 7, 8, 6, 2, 1]n = len(arr)zigZag(arr, n) # This code is contributed by Pratik Chhajer# This code was improved by Hardik Jain
// C# program to sort an array in Zig-Zag formusing System; class GFG{ static int []arr = new int[]{ 4, 3, 7, 8, 6, 2, 1 }; // Method for zig-zag conversion of arraystatic void zigZag(){ // Flag true indicates relation "<" // is expected, else ">" is expected. // The first expected relation // is "<" bool flag = true; int temp = 0; for(int i = 0; i <= arr.Length - 2; i++) { // "<" relation expected if (flag) { // If we have a situation like A > B > C, // we get A > C < B by swapping B and C if (arr[i] > arr[i+1]) { // Swap temp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = temp; } } // ">" relation expected else { // If we have a situation like A < B < C, // we get A < C > B by swapping B and C if (arr[i] < arr[i + 1]) { // Swap temp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = temp; } } // Flip flag flag = !flag; }} // Driver codepublic static void Main(String[] args){ zigZag(); foreach(int i in arr) Console.Write(i + " ");}} // This code is contributed by amal kumar choubey
<script> // JavaScript program to sort an array// in Zig-Zag form // Program for zig-zag conversion of arrayfunction zigZag(arr, n){ // Flag true indicates relation "<" // is expected, else ">" is expected. // The first expected relation is "<" let flag = true; for(let i = 0; i <= n - 2; i++) { // "<" relation expected if (flag) { // If we have a situation like A > B > C, // we get A > C < B by swapping B and C if (arr[i] > arr[i + 1]) temp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = temp; } // ">" relation expected else { // If we have a situation like A < B < C, // we get A < C > B by swapping B and C if (arr[i] < arr[i + 1]) temp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = temp; } // Flip flag flag = !flag; }} // Driver codelet arr = [ 4, 3, 7, 8, 6, 2, 1 ];let n = arr.length;zigZag(arr, n); for(let i = 0; i < n; i++) document.write(arr[i] + " "); // This code is contributed by Surbhi Tyagi. </script>
3 7 4 8 2 6 1
Time complexity: O(n) Auxiliary Space: O(1)
Another approach:Since the relation needed is a<b>c<d>e<f, it means the odd position elements have to be greater than its adjacent i.e. the even position elements. Simply traverse the array at the odd positions and check if it is greater than its adjacent elements, if it is not then swap them.
Follow the steps below to implement the above idea:
Java
/*package whatever //do not write package name here */ import java.io.*;import java.util.*;class GFG { // Method for zig-zag conversion of array static void swap(int a[], int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } static void zigZag(int a[], int n) { for (int i = 1; i < n; i += 2) { // Check if previous element // is greater then the current element // then swap them if (a[i - 1] > a[i]) swap(a, i, i - 1); // if next element is greater then // then the current element then // also swap them. if (i + 1 < n && (a[i + 1] > a[i])) swap(a, i, i + 1); } } // Driver Code public static void main(String[] args) { int a[] = new int[] { 4, 3, 7, 8, 6, 2, 1 }; zigZag(a, a.length); System.out.println(Arrays.toString(a)); }}
[3, 7, 4, 8, 2, 6, 1]
Time complexity: O(n) Auxiliary Space: O(1)
YouTubeGeeksforGeeks507K subscribersConvert array into Zig-Zag fashion | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 8:53•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=fYR0X_MP4Ks" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Siva Krishna Aleti. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Amal Kumar Choubey
surbhityagi15
hdkjain
patelkhananandini
Amazon
Paytm
Arrays
Paytm
Amazon
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Linked List vs Array
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Python | Using 2D arrays/lists the right way
Array of Strings in C++ (5 Different Ways to Create)
|
[
{
"code": null,
"e": 26755,
"s": 26727,
"text": "\n05 May, 2022"
},
{
"code": null,
"e": 26919,
"s": 26755,
"text": "Given an array of DISTINCT elements, rearrange the elements of array in zig-zag fashion in O(n) time. The converted array should be in form a < b > c < d > e < f. "
},
{
"code": null,
"e": 26928,
"s": 26919,
"text": "Example:"
},
{
"code": null,
"e": 27003,
"s": 26928,
"text": "Input: arr[] = {4, 3, 7, 8, 6, 2, 1} Output: arr[] = {3, 7, 4, 8, 2, 6, 1}"
},
{
"code": null,
"e": 27060,
"s": 27003,
"text": "Input: arr[] = {1, 4, 3, 2} Output: arr[] = {1, 4, 2, 3}"
},
{
"code": null,
"e": 27341,
"s": 27060,
"text": "A Simple Solution is to first sort the array. After sorting, exclude the first element, swap the remaining elements in pairs. (i.e. keep arr[0] as it is, swap arr[1] and arr[2], swap arr[3] and arr[4], and so on). Time complexity: O(N log N) since we need to sort the array first."
},
{
"code": null,
"e": 27453,
"s": 27341,
"text": "We can convert in O(n) time using an efficient approach. The idea is to use a modified one pass of bubble sort."
},
{
"code": null,
"e": 27530,
"s": 27453,
"text": "Maintain a flag for representing which order(i.e. < or >) currently we need."
},
{
"code": null,
"e": 27620,
"s": 27530,
"text": "If the current two elements are not in that order then swap those elements otherwise not."
},
{
"code": null,
"e": 27688,
"s": 27620,
"text": "Let us see the main logic using three consecutive elements A, B, C."
},
{
"code": null,
"e": 28066,
"s": 27688,
"text": "Suppose we are processing B and C currently and the current relation is ‘<‘, but we have B > C. Since current relation is ‘<‘ previous relation must be ‘>’ i.e., A must be greater than B. So, the relation is A > B and B > C. We can deduce A > C. So if we swap B and C then the relation is A > C and C < B. Finally we get the desired order A C B Refer this for more explanation."
},
{
"code": null,
"e": 28114,
"s": 28066,
"text": "Below image is a dry run of the above approach:"
},
{
"code": null,
"e": 28161,
"s": 28114,
"text": "Below is the implementation of above approach:"
},
{
"code": null,
"e": 28165,
"s": 28161,
"text": "C++"
},
{
"code": null,
"e": 28170,
"s": 28165,
"text": "Java"
},
{
"code": null,
"e": 28177,
"s": 28170,
"text": "Python"
},
{
"code": null,
"e": 28180,
"s": 28177,
"text": "C#"
},
{
"code": null,
"e": 28191,
"s": 28180,
"text": "Javascript"
},
{
"code": "// C++ program to sort an array in Zig-Zag form#include <iostream>using namespace std; // Program for zig-zag conversion of arrayvoid zigZag(int arr[], int n){ // Flag true indicates relation \"<\" is expected, // else \">\" is expected. The first expected relation // is \"<\" bool flag = true; for (int i=0; i<=n-2; i++) { if (flag) /* \"<\" relation expected */ { /* If we have a situation like A > B > C, we get A > C < B by swapping B and C */ if (arr[i] > arr[i+1]) swap(arr[i], arr[i+1]); } else /* \">\" relation expected */ { /* If we have a situation like A < B < C, we get A < C > B by swapping B and C */ if (arr[i] < arr[i+1]) swap(arr[i], arr[i+1]); } flag = !flag; /* flip flag */ }} // Driver programint main(){ int arr[] = {4, 3, 7, 8, 6, 2, 1}; int n = sizeof(arr)/sizeof(arr[0]); zigZag(arr, n); for (int i=0; i<n; i++) cout << arr[i] << \" \"; return 0;}",
"e": 29243,
"s": 28191,
"text": null
},
{
"code": "// Java program to sort an array in Zig-Zag formimport java.util.Arrays; class Test{ static int arr[] = new int[]{4, 3, 7, 8, 6, 2, 1}; // Method for zig-zag conversion of array static void zigZag() { // Flag true indicates relation \"<\" is expected, // else \">\" is expected. The first expected relation // is \"<\" boolean flag = true; int temp =0; for (int i=0; i<=arr.length-2; i++) { if (flag) /* \"<\" relation expected */ { /* If we have a situation like A > B > C, we get A > C < B by swapping B and C */ if (arr[i] > arr[i+1]) { // swap temp = arr[i]; arr[i] = arr[i+1]; arr[i+1] = temp; } } else /* \">\" relation expected */ { /* If we have a situation like A < B < C, we get A < C > B by swapping B and C */ if (arr[i] < arr[i+1]) { // swap temp = arr[i]; arr[i] = arr[i+1]; arr[i+1] = temp; } } flag = !flag; /* flip flag */ } } // Driver method to test the above function public static void main(String[] args) { zigZag(); System.out.println(Arrays.toString(arr)); }}",
"e": 30734,
"s": 29243,
"text": null
},
{
"code": "# Python program to sort an array in Zig-Zag form # Program for zig-zag conversion of arraydef zigZag(arr, n): # Flag true indicates relation \"<\" is expected, # else \">\" is expected. The first expected relation # is \"<\" flag = True for i in range(n-1): # \"<\" relation expected if flag is True: # If we have a situation like A > B > C, # we get A > C < B # by swapping B and C if arr[i] > arr[i+1]: arr[i],arr[i+1] = arr[i+1],arr[i] # \">\" relation expected else: # If we have a situation like A < B < C, # we get A < C > B # by swapping B and C if arr[i] < arr[i+1]: arr[i],arr[i+1] = arr[i+1],arr[i] flag = bool(1 - flag) print(arr) # Driver programarr = [4, 3, 7, 8, 6, 2, 1]n = len(arr)zigZag(arr, n) # This code is contributed by Pratik Chhajer# This code was improved by Hardik Jain",
"e": 31700,
"s": 30734,
"text": null
},
{
"code": "// C# program to sort an array in Zig-Zag formusing System; class GFG{ static int []arr = new int[]{ 4, 3, 7, 8, 6, 2, 1 }; // Method for zig-zag conversion of arraystatic void zigZag(){ // Flag true indicates relation \"<\" // is expected, else \">\" is expected. // The first expected relation // is \"<\" bool flag = true; int temp = 0; for(int i = 0; i <= arr.Length - 2; i++) { // \"<\" relation expected if (flag) { // If we have a situation like A > B > C, // we get A > C < B by swapping B and C if (arr[i] > arr[i+1]) { // Swap temp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = temp; } } // \">\" relation expected else { // If we have a situation like A < B < C, // we get A < C > B by swapping B and C if (arr[i] < arr[i + 1]) { // Swap temp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = temp; } } // Flip flag flag = !flag; }} // Driver codepublic static void Main(String[] args){ zigZag(); foreach(int i in arr) Console.Write(i + \" \");}} // This code is contributed by amal kumar choubey",
"e": 33130,
"s": 31700,
"text": null
},
{
"code": "<script> // JavaScript program to sort an array// in Zig-Zag form // Program for zig-zag conversion of arrayfunction zigZag(arr, n){ // Flag true indicates relation \"<\" // is expected, else \">\" is expected. // The first expected relation is \"<\" let flag = true; for(let i = 0; i <= n - 2; i++) { // \"<\" relation expected if (flag) { // If we have a situation like A > B > C, // we get A > C < B by swapping B and C if (arr[i] > arr[i + 1]) temp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = temp; } // \">\" relation expected else { // If we have a situation like A < B < C, // we get A < C > B by swapping B and C if (arr[i] < arr[i + 1]) temp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = temp; } // Flip flag flag = !flag; }} // Driver codelet arr = [ 4, 3, 7, 8, 6, 2, 1 ];let n = arr.length;zigZag(arr, n); for(let i = 0; i < n; i++) document.write(arr[i] + \" \"); // This code is contributed by Surbhi Tyagi. </script>",
"e": 34360,
"s": 33130,
"text": null
},
{
"code": null,
"e": 34375,
"s": 34360,
"text": "3 7 4 8 2 6 1 "
},
{
"code": null,
"e": 34420,
"s": 34375,
"text": "Time complexity: O(n) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 34715,
"s": 34420,
"text": "Another approach:Since the relation needed is a<b>c<d>e<f, it means the odd position elements have to be greater than its adjacent i.e. the even position elements. Simply traverse the array at the odd positions and check if it is greater than its adjacent elements, if it is not then swap them."
},
{
"code": null,
"e": 34767,
"s": 34715,
"text": "Follow the steps below to implement the above idea:"
},
{
"code": null,
"e": 34772,
"s": 34767,
"text": "Java"
},
{
"code": "/*package whatever //do not write package name here */ import java.io.*;import java.util.*;class GFG { // Method for zig-zag conversion of array static void swap(int a[], int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } static void zigZag(int a[], int n) { for (int i = 1; i < n; i += 2) { // Check if previous element // is greater then the current element // then swap them if (a[i - 1] > a[i]) swap(a, i, i - 1); // if next element is greater then // then the current element then // also swap them. if (i + 1 < n && (a[i + 1] > a[i])) swap(a, i, i + 1); } } // Driver Code public static void main(String[] args) { int a[] = new int[] { 4, 3, 7, 8, 6, 2, 1 }; zigZag(a, a.length); System.out.println(Arrays.toString(a)); }}",
"e": 35730,
"s": 34772,
"text": null
},
{
"code": null,
"e": 35753,
"s": 35730,
"text": "[3, 7, 4, 8, 2, 6, 1]\n"
},
{
"code": null,
"e": 35799,
"s": 35753,
"text": "Time complexity: O(n) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 36632,
"s": 35799,
"text": "YouTubeGeeksforGeeks507K subscribersConvert array into Zig-Zag fashion | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 8:53•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=fYR0X_MP4Ks\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 36808,
"s": 36632,
"text": "This article is contributed by Siva Krishna Aleti. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 36827,
"s": 36808,
"text": "Amal Kumar Choubey"
},
{
"code": null,
"e": 36841,
"s": 36827,
"text": "surbhityagi15"
},
{
"code": null,
"e": 36849,
"s": 36841,
"text": "hdkjain"
},
{
"code": null,
"e": 36867,
"s": 36849,
"text": "patelkhananandini"
},
{
"code": null,
"e": 36874,
"s": 36867,
"text": "Amazon"
},
{
"code": null,
"e": 36880,
"s": 36874,
"text": "Paytm"
},
{
"code": null,
"e": 36887,
"s": 36880,
"text": "Arrays"
},
{
"code": null,
"e": 36893,
"s": 36887,
"text": "Paytm"
},
{
"code": null,
"e": 36900,
"s": 36893,
"text": "Amazon"
},
{
"code": null,
"e": 36907,
"s": 36900,
"text": "Arrays"
},
{
"code": null,
"e": 37005,
"s": 36907,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37073,
"s": 37005,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 37117,
"s": 37073,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 37165,
"s": 37117,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 37188,
"s": 37165,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 37220,
"s": 37188,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 37234,
"s": 37220,
"text": "Linear Search"
},
{
"code": null,
"e": 37255,
"s": 37234,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 37340,
"s": 37255,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 37385,
"s": 37340,
"text": "Python | Using 2D arrays/lists the right way"
}
] |
Prim’s (Minimum Spanning Tree) MST Algorithm
|
There is a connected graph G(V,E) and the weight or cost for every edge is given. Prim’s Algorithm will find the minimum spanning tree from the graph G.
It is growing tree approach. This algorithm needs a seed value to start the tree. The seed vertex is grown to form the whole tree.
The problem will be solved using two sets. One set holds the nodes that are already selected, and another set holds the item that are not considered yet. From the seed vertex, it takes adjacent vertices, based on minimum edge cost, thus it grows the tree by taking nodes one by one.
Time complexity of this problem is O(V2). Here V is the number of vertices.
Time complexity of this problem is O(V2). Here V is the number of vertices.
Input − The adjacency list −
Output −
(0)---(1|1) (0)---(2|3) (0)---(3|4)
(1)---(0|1) (1)---(4|2)
(2)---(0|3)
(3)---(0|4)
(4)---(1|2) (4)---(5|2)
(5)---(4|2) (5)---(6|3)
(6)---(5|3)
Input − The graph g, A blank tree and the seed vertex named ‘start’ Output: The Tree after adding edges.
Begin
define two sets as usedVert, unusedVert
usedVert[0] := start and unusedVert[0] := φ
for all vertices except start do
usedVert[i] := φ
unusedVert[i] := i //add all vertices in unused list
done
while number of vertices in usedVert ≠ V do //V is number of total nodes
min := ∞
for all vertices of usedVert array do
for all vertices of the graph do
if min > cost[i,j] AND i ≠ j then
min := cost[i,j]
ed := edge between i and j, and cost of ed := min
done
done
unusedVert[destination of ed] := φ
add edge ed into the tree t
add source of ed into usedVert
done
End
#include<iostream>
#define V 7
#define INF 999
using namespace std;
//Cost matrix of the graph
int costMat[V][V] = {
{0, 1, 3, 4, INF, 5, INF},
{1, 0, INF, 7, 2, INF, INF},
{3, INF, 0, INF, 8, INF, INF},
{4, 7, INF, 0, INF, INF, INF},
{INF, 2, 8, INF, 0, 2, 4},
{5, INF, INF, INF, 2, 0, 3},
{INF, INF, INF, INF, 4, 3, 0}
};
typedef struct{
int u, v, cost;
}edge;
class Tree{
int n;
edge edges[V-1]; //as a tree has vertex-1 edges
public:
Tree(){
n = 0;
}
void addEdge(edge e){
edges[n] = e; //add edge e into the tree
n++;
}
void printEdges(){ //print edge, cost and total cost
int tCost = 0;
for(int i = 0; i<n; i++){
cout << "Edge: " << char(edges[i].u+'A') < "--" << char(edges[i].v+'A');
cout << " And Cost: " << edges[i].cost << endl;
tCost += edges[i].cost;
}
cout << "Total Cost: " << tCost << endl;
}
friend void prims(Tree &tre, int start);
};
void prims(Tree &tr, int start){
int usedVert[V], unusedVert[V];
int i, j, min, p;
edge ed;
//initialize
usedVert[0] = start; p = 1;
unusedVert[0] = -1;//-1 indicates the place is empty
for(i = 1; i<V; i++){
usedVert[i] = -1;//all places except first is empty
unusedVert[i] = i;//fill with vertices
}
tr.n = 0;
//get edges and add to tree
while(p != V){ //p is number of vertices in usedVert array
min = INF;
for(i = 0; i<p; i++){
for(j = 0; j<V; j++){
if(unusedVert[j] != -1){
if(min > costMat[i][j] && costMat[i][j] != 0){
//find the edge with minimum cost
//such that u is considered and v is not considered yet
min = costMat[i][j];
ed.u = i; ed.v = j; ed.cost = min;
}
}
}
}
unusedVert[ed.v] = -1;//delete v from unusedVertex
tr.addEdge(ed);
usedVert[p] = ed.u; p++;//add u to usedVertex
}
}
main(){
Tree tr;
prims(tr, 0); //starting node 0
tr.printEdges();
}
(0)---(1|1) (0)---(2|3) (0)---(3|4)
(1)---(0|1) (1)---(4|2)
(2)---(0|3)
(3)---(0|4)
(4)---(1|2) (4)---(5|2)
(5)---(4|2) (5)---(6|3)
(6)---(5|3)
|
[
{
"code": null,
"e": 1215,
"s": 1062,
"text": "There is a connected graph G(V,E) and the weight or cost for every edge is given. Prim’s Algorithm will find the minimum spanning tree from the graph G."
},
{
"code": null,
"e": 1346,
"s": 1215,
"text": "It is growing tree approach. This algorithm needs a seed value to start the tree. The seed vertex is grown to form the whole tree."
},
{
"code": null,
"e": 1629,
"s": 1346,
"text": "The problem will be solved using two sets. One set holds the nodes that are already selected, and another set holds the item that are not considered yet. From the seed vertex, it takes adjacent vertices, based on minimum edge cost, thus it grows the tree by taking nodes one by one."
},
{
"code": null,
"e": 1705,
"s": 1629,
"text": "Time complexity of this problem is O(V2). Here V is the number of vertices."
},
{
"code": null,
"e": 1781,
"s": 1705,
"text": "Time complexity of this problem is O(V2). Here V is the number of vertices."
},
{
"code": null,
"e": 1810,
"s": 1781,
"text": "Input − The adjacency list −"
},
{
"code": null,
"e": 1819,
"s": 1810,
"text": "Output −"
},
{
"code": null,
"e": 1963,
"s": 1819,
"text": "(0)---(1|1) (0)---(2|3) (0)---(3|4)\n(1)---(0|1) (1)---(4|2)\n(2)---(0|3)\n(3)---(0|4)\n(4)---(1|2) (4)---(5|2)\n(5)---(4|2) (5)---(6|3)\n(6)---(5|3)"
},
{
"code": null,
"e": 2068,
"s": 1963,
"text": "Input − The graph g, A blank tree and the seed vertex named ‘start’ Output: The Tree after adding edges."
},
{
"code": null,
"e": 2776,
"s": 2068,
"text": "Begin\n define two sets as usedVert, unusedVert\n usedVert[0] := start and unusedVert[0] := φ\n for all vertices except start do\n usedVert[i] := φ\n unusedVert[i] := i //add all vertices in unused list\n done\n while number of vertices in usedVert ≠ V do //V is number of total nodes\n min := ∞\n for all vertices of usedVert array do\n for all vertices of the graph do\n if min > cost[i,j] AND i ≠ j then\n min := cost[i,j]\n ed := edge between i and j, and cost of ed := min\n done\n done\n unusedVert[destination of ed] := φ\n add edge ed into the tree t\n add source of ed into usedVert\n done\nEnd"
},
{
"code": null,
"e": 4853,
"s": 2776,
"text": "#include<iostream>\n#define V 7\n#define INF 999\nusing namespace std;\n//Cost matrix of the graph\nint costMat[V][V] = {\n {0, 1, 3, 4, INF, 5, INF},\n {1, 0, INF, 7, 2, INF, INF},\n {3, INF, 0, INF, 8, INF, INF},\n {4, 7, INF, 0, INF, INF, INF},\n {INF, 2, 8, INF, 0, 2, 4},\n {5, INF, INF, INF, 2, 0, 3},\n {INF, INF, INF, INF, 4, 3, 0}\n};\ntypedef struct{\n int u, v, cost;\n}edge;\nclass Tree{\n int n;\n edge edges[V-1]; //as a tree has vertex-1 edges\n public:\n Tree(){\n n = 0;\n }\n void addEdge(edge e){\n edges[n] = e; //add edge e into the tree\n n++;\n }\n void printEdges(){ //print edge, cost and total cost\n int tCost = 0;\n for(int i = 0; i<n; i++){\n cout << \"Edge: \" << char(edges[i].u+'A') < \"--\" << char(edges[i].v+'A');\n cout << \" And Cost: \" << edges[i].cost << endl;\n tCost += edges[i].cost;\n }\n cout << \"Total Cost: \" << tCost << endl;\n }\n friend void prims(Tree &tre, int start);\n};\nvoid prims(Tree &tr, int start){\n int usedVert[V], unusedVert[V];\n int i, j, min, p;\n edge ed;\n //initialize\n usedVert[0] = start; p = 1;\n unusedVert[0] = -1;//-1 indicates the place is empty\n for(i = 1; i<V; i++){\n usedVert[i] = -1;//all places except first is empty\n unusedVert[i] = i;//fill with vertices\n }\n tr.n = 0;\n //get edges and add to tree\n while(p != V){ //p is number of vertices in usedVert array\n min = INF;\n for(i = 0; i<p; i++){\n for(j = 0; j<V; j++){\n if(unusedVert[j] != -1){\n if(min > costMat[i][j] && costMat[i][j] != 0){\n //find the edge with minimum cost\n //such that u is considered and v is not considered yet\n min = costMat[i][j];\n ed.u = i; ed.v = j; ed.cost = min;\n }\n }\n }\n }\n unusedVert[ed.v] = -1;//delete v from unusedVertex\n tr.addEdge(ed);\n usedVert[p] = ed.u; p++;//add u to usedVertex\n }\n}\nmain(){\n Tree tr;\n prims(tr, 0); //starting node 0\n tr.printEdges();\n}"
},
{
"code": null,
"e": 4997,
"s": 4853,
"text": "(0)---(1|1) (0)---(2|3) (0)---(3|4)\n(1)---(0|1) (1)---(4|2)\n(2)---(0|3)\n(3)---(0|4)\n(4)---(1|2) (4)---(5|2)\n(5)---(4|2) (5)---(6|3)\n(6)---(5|3)"
}
] |
Teaching Cars To See — Vehicle Detection Using Machine Learning And Computer Vision | by Eddie Forson | Towards Data Science
|
This is the final project of Term 1 of the Udacity Self-Driving Car Engineer Nanodegree. You can find all code related to this project on github. You can also read my posts on previous projects:
project 1: Detecting Lane Lines Using Computer Vision
project 2: Traffic Sign Classification Using Deep Learning
project 3: Steering Angle Prediction Using Deep Learning
project 4: Advanced Lane Detection Using Computer Vision
When we drive, we constantly pay attention to our environment, as our safety and that of many other people are at stake. We particularly look out for position of potential obstacles, whether they be other cars, pedestrians, or objects on the road. Similarly, as we develop the intelligence and sensors necessary to power a autonomous vehicles, it is of the utmost importance that such vehicles can detect obstacles as well, as it reinforces the car’s understanding of its environment. One of the most important types of ostacles to detect is other vehicles on the road, as they would most likely be the biggest objects in our lane or neighbouring ones and therefore constitute a potential hazard.
A number of techniques for obstacle detection have been developed throughout the literature, from traditional computer vision techniques to deep learning ones, and more. In this exercise, we build a vehicle detector by employing a conventional computer vision technique called Histogram of Oriented Gradients (HOG), combined with a machine learning algorithm called Support Vector Machines (SVM).
Udacity generously provided a balanced dataset with the following characteristics:
~ 9K images of vehicles
~ 9K images of non-vehicles
all images are 64x64
The dataset comes from the GTI Vehicle Image Database, KITTI Vision Benchmark Suite, and examples extracted from the project video itself. The latter is much larger and was not used for this project. However, it would be a great addition in the future, especially as we plan to build a classifier using deep learning. You can see a sample of images from the dataset below:
We can clearly see both vehicle and non-vehicle images. Non-vehicle images tend to be other elements of the road such as the asphalt, road signs or pavement. The distinction is very clear. Most images also display the vehicle in the center, but in different orientations, which is good. Moreover, there is a good variety of car types and colors, as well as lighting conditions.
Using HOG for detection was popularised by Navneet Dalal and Bill Triggs after showing impressive results in their paper named Histogram of Oriented Gradients For Human Detection. The algorithm is well explained by Satya Mallick on this post, for those who want to acquire a stronger fundamental grasp of HOG.
We firstly explored different configurations for the following values in the HOG algorithm, on a RGB image:
number of orientations (denoted by o)
pixels per cell (denoted by px/c)
The cells per block were originally fixed at 2 (denoted by c/bk). The images below show the results obtained on the sample vehicle image in RGB format:
From pure observation, it looks like a HOG configuration with:
11 orientations
14 pixels per cell
2 cells per blocks
produces the most distinctive gradients of a vehicle. We have not experimented with different cells per block so let us try now.
To the human eye, there is no significant difference that we notice visually. We would ideally like to reduce the feature space for faster computation. We will settle for now on 3 cells per block.
We must now explore the most suitable color space for our configuration, as it seems our HOG features across the 3 RGB channels are too similar, therefore it feels we are not generating features with enough variations.
We generate the following outputs across a multitude of color spaces:
For some color channels, it is difficult to interpret the result of HOG. Interestingly, it seems the first color channel in YUV, YCrCb, and LAB could be enough to capture the gradients we are looking for. In HSV and HLS it is respectively on the Value and Lightness channels that HOG captures the most significant features for the vehicle.
To confirm our hypothesis, let us try with a different image of a vehicle:
Houston, we’ve have a problem here... On a dark image such as the one above, we can observe that HOG on the channel that carries the most light information produces bad results. We must therefore take into account all color channels to capture the most features. In the end, our configuration looks as follows:
ALL channels of YCrCb color space
HOG orientations of 11
HOG pixels per cell of 14
HOG cells per block of 2
We will also be adding color information to strengthen our feature set. To do so we simply produce histograms across all color channels, using 32 bins, as shown below:
def color_histogram(img, nbins=32, bins_range=(0, 256)): """ Returns the histograms of the color image across all channels, as a concatenanted feature vector """ # Compute the histogram of the color channels separately channel1_hist = np.histogram(img[:,:,0], bins=nbins, range=bins_range) channel2_hist = np.histogram(img[:,:,1], bins=nbins, range=bins_range) channel3_hist = np.histogram(img[:,:,2], bins=nbins, range=bins_range) # Concatenate the histograms into a single feature vector and return it return np.concatenate((channel1_hist[0], channel2_hist[0], channel3_hist[0]))
The classifier is responsible for categorising the images we submit into either vehicle or non-vehicle classes. To do so, we must take the following steps:
Load our images from the dataset
Extract the features we desire
Normalise those features
Split the dataset for training and testing
Build a classifier with the appropriate parameters
Train the classifier on training data
As discussed in the previous section, we have decided to only retain one feature: the HOG feature vector computed on the Y channel of our YCrCb image.
We randomly split our dataset, leaving 20% of it for testing. Moreover, we scale the data by employing a sklearn.preprocessing.StandardScaler normaliser.
We did not have enough time to experiment with many classifiers so opted to use Support Vector Machines (SVMs) as they are commonly combined with HOG in the literature for object detection problems. Moreover, we used a SVC with kernel rbf as it provided the best accuracy, while being slower than a LinearSVC. We accepted the tradeoff as the detection of the SVC with rbf kernel was much stronger when we tested it on a series of images.
The ideal parameters among kernel types (linear or rbf), C (1, 100, 1000, 1000) and gamma (auto, 0.01, 0.1, 1) were obtained by using the GridSearchCV function. The best configuration achieved over 99% accuracy and had the following parameters:
kernel = rbf
C = 100
gamma = auto
We created sliding windows of multiple dimensions, ranging from 64x64 to 256x256 pixels, to test portions of the image against the classifier and retained only positive predictions. We generally slid the bigger windows from the bottom of the screen, as this would correspond to where vehicles would appear the largest. Smaller windows would slide higher on the screen. Moreover, we have the ability to configure the cell overlap and have currently set it 1 for maximum coverage (i.e. overlap every 14 pixels * scale, where the minimum window of scale 1 is 64x64). We stop attempting to detect vehicles on anything below 350 pixels in the y direction (i.e. higher portion of the image on the screen). The image below shows the example of overlapping sliding windows with cell overlap set to 4:
The classifier sometimes misclassifies sections of the images that are actually not a vehicle. To avoid highlighting those on the video, we take advantage of the redundancy we created with our multi-size sliding windows and count the number of times our classifier predicted vehicle for a given section of the image across all the windows it appears in. We first label objects with overlapping windows using scipy.ndimage.measurements’ label function. We then extract the positions of each label by determining the smallest bounding box our detected object could fit in. We only retain sections of the image where the detected threshold is set to a particular value. From experimentation, we find out that a threshold of 4 is enough to attain solid results on the project video. The photo below illustrates how the heatmap and thresholding work:
The first mini heatmap represents the original raw detections from the classifier, whereas the second one shows the thresholded areas, where the intensity of the red increases as the number of overlapping windows goes up. The last mini image on the right shows all the windows where our classifier predicted vehicle. In this example we were in fact using a LinearSVC, which tends to get the prediction wrong more often than the rbf SVC.
To further strengthen our pipeline, we have decided to smoothen all detected windows every n frames. To do so, we accumulate all detected windows between frames (n-1)*f+1 to n*f, where n is a positive scalar that represents the group of frames we are in. We have created the following class that encapsulates a detected object:
class DetectedObject: """ The DetectedObject class encapsulates information about an object identified by our detector """ def __init__(self, bounding_box, img_patch, frame_nb): self.bounding_box = bounding_box self.img_patch = img_patch self.frame_nb = frame_nb self.centroid = (int((bounding_box[0][0] + bounding_box[1][0]) / 2), int((bounding_box[0][1] + bounding_box[1][1]) / 2)) self.similar_objects = []...
Everytime we detect a new object on the current or next frames in the group, we check whether we have detected a similar object in the past, and if so, we append the similar object, thus increasing this object’s count across multiple frames. At frame n*f we only retain detected objects (and their associated bounding boxes) that have over m detected counts, thereby achieving some kind of double filtering in the pipeline (the first filtering was the threshold on the number overlapping bounding boxes).
On the below gif, you can see that there is a split second between when we have a single bounding box covering both cars and when each car has its own bounding box: the frame aggregation logic must have waited until the two windows appeared enough times before displaying them:
The video link below shows a successful detection of vehicles. As this is the final project for Term 1, I just had to use the track End Titles from Tron Legacy’s OST as background music — nothing else would have been more fitting 😎. Enjoy, as usual!
This was a tricky project, especially for those who opted for the more conventional computer vision and machine learning approach as opposed to deep learning. The following steps were quite time consuming:
determining the most suitable features (HOG, image color histogram, etc)
exploring the combination of HOG parameters + color spaces
applying grid search to find the most suitable classifier
Moreover, in our pipeline we struggled with the following:
Determining correct position of our sliding windows and the overlap
Identifying suitable threshold for overlapping detection
Adopting suitable frame sampling rate
Finding a good enough minimum detection count over multiple frames
Aggregating the combined window dimensions for overlapping detections
The pipeline would fail for object that are not vehicles but detected as such by the classifier, and where such false detections occur over enough overlapping windows to break through the threshold configured, and do so consistently over minimum number of frames per group. The drawn bounding boxes do not always perfectly fit the vehicles and are being redrawn every n frames, therefore causing the impression of a lack of smoothness. Moreover, the frame aggregation could be improved by using a rolling window of n frames as opposed to batch aggregation every n frames.
The last problem is that our pipeline is too slow. We should not be sliding windows across the whole screen, only portions of the screen need to be looked at: in the future we could employ decision trees to identify regions of interest for instance. We could also look at reducing the number of sliding windows as well as employing a faster classifier like a LinearSVC to speed up detection (but accuracy decreases significantly too). Still, this vehicle detection pipeline is unlikely to work in real time.
In the future, a deep learning approach using for instance Faster R-CNN or YOLO architectures will be adopted, as these are now the state-of-the-art for detection problems, and can run in real-time. Nevertheless, this is a worthwhile exercise to better understand traditional machine learning techniques and build intuition on feature selection. Moreover, I was struck by the beauty and simplicity of a technique like HOG, which still manages to produce solid results.
I would like to thank once again my mentor Dylan for his support and advice throughout this term. I am also very grateful to Udacity for putting in place such an exciting and challenging Nanodegree, with great projects and excellent material.
We stand on the shoulders of giants, and therefore I am thankful to all researchers and enthusiasts in the fields of artificial intelligence, computer vision, and beyond, for the work produced and shared via papers and code. Without those resources, I would not have been able to “borrow” their ideas and techniques and successfully complete this project.
Term 1 is now over 🎉🎉. I will begin Term 2 in January 2018, and in the meantime will work on deepening my nascent AI skills as well as resume work on side projects. Thanks for reading and stay tuned!
Thanks for reading this post. I hope you found it useful. I’m now building a new startup called EnVsion! At EnVsion, we’re creating the central repository for UX researchers and product teams to unlock the insights from their user interview videos. And of course we use AI for this ;).
If you’re a UX researcher or product manager feeling overwhelmed with all your video calls with users and customers, then EnVsion is for you!
You also can follow me on Twitter.
|
[
{
"code": null,
"e": 367,
"s": 172,
"text": "This is the final project of Term 1 of the Udacity Self-Driving Car Engineer Nanodegree. You can find all code related to this project on github. You can also read my posts on previous projects:"
},
{
"code": null,
"e": 421,
"s": 367,
"text": "project 1: Detecting Lane Lines Using Computer Vision"
},
{
"code": null,
"e": 480,
"s": 421,
"text": "project 2: Traffic Sign Classification Using Deep Learning"
},
{
"code": null,
"e": 537,
"s": 480,
"text": "project 3: Steering Angle Prediction Using Deep Learning"
},
{
"code": null,
"e": 594,
"s": 537,
"text": "project 4: Advanced Lane Detection Using Computer Vision"
},
{
"code": null,
"e": 1291,
"s": 594,
"text": "When we drive, we constantly pay attention to our environment, as our safety and that of many other people are at stake. We particularly look out for position of potential obstacles, whether they be other cars, pedestrians, or objects on the road. Similarly, as we develop the intelligence and sensors necessary to power a autonomous vehicles, it is of the utmost importance that such vehicles can detect obstacles as well, as it reinforces the car’s understanding of its environment. One of the most important types of ostacles to detect is other vehicles on the road, as they would most likely be the biggest objects in our lane or neighbouring ones and therefore constitute a potential hazard."
},
{
"code": null,
"e": 1688,
"s": 1291,
"text": "A number of techniques for obstacle detection have been developed throughout the literature, from traditional computer vision techniques to deep learning ones, and more. In this exercise, we build a vehicle detector by employing a conventional computer vision technique called Histogram of Oriented Gradients (HOG), combined with a machine learning algorithm called Support Vector Machines (SVM)."
},
{
"code": null,
"e": 1771,
"s": 1688,
"text": "Udacity generously provided a balanced dataset with the following characteristics:"
},
{
"code": null,
"e": 1795,
"s": 1771,
"text": "~ 9K images of vehicles"
},
{
"code": null,
"e": 1823,
"s": 1795,
"text": "~ 9K images of non-vehicles"
},
{
"code": null,
"e": 1844,
"s": 1823,
"text": "all images are 64x64"
},
{
"code": null,
"e": 2217,
"s": 1844,
"text": "The dataset comes from the GTI Vehicle Image Database, KITTI Vision Benchmark Suite, and examples extracted from the project video itself. The latter is much larger and was not used for this project. However, it would be a great addition in the future, especially as we plan to build a classifier using deep learning. You can see a sample of images from the dataset below:"
},
{
"code": null,
"e": 2595,
"s": 2217,
"text": "We can clearly see both vehicle and non-vehicle images. Non-vehicle images tend to be other elements of the road such as the asphalt, road signs or pavement. The distinction is very clear. Most images also display the vehicle in the center, but in different orientations, which is good. Moreover, there is a good variety of car types and colors, as well as lighting conditions."
},
{
"code": null,
"e": 2905,
"s": 2595,
"text": "Using HOG for detection was popularised by Navneet Dalal and Bill Triggs after showing impressive results in their paper named Histogram of Oriented Gradients For Human Detection. The algorithm is well explained by Satya Mallick on this post, for those who want to acquire a stronger fundamental grasp of HOG."
},
{
"code": null,
"e": 3013,
"s": 2905,
"text": "We firstly explored different configurations for the following values in the HOG algorithm, on a RGB image:"
},
{
"code": null,
"e": 3051,
"s": 3013,
"text": "number of orientations (denoted by o)"
},
{
"code": null,
"e": 3085,
"s": 3051,
"text": "pixels per cell (denoted by px/c)"
},
{
"code": null,
"e": 3237,
"s": 3085,
"text": "The cells per block were originally fixed at 2 (denoted by c/bk). The images below show the results obtained on the sample vehicle image in RGB format:"
},
{
"code": null,
"e": 3300,
"s": 3237,
"text": "From pure observation, it looks like a HOG configuration with:"
},
{
"code": null,
"e": 3316,
"s": 3300,
"text": "11 orientations"
},
{
"code": null,
"e": 3335,
"s": 3316,
"text": "14 pixels per cell"
},
{
"code": null,
"e": 3354,
"s": 3335,
"text": "2 cells per blocks"
},
{
"code": null,
"e": 3483,
"s": 3354,
"text": "produces the most distinctive gradients of a vehicle. We have not experimented with different cells per block so let us try now."
},
{
"code": null,
"e": 3680,
"s": 3483,
"text": "To the human eye, there is no significant difference that we notice visually. We would ideally like to reduce the feature space for faster computation. We will settle for now on 3 cells per block."
},
{
"code": null,
"e": 3899,
"s": 3680,
"text": "We must now explore the most suitable color space for our configuration, as it seems our HOG features across the 3 RGB channels are too similar, therefore it feels we are not generating features with enough variations."
},
{
"code": null,
"e": 3969,
"s": 3899,
"text": "We generate the following outputs across a multitude of color spaces:"
},
{
"code": null,
"e": 4309,
"s": 3969,
"text": "For some color channels, it is difficult to interpret the result of HOG. Interestingly, it seems the first color channel in YUV, YCrCb, and LAB could be enough to capture the gradients we are looking for. In HSV and HLS it is respectively on the Value and Lightness channels that HOG captures the most significant features for the vehicle."
},
{
"code": null,
"e": 4384,
"s": 4309,
"text": "To confirm our hypothesis, let us try with a different image of a vehicle:"
},
{
"code": null,
"e": 4695,
"s": 4384,
"text": "Houston, we’ve have a problem here... On a dark image such as the one above, we can observe that HOG on the channel that carries the most light information produces bad results. We must therefore take into account all color channels to capture the most features. In the end, our configuration looks as follows:"
},
{
"code": null,
"e": 4729,
"s": 4695,
"text": "ALL channels of YCrCb color space"
},
{
"code": null,
"e": 4752,
"s": 4729,
"text": "HOG orientations of 11"
},
{
"code": null,
"e": 4778,
"s": 4752,
"text": "HOG pixels per cell of 14"
},
{
"code": null,
"e": 4803,
"s": 4778,
"text": "HOG cells per block of 2"
},
{
"code": null,
"e": 4971,
"s": 4803,
"text": "We will also be adding color information to strengthen our feature set. To do so we simply produce histograms across all color channels, using 32 bins, as shown below:"
},
{
"code": null,
"e": 5584,
"s": 4971,
"text": "def color_histogram(img, nbins=32, bins_range=(0, 256)): \"\"\" Returns the histograms of the color image across all channels, as a concatenanted feature vector \"\"\" # Compute the histogram of the color channels separately channel1_hist = np.histogram(img[:,:,0], bins=nbins, range=bins_range) channel2_hist = np.histogram(img[:,:,1], bins=nbins, range=bins_range) channel3_hist = np.histogram(img[:,:,2], bins=nbins, range=bins_range) # Concatenate the histograms into a single feature vector and return it return np.concatenate((channel1_hist[0], channel2_hist[0], channel3_hist[0])) "
},
{
"code": null,
"e": 5740,
"s": 5584,
"text": "The classifier is responsible for categorising the images we submit into either vehicle or non-vehicle classes. To do so, we must take the following steps:"
},
{
"code": null,
"e": 5773,
"s": 5740,
"text": "Load our images from the dataset"
},
{
"code": null,
"e": 5804,
"s": 5773,
"text": "Extract the features we desire"
},
{
"code": null,
"e": 5829,
"s": 5804,
"text": "Normalise those features"
},
{
"code": null,
"e": 5872,
"s": 5829,
"text": "Split the dataset for training and testing"
},
{
"code": null,
"e": 5923,
"s": 5872,
"text": "Build a classifier with the appropriate parameters"
},
{
"code": null,
"e": 5961,
"s": 5923,
"text": "Train the classifier on training data"
},
{
"code": null,
"e": 6112,
"s": 5961,
"text": "As discussed in the previous section, we have decided to only retain one feature: the HOG feature vector computed on the Y channel of our YCrCb image."
},
{
"code": null,
"e": 6266,
"s": 6112,
"text": "We randomly split our dataset, leaving 20% of it for testing. Moreover, we scale the data by employing a sklearn.preprocessing.StandardScaler normaliser."
},
{
"code": null,
"e": 6704,
"s": 6266,
"text": "We did not have enough time to experiment with many classifiers so opted to use Support Vector Machines (SVMs) as they are commonly combined with HOG in the literature for object detection problems. Moreover, we used a SVC with kernel rbf as it provided the best accuracy, while being slower than a LinearSVC. We accepted the tradeoff as the detection of the SVC with rbf kernel was much stronger when we tested it on a series of images."
},
{
"code": null,
"e": 6949,
"s": 6704,
"text": "The ideal parameters among kernel types (linear or rbf), C (1, 100, 1000, 1000) and gamma (auto, 0.01, 0.1, 1) were obtained by using the GridSearchCV function. The best configuration achieved over 99% accuracy and had the following parameters:"
},
{
"code": null,
"e": 6962,
"s": 6949,
"text": "kernel = rbf"
},
{
"code": null,
"e": 6970,
"s": 6962,
"text": "C = 100"
},
{
"code": null,
"e": 6983,
"s": 6970,
"text": "gamma = auto"
},
{
"code": null,
"e": 7776,
"s": 6983,
"text": "We created sliding windows of multiple dimensions, ranging from 64x64 to 256x256 pixels, to test portions of the image against the classifier and retained only positive predictions. We generally slid the bigger windows from the bottom of the screen, as this would correspond to where vehicles would appear the largest. Smaller windows would slide higher on the screen. Moreover, we have the ability to configure the cell overlap and have currently set it 1 for maximum coverage (i.e. overlap every 14 pixels * scale, where the minimum window of scale 1 is 64x64). We stop attempting to detect vehicles on anything below 350 pixels in the y direction (i.e. higher portion of the image on the screen). The image below shows the example of overlapping sliding windows with cell overlap set to 4:"
},
{
"code": null,
"e": 8622,
"s": 7776,
"text": "The classifier sometimes misclassifies sections of the images that are actually not a vehicle. To avoid highlighting those on the video, we take advantage of the redundancy we created with our multi-size sliding windows and count the number of times our classifier predicted vehicle for a given section of the image across all the windows it appears in. We first label objects with overlapping windows using scipy.ndimage.measurements’ label function. We then extract the positions of each label by determining the smallest bounding box our detected object could fit in. We only retain sections of the image where the detected threshold is set to a particular value. From experimentation, we find out that a threshold of 4 is enough to attain solid results on the project video. The photo below illustrates how the heatmap and thresholding work:"
},
{
"code": null,
"e": 9059,
"s": 8622,
"text": "The first mini heatmap represents the original raw detections from the classifier, whereas the second one shows the thresholded areas, where the intensity of the red increases as the number of overlapping windows goes up. The last mini image on the right shows all the windows where our classifier predicted vehicle. In this example we were in fact using a LinearSVC, which tends to get the prediction wrong more often than the rbf SVC."
},
{
"code": null,
"e": 9387,
"s": 9059,
"text": "To further strengthen our pipeline, we have decided to smoothen all detected windows every n frames. To do so, we accumulate all detected windows between frames (n-1)*f+1 to n*f, where n is a positive scalar that represents the group of frames we are in. We have created the following class that encapsulates a detected object:"
},
{
"code": null,
"e": 9848,
"s": 9387,
"text": "class DetectedObject: \"\"\" The DetectedObject class encapsulates information about an object identified by our detector \"\"\" def __init__(self, bounding_box, img_patch, frame_nb): self.bounding_box = bounding_box self.img_patch = img_patch self.frame_nb = frame_nb self.centroid = (int((bounding_box[0][0] + bounding_box[1][0]) / 2), int((bounding_box[0][1] + bounding_box[1][1]) / 2)) self.similar_objects = []..."
},
{
"code": null,
"e": 10353,
"s": 9848,
"text": "Everytime we detect a new object on the current or next frames in the group, we check whether we have detected a similar object in the past, and if so, we append the similar object, thus increasing this object’s count across multiple frames. At frame n*f we only retain detected objects (and their associated bounding boxes) that have over m detected counts, thereby achieving some kind of double filtering in the pipeline (the first filtering was the threshold on the number overlapping bounding boxes)."
},
{
"code": null,
"e": 10631,
"s": 10353,
"text": "On the below gif, you can see that there is a split second between when we have a single bounding box covering both cars and when each car has its own bounding box: the frame aggregation logic must have waited until the two windows appeared enough times before displaying them:"
},
{
"code": null,
"e": 10881,
"s": 10631,
"text": "The video link below shows a successful detection of vehicles. As this is the final project for Term 1, I just had to use the track End Titles from Tron Legacy’s OST as background music — nothing else would have been more fitting 😎. Enjoy, as usual!"
},
{
"code": null,
"e": 11087,
"s": 10881,
"text": "This was a tricky project, especially for those who opted for the more conventional computer vision and machine learning approach as opposed to deep learning. The following steps were quite time consuming:"
},
{
"code": null,
"e": 11160,
"s": 11087,
"text": "determining the most suitable features (HOG, image color histogram, etc)"
},
{
"code": null,
"e": 11219,
"s": 11160,
"text": "exploring the combination of HOG parameters + color spaces"
},
{
"code": null,
"e": 11277,
"s": 11219,
"text": "applying grid search to find the most suitable classifier"
},
{
"code": null,
"e": 11336,
"s": 11277,
"text": "Moreover, in our pipeline we struggled with the following:"
},
{
"code": null,
"e": 11404,
"s": 11336,
"text": "Determining correct position of our sliding windows and the overlap"
},
{
"code": null,
"e": 11461,
"s": 11404,
"text": "Identifying suitable threshold for overlapping detection"
},
{
"code": null,
"e": 11499,
"s": 11461,
"text": "Adopting suitable frame sampling rate"
},
{
"code": null,
"e": 11566,
"s": 11499,
"text": "Finding a good enough minimum detection count over multiple frames"
},
{
"code": null,
"e": 11636,
"s": 11566,
"text": "Aggregating the combined window dimensions for overlapping detections"
},
{
"code": null,
"e": 12208,
"s": 11636,
"text": "The pipeline would fail for object that are not vehicles but detected as such by the classifier, and where such false detections occur over enough overlapping windows to break through the threshold configured, and do so consistently over minimum number of frames per group. The drawn bounding boxes do not always perfectly fit the vehicles and are being redrawn every n frames, therefore causing the impression of a lack of smoothness. Moreover, the frame aggregation could be improved by using a rolling window of n frames as opposed to batch aggregation every n frames."
},
{
"code": null,
"e": 12716,
"s": 12208,
"text": "The last problem is that our pipeline is too slow. We should not be sliding windows across the whole screen, only portions of the screen need to be looked at: in the future we could employ decision trees to identify regions of interest for instance. We could also look at reducing the number of sliding windows as well as employing a faster classifier like a LinearSVC to speed up detection (but accuracy decreases significantly too). Still, this vehicle detection pipeline is unlikely to work in real time."
},
{
"code": null,
"e": 13185,
"s": 12716,
"text": "In the future, a deep learning approach using for instance Faster R-CNN or YOLO architectures will be adopted, as these are now the state-of-the-art for detection problems, and can run in real-time. Nevertheless, this is a worthwhile exercise to better understand traditional machine learning techniques and build intuition on feature selection. Moreover, I was struck by the beauty and simplicity of a technique like HOG, which still manages to produce solid results."
},
{
"code": null,
"e": 13428,
"s": 13185,
"text": "I would like to thank once again my mentor Dylan for his support and advice throughout this term. I am also very grateful to Udacity for putting in place such an exciting and challenging Nanodegree, with great projects and excellent material."
},
{
"code": null,
"e": 13784,
"s": 13428,
"text": "We stand on the shoulders of giants, and therefore I am thankful to all researchers and enthusiasts in the fields of artificial intelligence, computer vision, and beyond, for the work produced and shared via papers and code. Without those resources, I would not have been able to “borrow” their ideas and techniques and successfully complete this project."
},
{
"code": null,
"e": 13984,
"s": 13784,
"text": "Term 1 is now over 🎉🎉. I will begin Term 2 in January 2018, and in the meantime will work on deepening my nascent AI skills as well as resume work on side projects. Thanks for reading and stay tuned!"
},
{
"code": null,
"e": 14270,
"s": 13984,
"text": "Thanks for reading this post. I hope you found it useful. I’m now building a new startup called EnVsion! At EnVsion, we’re creating the central repository for UX researchers and product teams to unlock the insights from their user interview videos. And of course we use AI for this ;)."
},
{
"code": null,
"e": 14412,
"s": 14270,
"text": "If you’re a UX researcher or product manager feeling overwhelmed with all your video calls with users and customers, then EnVsion is for you!"
}
] |
SQL - Logical Operators
|
Consider the CUSTOMERS table having the following records −
SQL> SELECT * FROM CUSTOMERS;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
7 rows in set (0.00 sec)
Here are some simple examples showing usage of SQL Comparison Operators −
SQL> SELECT * FROM CUSTOMERS WHERE AGE >= 25 AND SALARY >= 6500;
+----+----------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+---------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
+----+----------+-----+---------+---------+
2 rows in set (0.00 sec)
SQL> SELECT * FROM CUSTOMERS WHERE AGE >= 25 OR SALARY >= 6500;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
5 rows in set (0.00 sec)
SQL> SELECT * FROM CUSTOMERS WHERE AGE IS NOT NULL;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
7 rows in set (0.00 sec)
SQL> SELECT * FROM CUSTOMERS WHERE NAME LIKE 'Ko%';
+----+-------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+-------+-----+---------+---------+
| 6 | Komal | 22 | MP | 4500.00 |
+----+-------+-----+---------+---------+
1 row in set (0.00 sec)
SQL> SELECT * FROM CUSTOMERS WHERE AGE IN ( 25, 27 );
+----+----------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+---------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
+----+----------+-----+---------+---------+
3 rows in set (0.00 sec)
SQL> SELECT * FROM CUSTOMERS WHERE AGE BETWEEN 25 AND 27;
+----+----------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+---------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
+----+----------+-----+---------+---------+
3 rows in set (0.00 sec)
SQL> SELECT AGE FROM CUSTOMERS
WHERE EXISTS (SELECT AGE FROM CUSTOMERS WHERE SALARY > 6500);
+-----+
| AGE |
+-----+
| 32 |
| 25 |
| 23 |
| 25 |
| 27 |
| 22 |
| 24 |
+-----+
7 rows in set (0.02 sec)
SQL> SELECT * FROM CUSTOMERS
WHERE AGE > ALL (SELECT AGE FROM CUSTOMERS WHERE SALARY > 6500);
+----+--------+-----+-----------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+--------+-----+-----------+---------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
+----+--------+-----+-----------+---------+
1 row in set (0.02 sec)
SQL> SELECT * FROM CUSTOMERS
WHERE AGE > ANY (SELECT AGE FROM CUSTOMERS WHERE SALARY > 6500);
+----+----------+-----+-----------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+---------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
+----+----------+-----+-----------+---------+
4 rows in set (0.00 sec)
42 Lectures
5 hours
Anadi Sharma
14 Lectures
2 hours
Anadi Sharma
44 Lectures
4.5 hours
Anadi Sharma
94 Lectures
7 hours
Abhishek And Pukhraj
80 Lectures
6.5 hours
Oracle Master Training | 150,000+ Students Worldwide
31 Lectures
6 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2513,
"s": 2453,
"text": "Consider the CUSTOMERS table having the following records −"
},
{
"code": null,
"e": 2543,
"s": 2513,
"text": "SQL> SELECT * FROM CUSTOMERS;"
},
{
"code": null,
"e": 3086,
"s": 2543,
"text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n7 rows in set (0.00 sec)\n"
},
{
"code": null,
"e": 3160,
"s": 3086,
"text": "Here are some simple examples showing usage of SQL Comparison Operators −"
},
{
"code": null,
"e": 3225,
"s": 3160,
"text": "SQL> SELECT * FROM CUSTOMERS WHERE AGE >= 25 AND SALARY >= 6500;"
},
{
"code": null,
"e": 3515,
"s": 3225,
"text": "+----+----------+-----+---------+---------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+---------+---------+\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n+----+----------+-----+---------+---------+\n2 rows in set (0.00 sec)\n"
},
{
"code": null,
"e": 3579,
"s": 3515,
"text": "SQL> SELECT * FROM CUSTOMERS WHERE AGE >= 25 OR SALARY >= 6500;"
},
{
"code": null,
"e": 4028,
"s": 3579,
"text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n5 rows in set (0.00 sec)\n"
},
{
"code": null,
"e": 4081,
"s": 4028,
"text": "SQL> SELECT * FROM CUSTOMERS WHERE AGE IS NOT NULL;"
},
{
"code": null,
"e": 4624,
"s": 4081,
"text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n7 rows in set (0.00 sec)\n"
},
{
"code": null,
"e": 4676,
"s": 4624,
"text": "SQL> SELECT * FROM CUSTOMERS WHERE NAME LIKE 'Ko%';"
},
{
"code": null,
"e": 4906,
"s": 4676,
"text": "+----+-------+-----+---------+---------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+-------+-----+---------+---------+\n| 6 | Komal | 22 | MP | 4500.00 |\n+----+-------+-----+---------+---------+\n1 row in set (0.00 sec)\n"
},
{
"code": null,
"e": 4960,
"s": 4906,
"text": "SQL> SELECT * FROM CUSTOMERS WHERE AGE IN ( 25, 27 );"
},
{
"code": null,
"e": 5294,
"s": 4960,
"text": "+----+----------+-----+---------+---------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+---------+---------+\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n+----+----------+-----+---------+---------+\n3 rows in set (0.00 sec)\n"
},
{
"code": null,
"e": 5352,
"s": 5294,
"text": "SQL> SELECT * FROM CUSTOMERS WHERE AGE BETWEEN 25 AND 27;"
},
{
"code": null,
"e": 5686,
"s": 5352,
"text": "+----+----------+-----+---------+---------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+---------+---------+\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n+----+----------+-----+---------+---------+\n3 rows in set (0.00 sec)\n"
},
{
"code": null,
"e": 5780,
"s": 5686,
"text": "SQL> SELECT AGE FROM CUSTOMERS \nWHERE EXISTS (SELECT AGE FROM CUSTOMERS WHERE SALARY > 6500);"
},
{
"code": null,
"e": 5894,
"s": 5780,
"text": "+-----+\n| AGE |\n+-----+\n| 32 |\n| 25 |\n| 23 |\n| 25 |\n| 27 |\n| 22 |\n| 24 |\n+-----+\n7 rows in set (0.02 sec)\n"
},
{
"code": null,
"e": 5989,
"s": 5894,
"text": "SQL> SELECT * FROM CUSTOMERS \nWHERE AGE > ALL (SELECT AGE FROM CUSTOMERS WHERE SALARY > 6500);"
},
{
"code": null,
"e": 6234,
"s": 5989,
"text": "+----+--------+-----+-----------+---------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+--------+-----+-----------+---------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n+----+--------+-----+-----------+---------+\n1 row in set (0.02 sec)\n"
},
{
"code": null,
"e": 6329,
"s": 6234,
"text": "SQL> SELECT * FROM CUSTOMERS \nWHERE AGE > ANY (SELECT AGE FROM CUSTOMERS WHERE SALARY > 6500);"
},
{
"code": null,
"e": 6723,
"s": 6329,
"text": "+----+----------+-----+-----------+---------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+---------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n+----+----------+-----+-----------+---------+\n4 rows in set (0.00 sec)\n"
},
{
"code": null,
"e": 6756,
"s": 6723,
"text": "\n 42 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6770,
"s": 6756,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6803,
"s": 6770,
"text": "\n 14 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6817,
"s": 6803,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6852,
"s": 6817,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6866,
"s": 6852,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6899,
"s": 6866,
"text": "\n 94 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 6921,
"s": 6899,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 6956,
"s": 6921,
"text": "\n 80 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 7010,
"s": 6956,
"text": " Oracle Master Training | 150,000+ Students Worldwide"
},
{
"code": null,
"e": 7043,
"s": 7010,
"text": "\n 31 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 7071,
"s": 7043,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 7078,
"s": 7071,
"text": " Print"
},
{
"code": null,
"e": 7089,
"s": 7078,
"text": " Add Notes"
}
] |
How to get the width and height of an android.widget.ImageView in Kotlin?
|
This example demonstrates how to get the width and height of an android.widget.ImageView in Kotlin.
Step 1 − Create a new project in Android Studio, go to File ? New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:padding="8dp"
tools:context=".MainActivity">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="400dp"
android:src="@drawable/image" />
<Button
android:id="@+id/btnCheckSize"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20sp"
android:text="Check ImageView size"
android:textSize="12sp"
android:textStyle="bold" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text=""
android:textColor="@android:color/background_dark"
android:textSize="16sp"
android:textStyle="bold" />
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
lateinit var imageView: ImageView
lateinit var textView: TextView
lateinit var button: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
imageView = findViewById(R.id.imageView)
textView = findViewById(R.id.textView)
button = findViewById(R.id.btnCheckSize)
button.setOnClickListener { textView.text = String.format("Size of ImageView:\nHeight: %s\nWidth:
%s", imageView.width.toString(), imageView.height.toString()) }
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.q1">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
|
[
{
"code": null,
"e": 1162,
"s": 1062,
"text": "This example demonstrates how to get the width and height of an android.widget.ImageView in Kotlin."
},
{
"code": null,
"e": 1291,
"s": 1162,
"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": 1356,
"s": 1291,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2496,
"s": 1356,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\nxmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:gravity=\"center_horizontal\"\n android:orientation=\"vertical\"\n android:padding=\"8dp\"\n tools:context=\".MainActivity\">\n <ImageView\n android:id=\"@+id/imageView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"400dp\"\n android:src=\"@drawable/image\" />\n <Button\n android:id=\"@+id/btnCheckSize\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"20sp\"\n android:text=\"Check ImageView size\"\n android:textSize=\"12sp\"\n android:textStyle=\"bold\" />\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"10dp\"\n android:text=\"\"\n android:textColor=\"@android:color/background_dark\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold\" />\n</LinearLayout>"
},
{
"code": null,
"e": 2551,
"s": 2496,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 3324,
"s": 2551,
"text": "import android.os.Bundle\nimport android.widget.Button\nimport android.widget.ImageView\nimport android.widget.TextView\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n lateinit var imageView: ImageView\n lateinit var textView: TextView\n lateinit var button: Button\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n imageView = findViewById(R.id.imageView)\n textView = findViewById(R.id.textView)\n button = findViewById(R.id.btnCheckSize)\n button.setOnClickListener { textView.text = String.format(\"Size of ImageView:\\nHeight: %s\\nWidth:\n %s\", imageView.width.toString(), imageView.height.toString()) }\n }\n}"
},
{
"code": null,
"e": 3379,
"s": 3324,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4045,
"s": 3379,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.q1\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4393,
"s": 4045,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen"
}
] |
Draw Graph Grid Using Turtle in Python - GeeksforGeeks
|
29 Aug, 2021
Prerequisite: Turtle Programming Basics
Turtle is an inbuilt module in Python. It provides drawing using a screen (cardboard) and turtle (pen). To draw something on the screen, we need to move the turtle (pen). To move turtle, there are some functions i.e forward(), backward(), etc.
Approach:
Following steps are used :
Import turtle
Set screen
Make turtle
Draw the y-axis lines
Draw the x-axis lines
Draw the x-axis and y-axis with labeling.
Below is the implementation :
Python3
# import package and making objectsimport turtle sc=turtle.Screen()trtl=turtle.Turtle() # method to draw y-axis linesdef drawy(val): # line trtl.forward(300) # set position trtl.up() trtl.setpos(val,300) trtl.down() # another line trtl.backward(300) # set position again trtl.up() trtl.setpos(val+10,0) trtl.down() # method to draw y-axis linesdef drawx(val): # line trtl.forward(300) # set position trtl.up() trtl.setpos(300,val) trtl.down() # another line trtl.backward(300) # set position again trtl.up() trtl.setpos(0,val+10) trtl.down() # method to label the graph griddef lab(): # set position trtl.penup() trtl.setpos(155,155) trtl.pendown() # write 0 trtl.write(0,font=("Verdana", 12, "bold")) # set position again trtl.penup() trtl.setpos(290,155) trtl.pendown() # write x trtl.write("x",font=("Verdana", 12, "bold")) # set position again trtl.penup() trtl.setpos(155,290) trtl.pendown() # write y trtl.write("y",font=("Verdana", 12, "bold")) # Main Section# set screensc.setup(800,800) # set turtle featurestrtl.speed(100)trtl.left(90) trtl.color('lightgreen') # y linesfor i in range(30): drawy(10*(i+1)) # set position for x linestrtl.right(90)trtl.up()trtl.setpos(0,0)trtl.down() # x linesfor i in range(30): drawx(10*(i+1)) # axistrtl.color('green') # set position for x axistrtl.up()trtl.setpos(0,150)trtl.down() # x-axistrtl.forward(300) # set position for y axistrtl.left(90)trtl.up()trtl.setpos(150,0)trtl.down() # y-axistrtl.forward(300) # labelinglab() # hide the turtletrtl.hideturtle()
Output :
surinderdawra388
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
|
[
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n29 Aug, 2021"
},
{
"code": null,
"e": 23941,
"s": 23901,
"text": "Prerequisite: Turtle Programming Basics"
},
{
"code": null,
"e": 24185,
"s": 23941,
"text": "Turtle is an inbuilt module in Python. It provides drawing using a screen (cardboard) and turtle (pen). To draw something on the screen, we need to move the turtle (pen). To move turtle, there are some functions i.e forward(), backward(), etc."
},
{
"code": null,
"e": 24195,
"s": 24185,
"text": "Approach:"
},
{
"code": null,
"e": 24222,
"s": 24195,
"text": "Following steps are used :"
},
{
"code": null,
"e": 24236,
"s": 24222,
"text": "Import turtle"
},
{
"code": null,
"e": 24247,
"s": 24236,
"text": "Set screen"
},
{
"code": null,
"e": 24259,
"s": 24247,
"text": "Make turtle"
},
{
"code": null,
"e": 24281,
"s": 24259,
"text": "Draw the y-axis lines"
},
{
"code": null,
"e": 24303,
"s": 24281,
"text": "Draw the x-axis lines"
},
{
"code": null,
"e": 24345,
"s": 24303,
"text": "Draw the x-axis and y-axis with labeling."
},
{
"code": null,
"e": 24375,
"s": 24345,
"text": "Below is the implementation :"
},
{
"code": null,
"e": 24383,
"s": 24375,
"text": "Python3"
},
{
"code": "# import package and making objectsimport turtle sc=turtle.Screen()trtl=turtle.Turtle() # method to draw y-axis linesdef drawy(val): # line trtl.forward(300) # set position trtl.up() trtl.setpos(val,300) trtl.down() # another line trtl.backward(300) # set position again trtl.up() trtl.setpos(val+10,0) trtl.down() # method to draw y-axis linesdef drawx(val): # line trtl.forward(300) # set position trtl.up() trtl.setpos(300,val) trtl.down() # another line trtl.backward(300) # set position again trtl.up() trtl.setpos(0,val+10) trtl.down() # method to label the graph griddef lab(): # set position trtl.penup() trtl.setpos(155,155) trtl.pendown() # write 0 trtl.write(0,font=(\"Verdana\", 12, \"bold\")) # set position again trtl.penup() trtl.setpos(290,155) trtl.pendown() # write x trtl.write(\"x\",font=(\"Verdana\", 12, \"bold\")) # set position again trtl.penup() trtl.setpos(155,290) trtl.pendown() # write y trtl.write(\"y\",font=(\"Verdana\", 12, \"bold\")) # Main Section# set screensc.setup(800,800) # set turtle featurestrtl.speed(100)trtl.left(90) trtl.color('lightgreen') # y linesfor i in range(30): drawy(10*(i+1)) # set position for x linestrtl.right(90)trtl.up()trtl.setpos(0,0)trtl.down() # x linesfor i in range(30): drawx(10*(i+1)) # axistrtl.color('green') # set position for x axistrtl.up()trtl.setpos(0,150)trtl.down() # x-axistrtl.forward(300) # set position for y axistrtl.left(90)trtl.up()trtl.setpos(150,0)trtl.down() # y-axistrtl.forward(300) # labelinglab() # hide the turtletrtl.hideturtle()",
"e": 26110,
"s": 24383,
"text": null
},
{
"code": null,
"e": 26123,
"s": 26114,
"text": "Output :"
},
{
"code": null,
"e": 26144,
"s": 26127,
"text": "surinderdawra388"
},
{
"code": null,
"e": 26158,
"s": 26144,
"text": "Python-turtle"
},
{
"code": null,
"e": 26165,
"s": 26158,
"text": "Python"
},
{
"code": null,
"e": 26263,
"s": 26165,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26272,
"s": 26263,
"text": "Comments"
},
{
"code": null,
"e": 26285,
"s": 26272,
"text": "Old Comments"
},
{
"code": null,
"e": 26317,
"s": 26285,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26373,
"s": 26317,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26415,
"s": 26373,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26457,
"s": 26415,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26493,
"s": 26457,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 26515,
"s": 26493,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26554,
"s": 26515,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26581,
"s": 26554,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26612,
"s": 26581,
"text": "Python | os.path.join() method"
}
] |
Design and Analysis Radix Sort
|
Radix sort is a small method that many people intuitively use when alphabetizing a large list of names. Specifically, the list of names is first sorted according to the first letter of each name, that is, the names are arranged in 26 classes.
Intuitively, one might want to sort numbers on their most significant digit. However, Radix sort works counter-intuitively by sorting on the least significant digits first. On the first pass, all the numbers are sorted on the least significant digit and combined in an array. Then on the second pass, the entire numbers are sorted again on the second least significant digits and combined in an array and so on.
Algorithm: Radix-Sort (list, n)
shift = 1
for loop = 1 to keysize do
for entry = 1 to n do
bucketnumber = (list[entry].key / shift) mod 10
append (bucket[bucketnumber], list[entry])
list = combinebuckets()
shift = shift * 10
Each key is looked at once for each digit (or letter if the keys are alphabetic) of the longest key. Hence, if the longest key has m digits and there are n keys, radix sort has order O(m.n).
However, if we look at these two values, the size of the keys will be relatively small when compared to the number of keys. For example, if we have six-digit keys, we could have a million different records.
Here, we see that the size of the keys is not significant, and this algorithm is of linear complexity O(n).
Following example shows how Radix sort operates on seven 3-digits number.
In the above example, the first column is the input. The remaining columns show the list after successive sorts on increasingly significant digits position. The code for Radix sort assumes that each element in an array A of n elements has d digits, where digit 1 is the lowest-order digit and d is the highest-order digit.
102 Lectures
10 hours
Arnab Chakraborty
30 Lectures
3 hours
Arnab Chakraborty
31 Lectures
4 hours
Arnab Chakraborty
43 Lectures
1.5 hours
Manoj Kumar
7 Lectures
1 hours
Zach Miller
54 Lectures
4 hours
Sasha Miller
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2842,
"s": 2599,
"text": "Radix sort is a small method that many people intuitively use when alphabetizing a large list of names. Specifically, the list of names is first sorted according to the first letter of each name, that is, the names are arranged in 26 classes."
},
{
"code": null,
"e": 3254,
"s": 2842,
"text": "Intuitively, one might want to sort numbers on their most significant digit. However, Radix sort works counter-intuitively by sorting on the least significant digits first. On the first pass, all the numbers are sorted on the least significant digit and combined in an array. Then on the second pass, the entire numbers are sorted again on the second least significant digits and combined in an array and so on."
},
{
"code": null,
"e": 3509,
"s": 3254,
"text": "Algorithm: Radix-Sort (list, n) \nshift = 1 \nfor loop = 1 to keysize do \n for entry = 1 to n do \n bucketnumber = (list[entry].key / shift) mod 10 \n append (bucket[bucketnumber], list[entry]) \n list = combinebuckets() \n shift = shift * 10 \n"
},
{
"code": null,
"e": 3700,
"s": 3509,
"text": "Each key is looked at once for each digit (or letter if the keys are alphabetic) of the longest key. Hence, if the longest key has m digits and there are n keys, radix sort has order O(m.n)."
},
{
"code": null,
"e": 3907,
"s": 3700,
"text": "However, if we look at these two values, the size of the keys will be relatively small when compared to the number of keys. For example, if we have six-digit keys, we could have a million different records."
},
{
"code": null,
"e": 4015,
"s": 3907,
"text": "Here, we see that the size of the keys is not significant, and this algorithm is of linear complexity O(n)."
},
{
"code": null,
"e": 4089,
"s": 4015,
"text": "Following example shows how Radix sort operates on seven 3-digits number."
},
{
"code": null,
"e": 4412,
"s": 4089,
"text": "In the above example, the first column is the input. The remaining columns show the list after successive sorts on increasingly significant digits position. The code for Radix sort assumes that each element in an array A of n elements has d digits, where digit 1 is the lowest-order digit and d is the highest-order digit."
},
{
"code": null,
"e": 4447,
"s": 4412,
"text": "\n 102 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 4466,
"s": 4447,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4499,
"s": 4466,
"text": "\n 30 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 4518,
"s": 4499,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4551,
"s": 4518,
"text": "\n 31 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4570,
"s": 4551,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4605,
"s": 4570,
"text": "\n 43 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4618,
"s": 4605,
"text": " Manoj Kumar"
},
{
"code": null,
"e": 4650,
"s": 4618,
"text": "\n 7 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4663,
"s": 4650,
"text": " Zach Miller"
},
{
"code": null,
"e": 4696,
"s": 4663,
"text": "\n 54 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4710,
"s": 4696,
"text": " Sasha Miller"
},
{
"code": null,
"e": 4717,
"s": 4710,
"text": " Print"
},
{
"code": null,
"e": 4728,
"s": 4717,
"text": " Add Notes"
}
] |
How to pass parameters to a method in C#?
|
To pass parameters to a method in C#, let us see how to pass parameters by value. In this mechanism, when a method is called, a new storage location is created for each value parameter.
The values of the actual parameters are copied into them. Hence, the changes made to the parameter inside the method have no effect on the argument.
Here is the example showing how to pass parameters to a method −
Live Demo
using System;
namespace Demo {
class NumberManipulator {
public void swap(int x, int y) {
int temp;
temp = x;
x = y;
y = temp;
}
static void Main(string[] args) {
NumberManipulator n = new NumberManipulator();
int a = 50;
int b = 150;
Console.WriteLine("Before swap, value of a : {0}", a);
Console.WriteLine("Before swap, value of b : {0}", b);
/* calling a function to swap the values */
n.swap(a, b);
Console.WriteLine("After swap, value of a : {0}", a);
Console.WriteLine("After swap, value of b : {0}", b);
Console.ReadLine();
}
}
}
Before swap, value of a : 50
Before swap, value of b : 150
After swap, value of a : 50
After swap, value of b : 150
|
[
{
"code": null,
"e": 1248,
"s": 1062,
"text": "To pass parameters to a method in C#, let us see how to pass parameters by value. In this mechanism, when a method is called, a new storage location is created for each value parameter."
},
{
"code": null,
"e": 1397,
"s": 1248,
"text": "The values of the actual parameters are copied into them. Hence, the changes made to the parameter inside the method have no effect on the argument."
},
{
"code": null,
"e": 1462,
"s": 1397,
"text": "Here is the example showing how to pass parameters to a method −"
},
{
"code": null,
"e": 1473,
"s": 1462,
"text": " Live Demo"
},
{
"code": null,
"e": 2167,
"s": 1473,
"text": "using System;\n\nnamespace Demo {\n class NumberManipulator {\n public void swap(int x, int y) {\n int temp;\n temp = x;\n x = y;\n y = temp;\n }\n static void Main(string[] args) {\n NumberManipulator n = new NumberManipulator();\n int a = 50;\n int b = 150;\n Console.WriteLine(\"Before swap, value of a : {0}\", a);\n Console.WriteLine(\"Before swap, value of b : {0}\", b);\n /* calling a function to swap the values */\n n.swap(a, b);\n Console.WriteLine(\"After swap, value of a : {0}\", a);\n Console.WriteLine(\"After swap, value of b : {0}\", b);\n Console.ReadLine();\n }\n }\n}"
},
{
"code": null,
"e": 2283,
"s": 2167,
"text": "Before swap, value of a : 50\nBefore swap, value of b : 150\nAfter swap, value of a : 50\nAfter swap, value of b : 150"
}
] |
Plot parallel coordinates in Matplotlib
|
To plot parallel coordinates, we can take the following Steps −
Load dataset iris using Seaborn (Need internet).
Load dataset iris using Seaborn (Need internet).
Pass the loaded data into the parallel_coordinates() method, which will help in parallel plotting.
Pass the loaded data into the parallel_coordinates() method, which will help in parallel plotting.
To display the figure, use the show() method.
To display the figure, use the show() method.
import matplotlib.pyplot as plt
from pandas.plotting import parallel_coordinates
import seaborn as sns
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
data = sns.load_dataset('iris')
parallel_coordinates(data, 'species', colormap=plt.get_cmap("Set2"))
plt.show()
|
[
{
"code": null,
"e": 1126,
"s": 1062,
"text": "To plot parallel coordinates, we can take the following Steps −"
},
{
"code": null,
"e": 1175,
"s": 1126,
"text": "Load dataset iris using Seaborn (Need internet)."
},
{
"code": null,
"e": 1224,
"s": 1175,
"text": "Load dataset iris using Seaborn (Need internet)."
},
{
"code": null,
"e": 1323,
"s": 1224,
"text": "Pass the loaded data into the parallel_coordinates() method, which will help in parallel plotting."
},
{
"code": null,
"e": 1422,
"s": 1323,
"text": "Pass the loaded data into the parallel_coordinates() method, which will help in parallel plotting."
},
{
"code": null,
"e": 1468,
"s": 1422,
"text": "To display the figure, use the show() method."
},
{
"code": null,
"e": 1514,
"s": 1468,
"text": "To display the figure, use the show() method."
},
{
"code": null,
"e": 1816,
"s": 1514,
"text": "import matplotlib.pyplot as plt\nfrom pandas.plotting import parallel_coordinates\nimport seaborn as sns\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\ndata = sns.load_dataset('iris')\nparallel_coordinates(data, 'species', colormap=plt.get_cmap(\"Set2\"))\nplt.show()"
}
] |
How to get the Tkinter Label text?
|
Tkinter Labels are used to create and display text or images on the window. It has several components and functions that can be used to customize the label information such as fontfamily, padding, width, height, etc. In order to get the Label text on the window, we can write the value for the text that has to be displayed on the window.
#Import the required library
from tkinter import *
#Create an instance of tkinter frame
win= Tk()
#Define the geometry of the window
win.geometry("600x250")
#Create a Label with Text
my_text= Label(win, text= "This is a New Line Text", font=('Helvetica bold', 16))
my_text.pack(pady=15)
#Print the label text
print(my_text['text'])
win.mainloop()
The above code will display the Label “This is a New Line Text” which can be printed by the print function.
|
[
{
"code": null,
"e": 1401,
"s": 1062,
"text": "Tkinter Labels are used to create and display text or images on the window. It has several components and functions that can be used to customize the label information such as fontfamily, padding, width, height, etc. In order to get the Label text on the window, we can write the value for the text that has to be displayed on the window."
},
{
"code": null,
"e": 1753,
"s": 1401,
"text": "#Import the required library\nfrom tkinter import *\n\n#Create an instance of tkinter frame\nwin= Tk()\n\n#Define the geometry of the window\nwin.geometry(\"600x250\")\n\n#Create a Label with Text\nmy_text= Label(win, text= \"This is a New Line Text\", font=('Helvetica bold', 16))\nmy_text.pack(pady=15)\n\n#Print the label text\nprint(my_text['text'])\n\nwin.mainloop()"
},
{
"code": null,
"e": 1861,
"s": 1753,
"text": "The above code will display the Label “This is a New Line Text” which can be printed by the print function."
}
] |
Find the minimum and maximum values that can be calculated by summing exactly four of the five integers in JavaScript
|
Given an array of five positive integers, we are required to find the minimum and maximum values that can be calculated by summing exactly four of the five integers.
Then print the respective minimum and maximum values as a single line of two spaceseparated long integers.
The array is not sorted all the times.
For example −
const arr = [1, 3, 5, 7, 9]
The minimum sum is −
1 + 3 + 5 + 7 = 16
and the maximum sum is −
3 + 5 + 7 = 24
The return value of the function should be −
[16, 24];
The code for this will be −
const arr = [1, 3, 5, 7, 9]
const findMinMaxSum = (arr = []) => {
let numbers = arr.slice().sort();
let maxScore = 0;
let minScore = 0;
for(let i = 0; i < numbers.length − 1; i++) {
minScore += numbers[i];
};
for(let j = 1; j < numbers.length; j++) {
maxScore += numbers[j];
};
return [minScore, maxScore];
};
console.log(findMinMaxSum(arr));
And the output in the console will be −
[16, 24]
|
[
{
"code": null,
"e": 1228,
"s": 1062,
"text": "Given an array of five positive integers, we are required to find the minimum and maximum values that can be calculated by summing exactly four of the five integers."
},
{
"code": null,
"e": 1335,
"s": 1228,
"text": "Then print the respective minimum and maximum values as a single line of two spaceseparated long integers."
},
{
"code": null,
"e": 1374,
"s": 1335,
"text": "The array is not sorted all the times."
},
{
"code": null,
"e": 1388,
"s": 1374,
"text": "For example −"
},
{
"code": null,
"e": 1416,
"s": 1388,
"text": "const arr = [1, 3, 5, 7, 9]"
},
{
"code": null,
"e": 1437,
"s": 1416,
"text": "The minimum sum is −"
},
{
"code": null,
"e": 1456,
"s": 1437,
"text": "1 + 3 + 5 + 7 = 16"
},
{
"code": null,
"e": 1481,
"s": 1456,
"text": "and the maximum sum is −"
},
{
"code": null,
"e": 1496,
"s": 1481,
"text": "3 + 5 + 7 = 24"
},
{
"code": null,
"e": 1541,
"s": 1496,
"text": "The return value of the function should be −"
},
{
"code": null,
"e": 1551,
"s": 1541,
"text": "[16, 24];"
},
{
"code": null,
"e": 1579,
"s": 1551,
"text": "The code for this will be −"
},
{
"code": null,
"e": 1958,
"s": 1579,
"text": "const arr = [1, 3, 5, 7, 9]\nconst findMinMaxSum = (arr = []) => {\n let numbers = arr.slice().sort();\n let maxScore = 0;\n let minScore = 0;\n for(let i = 0; i < numbers.length − 1; i++) {\n minScore += numbers[i];\n };\n for(let j = 1; j < numbers.length; j++) {\n maxScore += numbers[j];\n };\n return [minScore, maxScore];\n};\nconsole.log(findMinMaxSum(arr));"
},
{
"code": null,
"e": 1998,
"s": 1958,
"text": "And the output in the console will be −"
},
{
"code": null,
"e": 2007,
"s": 1998,
"text": "[16, 24]"
}
] |
Program to convert Byte array to IP Address
|
24 Apr, 2018
Given a Byte Array, convert it to the format of IP Address.
Examples:
Input : {16, 16, 16, 16}
Output : 16.16.16.16
Input : {172, 31, 102, 14}
Output : 172.31.102.14
Byte arrays:A byte is collection of bits (8). Byte arrays are arrays of contiguous bytes and can be used to store binary information. With byte arrays, one can work directly on bytes and thus control the bits. Byte arrays provide a faster way of accessing each byte in use.For more details: https://msdn.microsoft.com/en-us/library/dd126860.aspx
Syntax:
byte[] ArrayName = new byte[]
IPAddress Class:The IPAddress class contains the address of computer on IP network. IPAddress class accommodates IP Address values passed to or returned by Simple Network Management Protocol (SNMP) agents by extending the OctetString Class. IPAddress Class comes under ‘System.Net’ namespace.
Refer Link for details: http://snmpsharpnet.sourceforge.net/ver0-4/html/T_SnmpSharpNet_IpAddress.htm
Syntax:
[Serializable]
public class IPAddress
Using Byte Arrays with IPAddress Class
IPAddress ObjectName = new IPAddress(byte[])
Approach:The IPAddress Class is used to get the IP address. The IP Address is created with the Address property set to address. If the length of address is 4, IPAddress(Byte[]) constructs an IPv4 address otherwise, an IPv6 address with a scope of 0 is constructed. The Byte array is assumed to be in network byte order with the most significant byte in index position 0.
// C# code to convert Byte array to IP Addressusing System;using System.Net; public class GFG { public static void Main() { /* Initializes a new instance of the IPAddress class with the address specified as a Byte Array.*/ IPAddress add = new IPAddress(new byte[] { 172, 31, 102, 14 }); /* ToString() Converts an Internet address to its standard notation and console.WriteLine is used for printing*/ Console.WriteLine(add.ToString()); }}
Output:
172.31.102.14
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Apr, 2018"
},
{
"code": null,
"e": 88,
"s": 28,
"text": "Given a Byte Array, convert it to the format of IP Address."
},
{
"code": null,
"e": 98,
"s": 88,
"text": "Examples:"
},
{
"code": null,
"e": 196,
"s": 98,
"text": "Input : {16, 16, 16, 16}\nOutput : 16.16.16.16\n\nInput : {172, 31, 102, 14}\nOutput : 172.31.102.14\n"
},
{
"code": null,
"e": 542,
"s": 196,
"text": "Byte arrays:A byte is collection of bits (8). Byte arrays are arrays of contiguous bytes and can be used to store binary information. With byte arrays, one can work directly on bytes and thus control the bits. Byte arrays provide a faster way of accessing each byte in use.For more details: https://msdn.microsoft.com/en-us/library/dd126860.aspx"
},
{
"code": null,
"e": 550,
"s": 542,
"text": "Syntax:"
},
{
"code": null,
"e": 581,
"s": 550,
"text": "byte[] ArrayName = new byte[] "
},
{
"code": null,
"e": 874,
"s": 581,
"text": "IPAddress Class:The IPAddress class contains the address of computer on IP network. IPAddress class accommodates IP Address values passed to or returned by Simple Network Management Protocol (SNMP) agents by extending the OctetString Class. IPAddress Class comes under ‘System.Net’ namespace."
},
{
"code": null,
"e": 975,
"s": 874,
"text": "Refer Link for details: http://snmpsharpnet.sourceforge.net/ver0-4/html/T_SnmpSharpNet_IpAddress.htm"
},
{
"code": null,
"e": 983,
"s": 975,
"text": "Syntax:"
},
{
"code": null,
"e": 1021,
"s": 983,
"text": "[Serializable]\npublic class IPAddress"
},
{
"code": null,
"e": 1060,
"s": 1021,
"text": "Using Byte Arrays with IPAddress Class"
},
{
"code": null,
"e": 1105,
"s": 1060,
"text": "IPAddress ObjectName = new IPAddress(byte[])"
},
{
"code": null,
"e": 1476,
"s": 1105,
"text": "Approach:The IPAddress Class is used to get the IP address. The IP Address is created with the Address property set to address. If the length of address is 4, IPAddress(Byte[]) constructs an IPv4 address otherwise, an IPv6 address with a scope of 0 is constructed. The Byte array is assumed to be in network byte order with the most significant byte in index position 0."
},
{
"code": "// C# code to convert Byte array to IP Addressusing System;using System.Net; public class GFG { public static void Main() { /* Initializes a new instance of the IPAddress class with the address specified as a Byte Array.*/ IPAddress add = new IPAddress(new byte[] { 172, 31, 102, 14 }); /* ToString() Converts an Internet address to its standard notation and console.WriteLine is used for printing*/ Console.WriteLine(add.ToString()); }}",
"e": 2017,
"s": 1476,
"text": null
},
{
"code": null,
"e": 2025,
"s": 2017,
"text": "Output:"
},
{
"code": null,
"e": 2039,
"s": 2025,
"text": "172.31.102.14"
},
{
"code": null,
"e": 2042,
"s": 2039,
"text": "C#"
}
] |
Flatten a Matrix in Python using NumPy
|
29 Aug, 2020
Let’s discuss how to flatten a Matrix using NumPy in Python. By using ndarray.flatten() function we can flatten a matrix to one dimension in python.
Syntax:numpy_array.flatten(order=’C’)
order:‘C’ means to flatten in row-major.’F’ means to flatten in column-major.’A’ means to flatten in column-major order if a is Fortran contiguous in memory, row-major order otherwise.’K’ means to flatten a in the order the elements occur in memory. The default is ‘C’.
Return:Flattened 1-D matrix
Example 1:
python3
# importing numpy as npimport numpy as np # declare matrix with npgfg = np.array([[2, 3], [4, 5]]) # using array.flatten() methodflat_gfg = gfg.flatten()print(flat_gfg)
Output:
[2 3 4 5]
Example 2:
python3
# importing numpy as npimport numpy as np # declare matrix with npgfg = np.array([[6, 9], [8, 5], [18, 21]]) # using array.flatten() methodgfg.flatten()
Output:
array([ 6, 9, 8, 5, 18, 21])
Example 3:
python3
# importing numpy as npimport numpy as np # declare matrix with npgfg = np.array([[6, 9, 12], [8, 5, 2], [18, 21, 24]]) # using array.flatten() methodflat_gfg = gfg.flatten(order='A')print(flat_gfg)
Output:
[ 6, 9, 12, 8, 5, 2, 18, 21, 24]
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Aug, 2020"
},
{
"code": null,
"e": 177,
"s": 28,
"text": "Let’s discuss how to flatten a Matrix using NumPy in Python. By using ndarray.flatten() function we can flatten a matrix to one dimension in python."
},
{
"code": null,
"e": 215,
"s": 177,
"text": "Syntax:numpy_array.flatten(order=’C’)"
},
{
"code": null,
"e": 485,
"s": 215,
"text": "order:‘C’ means to flatten in row-major.’F’ means to flatten in column-major.’A’ means to flatten in column-major order if a is Fortran contiguous in memory, row-major order otherwise.’K’ means to flatten a in the order the elements occur in memory. The default is ‘C’."
},
{
"code": null,
"e": 513,
"s": 485,
"text": "Return:Flattened 1-D matrix"
},
{
"code": null,
"e": 524,
"s": 513,
"text": "Example 1:"
},
{
"code": null,
"e": 532,
"s": 524,
"text": "python3"
},
{
"code": "# importing numpy as npimport numpy as np # declare matrix with npgfg = np.array([[2, 3], [4, 5]]) # using array.flatten() methodflat_gfg = gfg.flatten()print(flat_gfg)",
"e": 703,
"s": 532,
"text": null
},
{
"code": null,
"e": 711,
"s": 703,
"text": "Output:"
},
{
"code": null,
"e": 722,
"s": 711,
"text": "[2 3 4 5]\n"
},
{
"code": null,
"e": 733,
"s": 722,
"text": "Example 2:"
},
{
"code": null,
"e": 741,
"s": 733,
"text": "python3"
},
{
"code": "# importing numpy as npimport numpy as np # declare matrix with npgfg = np.array([[6, 9], [8, 5], [18, 21]]) # using array.flatten() methodgfg.flatten()",
"e": 896,
"s": 741,
"text": null
},
{
"code": null,
"e": 904,
"s": 896,
"text": "Output:"
},
{
"code": null,
"e": 937,
"s": 904,
"text": "array([ 6, 9, 8, 5, 18, 21])\n"
},
{
"code": null,
"e": 948,
"s": 937,
"text": "Example 3:"
},
{
"code": null,
"e": 956,
"s": 948,
"text": "python3"
},
{
"code": "# importing numpy as npimport numpy as np # declare matrix with npgfg = np.array([[6, 9, 12], [8, 5, 2], [18, 21, 24]]) # using array.flatten() methodflat_gfg = gfg.flatten(order='A')print(flat_gfg)",
"e": 1157,
"s": 956,
"text": null
},
{
"code": null,
"e": 1165,
"s": 1157,
"text": "Output:"
},
{
"code": null,
"e": 1203,
"s": 1165,
"text": "[ 6, 9, 12, 8, 5, 2, 18, 21, 24]\n"
},
{
"code": null,
"e": 1234,
"s": 1203,
"text": "Python numpy-arrayManipulation"
},
{
"code": null,
"e": 1247,
"s": 1234,
"text": "Python-numpy"
},
{
"code": null,
"e": 1254,
"s": 1247,
"text": "Python"
}
] |
Python Program to Get total Business days between two dates
|
18 Jul, 2021
Given two dates, our task is to write a Python program to get total business days, i.e weekdays between the two dates.
Example:
Input : test_date1, test_date2 = datetime(2015, 6, 3), datetime(2015, 7, 1)
Output : 20
Explanation : Total weekdays, i.e business days are 20 in span.
Input : test_date1, test_date2 = datetime(2015, 6, 3), datetime(2016, 7, 1)
Output : 282
Explanation : Total weekdays, i.e business days are 282 in span.
Method 1: Using timedelta() + sum() + weekday()
In this, all the dates are extracted using timedelta(), by incrementing differences till the end date. Post that, business days are filtered using weekday(), summing all which has a value less than 5. i.e Mon – Fri.
Python3
# Python3 code to demonstrate working of# Business days in range# Using timedelta() + sum() + weekday()from datetime import datetime, timedelta # initializing dates rangestest_date1, test_date2 = datetime(2015, 6, 3), datetime(2015, 7, 1) # printing datesprint("The original range : " + str(test_date1) + " " + str(test_date2)) # generating datesdates = (test_date1 + timedelta(idx + 1) for idx in range((test_date2 - test_date1).days)) # summing all weekdaysres = sum(1 for day in dates if day.weekday() < 5) # printingprint("Total business days in range : " + str(res))
Output:
The original range : 2015-06-03 00:00:00 2015-07-01 00:00:00
Total business days in range : 20
Method #2 : Using np.busday_count()
This is inbuilt function that can be used to directly employ to solve this task.
Python3
# Python3 code to demonstrate working of# Business days in range# Using np.busday_countfrom datetime import datetime, timedeltaimport numpy as np # initializing dates ranges test_date1, test_date2 = datetime(2015, 6, 3), datetime(2015, 7, 1) # printing dates print("The original range : " + str(test_date1) + " " + str(test_date2)) # generating total days using busday_count()res = np.busday_count(test_date1.strftime('%Y-%m-%d'), test_date2.strftime('%Y-%m-%d')) # printing print("Total business days in range : " + str(res))
Output:
The original range : 2015-06-03 00:00:00 2015-07-01 00:00:00
Total business days in range : 20
Method #3 : Using pandas.bdate_range()
This is another inbuilt function that can be used to directly employ to solve this task. Returns total business dates list inclusive of the start and end date.
Python3
# Python3 code to demonstrate working of# Business days in range# Using pd.bdate_rangefrom datetime import datetimeimport pandas as pd # initializing dates rangestest_date1, test_date2 = datetime(2015, 6, 3), datetime(2015, 6, 30) # printing datesprint("The original range : " + str(test_date1) + " " + str(test_date2)) # generating total days using pd.bdate_range()# len() gets the number of days# includes both last and first date.res = len(pd.bdate_range(test_date1.strftime('%Y-%m-%d'), test_date2.strftime('%Y-%m-%d'))) # printing resultprint("Total business days in range : " + str(res))
Output :
The original range : 2015-06-03 00:00:00 2015-06-30 00:00:00
Total business days in range : 20
Python datetime-program
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jul, 2021"
},
{
"code": null,
"e": 147,
"s": 28,
"text": "Given two dates, our task is to write a Python program to get total business days, i.e weekdays between the two dates."
},
{
"code": null,
"e": 156,
"s": 147,
"text": "Example:"
},
{
"code": null,
"e": 232,
"s": 156,
"text": "Input : test_date1, test_date2 = datetime(2015, 6, 3), datetime(2015, 7, 1)"
},
{
"code": null,
"e": 244,
"s": 232,
"text": "Output : 20"
},
{
"code": null,
"e": 308,
"s": 244,
"text": "Explanation : Total weekdays, i.e business days are 20 in span."
},
{
"code": null,
"e": 384,
"s": 308,
"text": "Input : test_date1, test_date2 = datetime(2015, 6, 3), datetime(2016, 7, 1)"
},
{
"code": null,
"e": 397,
"s": 384,
"text": "Output : 282"
},
{
"code": null,
"e": 462,
"s": 397,
"text": "Explanation : Total weekdays, i.e business days are 282 in span."
},
{
"code": null,
"e": 510,
"s": 462,
"text": "Method 1: Using timedelta() + sum() + weekday()"
},
{
"code": null,
"e": 726,
"s": 510,
"text": "In this, all the dates are extracted using timedelta(), by incrementing differences till the end date. Post that, business days are filtered using weekday(), summing all which has a value less than 5. i.e Mon – Fri."
},
{
"code": null,
"e": 734,
"s": 726,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Business days in range# Using timedelta() + sum() + weekday()from datetime import datetime, timedelta # initializing dates rangestest_date1, test_date2 = datetime(2015, 6, 3), datetime(2015, 7, 1) # printing datesprint(\"The original range : \" + str(test_date1) + \" \" + str(test_date2)) # generating datesdates = (test_date1 + timedelta(idx + 1) for idx in range((test_date2 - test_date1).days)) # summing all weekdaysres = sum(1 for day in dates if day.weekday() < 5) # printingprint(\"Total business days in range : \" + str(res))",
"e": 1319,
"s": 734,
"text": null
},
{
"code": null,
"e": 1327,
"s": 1319,
"text": "Output:"
},
{
"code": null,
"e": 1422,
"s": 1327,
"text": "The original range : 2015-06-03 00:00:00 2015-07-01 00:00:00\nTotal business days in range : 20"
},
{
"code": null,
"e": 1458,
"s": 1422,
"text": "Method #2 : Using np.busday_count()"
},
{
"code": null,
"e": 1539,
"s": 1458,
"text": "This is inbuilt function that can be used to directly employ to solve this task."
},
{
"code": null,
"e": 1547,
"s": 1539,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Business days in range# Using np.busday_countfrom datetime import datetime, timedeltaimport numpy as np # initializing dates ranges test_date1, test_date2 = datetime(2015, 6, 3), datetime(2015, 7, 1) # printing dates print(\"The original range : \" + str(test_date1) + \" \" + str(test_date2)) # generating total days using busday_count()res = np.busday_count(test_date1.strftime('%Y-%m-%d'), test_date2.strftime('%Y-%m-%d')) # printing print(\"Total business days in range : \" + str(res))",
"e": 2099,
"s": 1547,
"text": null
},
{
"code": null,
"e": 2107,
"s": 2099,
"text": "Output:"
},
{
"code": null,
"e": 2202,
"s": 2107,
"text": "The original range : 2015-06-03 00:00:00 2015-07-01 00:00:00\nTotal business days in range : 20"
},
{
"code": null,
"e": 2241,
"s": 2202,
"text": "Method #3 : Using pandas.bdate_range()"
},
{
"code": null,
"e": 2402,
"s": 2241,
"text": "This is another inbuilt function that can be used to directly employ to solve this task. Returns total business dates list inclusive of the start and end date. "
},
{
"code": null,
"e": 2410,
"s": 2402,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Business days in range# Using pd.bdate_rangefrom datetime import datetimeimport pandas as pd # initializing dates rangestest_date1, test_date2 = datetime(2015, 6, 3), datetime(2015, 6, 30) # printing datesprint(\"The original range : \" + str(test_date1) + \" \" + str(test_date2)) # generating total days using pd.bdate_range()# len() gets the number of days# includes both last and first date.res = len(pd.bdate_range(test_date1.strftime('%Y-%m-%d'), test_date2.strftime('%Y-%m-%d'))) # printing resultprint(\"Total business days in range : \" + str(res))",
"e": 3032,
"s": 2410,
"text": null
},
{
"code": null,
"e": 3042,
"s": 3032,
"text": "Output : "
},
{
"code": null,
"e": 3137,
"s": 3042,
"text": "The original range : 2015-06-03 00:00:00 2015-06-30 00:00:00\nTotal business days in range : 20"
},
{
"code": null,
"e": 3161,
"s": 3137,
"text": "Python datetime-program"
},
{
"code": null,
"e": 3168,
"s": 3161,
"text": "Python"
},
{
"code": null,
"e": 3184,
"s": 3168,
"text": "Python Programs"
},
{
"code": null,
"e": 3282,
"s": 3184,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3314,
"s": 3282,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3341,
"s": 3314,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3362,
"s": 3341,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3385,
"s": 3362,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3416,
"s": 3385,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3438,
"s": 3416,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 3477,
"s": 3438,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 3515,
"s": 3477,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 3552,
"s": 3515,
"text": "Python Program for Fibonacci numbers"
}
] |
Joining NumPy Array
|
01 Oct, 2020
NumPy provides various functions to combine arrays. In this article, we will discuss some of the major ones.
numpy.concatenate
numpy.stack
numpy.block
Method 1: Using numpy.concatenate()
The concatenate function in NumPy joins two or more arrays along a specified axis.
Syntax:
numpy.concatenate((array1, array2, ...), axis=0)
The first argument is a tuple of arrays we intend to join and the second argument is the axis along which we need to join these arrays. Check out the following example showing the use of numpy.concatenate.
Python3
import numpy as np array_1 = np.array([1, 2])array_2 = np.array([3, 4]) array_new = np.concatenate((array_1, array_2))print(array_new)
Output:
[1 2 4 5]
By default, the value of the axis is set to 0. You can change it by specifying a value for the axis in the second argument. The following code joins two arrays along rows.
Python3
import numpy as np array_1 = np.array([[1, 2], [3, 4]])array_2 = np.array([[5, 6], [7, 8]]) array_new = np.concatenate((array_1, array_2), axis=1)print(array_new)
Output:
[[1 2 5 6]
[3 4 7 8]]
Method 2: Using numpy.stack()
The stack() function of NumPy joins two or more arrays along a new axis.
Syntax:
numpy.stack(arrays, axis=0)
The following code demonstrates the use of numpy.stack().
Python3
import numpy as np array_1 = np.array([1, 2, 3, 4])array_2 = np.array([5, 6, 7, 8]) array_new = np.stack((array_1, array_2), axis=1)print(array_new)
Output:
[[1 5]
[2 6]
[3 7]
[4 8]]
The arrays are joined along a new axis.
Method 3: numpy.block()
numpy.block is used to create nd-arrays from nested blocks of lists.
Syntax:
numpy.block(arrays)
The following example explains the working of numpy.block().
Python3
import numpy as np block_1 = np.array([[1, 1], [1, 1]])block_2 = np.array([[2, 2, 2], [2, 2, 2]])block_3 = np.array([[3, 3], [3, 3], [3, 3]])block_4 = np.array([[4, 4, 4], [4, 4, 4], [4, 4, 4]]) block_new = np.block([ [block_1, block_2], [block_3, block_4]]) print(block_new)
Output:
[[1 1 2 2 2]
[1 1 2 2 2]
[3 3 4 4 4]
[3 3 4 4 4]
[3 3 4 4 4]]
In this example, we assembled a block matrix( block_new ) from 4 separate 2-d arrays (block_1,block_2,block_3,block_4 ).
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Oct, 2020"
},
{
"code": null,
"e": 161,
"s": 52,
"text": "NumPy provides various functions to combine arrays. In this article, we will discuss some of the major ones."
},
{
"code": null,
"e": 179,
"s": 161,
"text": "numpy.concatenate"
},
{
"code": null,
"e": 191,
"s": 179,
"text": "numpy.stack"
},
{
"code": null,
"e": 203,
"s": 191,
"text": "numpy.block"
},
{
"code": null,
"e": 239,
"s": 203,
"text": "Method 1: Using numpy.concatenate()"
},
{
"code": null,
"e": 323,
"s": 239,
"text": "The concatenate function in NumPy joins two or more arrays along a specified axis. "
},
{
"code": null,
"e": 331,
"s": 323,
"text": "Syntax:"
},
{
"code": null,
"e": 381,
"s": 331,
"text": "numpy.concatenate((array1, array2, ...), axis=0)\n"
},
{
"code": null,
"e": 587,
"s": 381,
"text": "The first argument is a tuple of arrays we intend to join and the second argument is the axis along which we need to join these arrays. Check out the following example showing the use of numpy.concatenate."
},
{
"code": null,
"e": 595,
"s": 587,
"text": "Python3"
},
{
"code": "import numpy as np array_1 = np.array([1, 2])array_2 = np.array([3, 4]) array_new = np.concatenate((array_1, array_2))print(array_new)",
"e": 732,
"s": 595,
"text": null
},
{
"code": null,
"e": 741,
"s": 732,
"text": "Output: "
},
{
"code": null,
"e": 752,
"s": 741,
"text": "[1 2 4 5]\n"
},
{
"code": null,
"e": 924,
"s": 752,
"text": "By default, the value of the axis is set to 0. You can change it by specifying a value for the axis in the second argument. The following code joins two arrays along rows."
},
{
"code": null,
"e": 932,
"s": 924,
"text": "Python3"
},
{
"code": "import numpy as np array_1 = np.array([[1, 2], [3, 4]])array_2 = np.array([[5, 6], [7, 8]]) array_new = np.concatenate((array_1, array_2), axis=1)print(array_new)",
"e": 1097,
"s": 932,
"text": null
},
{
"code": null,
"e": 1105,
"s": 1097,
"text": "Output:"
},
{
"code": null,
"e": 1129,
"s": 1105,
"text": "[[1 2 5 6]\n [3 4 7 8]]\n"
},
{
"code": null,
"e": 1159,
"s": 1129,
"text": "Method 2: Using numpy.stack()"
},
{
"code": null,
"e": 1232,
"s": 1159,
"text": "The stack() function of NumPy joins two or more arrays along a new axis."
},
{
"code": null,
"e": 1240,
"s": 1232,
"text": "Syntax:"
},
{
"code": null,
"e": 1269,
"s": 1240,
"text": "numpy.stack(arrays, axis=0)\n"
},
{
"code": null,
"e": 1327,
"s": 1269,
"text": "The following code demonstrates the use of numpy.stack()."
},
{
"code": null,
"e": 1335,
"s": 1327,
"text": "Python3"
},
{
"code": "import numpy as np array_1 = np.array([1, 2, 3, 4])array_2 = np.array([5, 6, 7, 8]) array_new = np.stack((array_1, array_2), axis=1)print(array_new)",
"e": 1486,
"s": 1335,
"text": null
},
{
"code": null,
"e": 1494,
"s": 1486,
"text": "Output:"
},
{
"code": null,
"e": 1524,
"s": 1494,
"text": "[[1 5]\n [2 6]\n [3 7]\n [4 8]]\n"
},
{
"code": null,
"e": 1564,
"s": 1524,
"text": "The arrays are joined along a new axis."
},
{
"code": null,
"e": 1588,
"s": 1564,
"text": "Method 3: numpy.block()"
},
{
"code": null,
"e": 1657,
"s": 1588,
"text": "numpy.block is used to create nd-arrays from nested blocks of lists."
},
{
"code": null,
"e": 1665,
"s": 1657,
"text": "Syntax:"
},
{
"code": null,
"e": 1686,
"s": 1665,
"text": "numpy.block(arrays)\n"
},
{
"code": null,
"e": 1747,
"s": 1686,
"text": "The following example explains the working of numpy.block()."
},
{
"code": null,
"e": 1755,
"s": 1747,
"text": "Python3"
},
{
"code": "import numpy as np block_1 = np.array([[1, 1], [1, 1]])block_2 = np.array([[2, 2, 2], [2, 2, 2]])block_3 = np.array([[3, 3], [3, 3], [3, 3]])block_4 = np.array([[4, 4, 4], [4, 4, 4], [4, 4, 4]]) block_new = np.block([ [block_1, block_2], [block_3, block_4]]) print(block_new)",
"e": 2040,
"s": 1755,
"text": null
},
{
"code": null,
"e": 2048,
"s": 2040,
"text": "Output:"
},
{
"code": null,
"e": 2115,
"s": 2048,
"text": "[[1 1 2 2 2]\n [1 1 2 2 2]\n [3 3 4 4 4]\n [3 3 4 4 4]\n [3 3 4 4 4]]\n"
},
{
"code": null,
"e": 2236,
"s": 2115,
"text": "In this example, we assembled a block matrix( block_new ) from 4 separate 2-d arrays (block_1,block_2,block_3,block_4 )."
},
{
"code": null,
"e": 2267,
"s": 2236,
"text": "Python numpy-arrayManipulation"
},
{
"code": null,
"e": 2280,
"s": 2267,
"text": "Python-numpy"
},
{
"code": null,
"e": 2287,
"s": 2280,
"text": "Python"
}
] |
Python | Filter even values from a list
|
14 Feb, 2019
Given a list of numbers, the task is to make a new list containing only even values.
Examples:
Input: list = [1, 2, 3, 4, 5]
Output: [2, 4]
Input: list = [12, 14, 95, 3]
Output: [12, 14]
Method #1 : Using For loopIterate each element in the list using for loop and check if num % 2 == 0. If the condition satisfies, then append it in output list.
# Python code to filter even values from a list # Initialisation of listlis = [1,2,3,4,5] # Output list initialisationout = [] for num in lis: # checking condition if num % 2 == 0: out.append(num) # printing outputprint(out)
[2, 4]
Method #2 : Using While loop
# Python code to filter even values from a list # Initialisation of listlis = [1,2,3,4,5]num = 0 # Output list initialisationout = []while(num < len(lis)): # checking condition if lis[num] % 2 == 0: out.append(lis[num]) # increment num num += 1 # printing outputprint(out)
[2, 4]
Method #3 : Using list Comprehension
# Python code to filter even values from a list # Initialisation of listlis = [1,2,3,4,5] lis2 = [i for i in lis if i%2 == 0] # Printing outputprint(lis2)
[2, 4]
Method #4 : Using filter()
# Python code to filter even values from a list # Initialisation of listlis1 = [1,2,3,4,5] is_even = lambda x: x % 2 == 0 # using filterlis2 = list(filter(is_even, lis1)) # Printing outputprint(lis2)
[2, 4]
Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Feb, 2019"
},
{
"code": null,
"e": 113,
"s": 28,
"text": "Given a list of numbers, the task is to make a new list containing only even values."
},
{
"code": null,
"e": 123,
"s": 113,
"text": "Examples:"
},
{
"code": null,
"e": 217,
"s": 123,
"text": "Input: list = [1, 2, 3, 4, 5]\nOutput: [2, 4]\n\nInput: list = [12, 14, 95, 3]\nOutput: [12, 14]\n"
},
{
"code": null,
"e": 378,
"s": 217,
"text": " Method #1 : Using For loopIterate each element in the list using for loop and check if num % 2 == 0. If the condition satisfies, then append it in output list."
},
{
"code": "# Python code to filter even values from a list # Initialisation of listlis = [1,2,3,4,5] # Output list initialisationout = [] for num in lis: # checking condition if num % 2 == 0: out.append(num) # printing outputprint(out)",
"e": 639,
"s": 378,
"text": null
},
{
"code": null,
"e": 647,
"s": 639,
"text": "[2, 4]\n"
},
{
"code": null,
"e": 677,
"s": 647,
"text": " Method #2 : Using While loop"
},
{
"code": "# Python code to filter even values from a list # Initialisation of listlis = [1,2,3,4,5]num = 0 # Output list initialisationout = []while(num < len(lis)): # checking condition if lis[num] % 2 == 0: out.append(lis[num]) # increment num num += 1 # printing outputprint(out)",
"e": 984,
"s": 677,
"text": null
},
{
"code": null,
"e": 992,
"s": 984,
"text": "[2, 4]\n"
},
{
"code": null,
"e": 1030,
"s": 992,
"text": " Method #3 : Using list Comprehension"
},
{
"code": "# Python code to filter even values from a list # Initialisation of listlis = [1,2,3,4,5] lis2 = [i for i in lis if i%2 == 0] # Printing outputprint(lis2)",
"e": 1188,
"s": 1030,
"text": null
},
{
"code": null,
"e": 1196,
"s": 1188,
"text": "[2, 4]\n"
},
{
"code": null,
"e": 1224,
"s": 1196,
"text": " Method #4 : Using filter()"
},
{
"code": "# Python code to filter even values from a list # Initialisation of listlis1 = [1,2,3,4,5] is_even = lambda x: x % 2 == 0 # using filterlis2 = list(filter(is_even, lis1)) # Printing outputprint(lis2)",
"e": 1428,
"s": 1224,
"text": null
},
{
"code": null,
"e": 1436,
"s": 1428,
"text": "[2, 4]\n"
},
{
"code": null,
"e": 1457,
"s": 1436,
"text": "Python list-programs"
},
{
"code": null,
"e": 1469,
"s": 1457,
"text": "python-list"
},
{
"code": null,
"e": 1476,
"s": 1469,
"text": "Python"
},
{
"code": null,
"e": 1488,
"s": 1476,
"text": "python-list"
}
] |
Longest Subarray of non-negative Integers
|
22 Jun, 2022
Given an array, return the length of the longest subarray of non-negative integersExamples :
Input : {2, 3, 4, -1, -2, 1, 5, 6, 3}
Output : 4
The subarray [ 1, 5, 6, 3] has length 4 and
contains no negative integers
Input : {1, 0, 0, 1, -1, -1, 0, 0, 1, 0}
Output : 4
Subarrays [1, 0, 0, 1] and [0, 0, 1, 0] have
equal lengths but sum of first one is greater
so that will be the output.
Naive Approach: The idea is to use two nested loops, one for choosing starting index of a valid subarray (where all elements are positive) and the other for finding the ending index of a valid subarray. Keep updating the result if we find any longer valid subarray.
Below is the implementation of the above approach
Java
// Longest Subarray of non-negative Integersimport java.io.*; class GFG { public static int longestSubarray(int[] A) { int n = A.length; int result = 0; // Iterating the array for choosing starting index // of required subarray for (int i = 0; i < n; i++) { if (A[i] < 0) continue; // Checking if the element is positive or // negative int j = i; for (; j < n; j++) { // if the element is negative if (A[j] < 0) { --j; break; } } // Finding the max length of the subarray if (j - i + 1 > result) { result = j - i + 1; } } return result; } // Driver code public static void main(String[] args) { int arr[] = { 1, 0, 4, 0, 1, -1, -1, 0, 0, 1, 0 }; int n = arr.length; System.out.println(longestSubarray(arr)); }}
5
Time Complexity: O(N2), Where N is the length of the given arrayAuxiliary Space: O(1)
Efficient Approach: We follow a simple two-pointer window approach. Initially start index points to the starting of curr subarray i.e. a non-negative integer and traverses the array. Whenever a negative element occurs we compare it with the length of the max subarray so far and update the start and size if curr length is greater. finally, we return the subarray starting at the start of length size with the first element as the size of the subarray.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find length of the longest// subarray with non-negative numbers.#include<iostream>using namespace std; // Function that returns the longest// subarray of non-negative integersint longestSubarry(int *arr, int n){ // Initialize result int res = 0; // Traverse array for (int i = 0; i < n; i++) { // Count of current // non-negative integers int curr_count = 0; while (i < n && arr[i] >= 0) { curr_count++; i++; } // Update result if required. res = max(res, curr_count); } return res;} // Driver codeint main(){ int arr[] = {1, 0, 4, 0, 1, -1, -1, 0, 0, 1, 0}; int n = sizeof(arr) / sizeof(arr[0]); cout << longestSubarry(arr, n); return 0;}
// Java program to find length of the longest// subarray with non-negative numbers. class GFG{ // Function that returns the longest // subarray of non-negative integers static int longestSubarry(int arr[], int n) { // Initialize result int res = 0; // Traverse array for (int i = 0; i < n; i++) { // Count of current non- // negative integers int curr_count = 0; while (i < n && arr[i] >= 0) { curr_count++; i++; } // Update result if required. res = Math.max(res, curr_count); } return res; } // Driver code public static void main(String[] args) { int arr[] = {1, 0, 4, 0, 1, -1, -1, 0, 0, 1, 0}; int n = arr.length; System.out.println(longestSubarry(arr, n)); }} // This code is contributed by prerna saini.
# Python program to find# length of the longest# subarray with# non-negative numbers. # Function that returns# the longest subarray# of non-negative integersdef longestSubarry(arr,n): # Initialize result res = 0 # Traverse array for i in range(n): # Count of current # non-negative integers curr_count = 0 while (i < n and arr[i] >= 0): curr_count+=1 i+=1 # Update result if required. res = max(res, curr_count) return res # Driver code arr= [1, 0, 4, 0, 1, -1, -1, 0, 0, 1, 0]n = len(arr)print(longestSubarry(arr, n)) # This code is contributed# by Anant Agarwal.
// C# program to find length of the longest// subarray with non-negative numbers.using System; class GFG{ // Function that returns the longest // subarray of non-negative integers static int longestSubarry(int []arr, int n) { // Initialize result int res = 0; // Traverse array for (int i = 0; i < n; i++) { // Count of current non- // negative integers int curr_count = 0; while (i < n && arr[i] >= 0) { curr_count++; i++; } // Update result if required. res = Math.Max(res, curr_count); } return res; } // Driver code public static void Main() { int []arr = {1, 0, 4, 0, 1, -1, -1, 0, 0, 1, 0}; int n = arr.Length; Console.Write(longestSubarry(arr, n)); }} // This code is contributed by nitin mittal
<?php// PHP program to find length// of the longest subarray with// non-negative numbers. // Function that returns the longest// subarray of non-negative integersfunction longestSubarry($arr, $n){ // Initialize result $res = 0; // Traverse array for ($i = 0; $i < $n; $i++) { // Count of current // non-negative integers $curr_count = 0; while ($i < $n && $arr[$i] >= 0) { $curr_count++; $i++; } // Update result if required. $res = max($res, $curr_count); } return $res;} // Driver code$arr = array(1, 0, 4, 0, 1, -1, -1, 0, 0, 1, 0);$n = sizeof($arr) / sizeof($arr[0]);echo longestSubarry($arr, $n); // This code is contributed by nitin mittal.?>
<script> // JavaScript program for the above approach // Function that returns the longest// subarray of non-negative integersfunction longestSubarry(arr, n){ // Initialize result let res = 0; // Traverse array for (let i = 0; i < n; i++) { // Count of current // non-negative integers let curr_count = 0; while (i < n && arr[i] >= 0) { curr_count++; i++; } // Update result if required. res = Math.max(res, curr_count); } return res;} // Driver code var arr = [1, 0, 4, 0, 1, -1, -1, 0, 0, 1, 0]; let n = arr.length; document.write(longestSubarry(arr, n)); // This code is contributed by Potta Lokesh </script>
5
Time Complexity: O(N), Where N is the length of the given arrayAuxiliary Space: O(1)
Exercise : Modify the above solution to print the result subarray. Also, in case two subarrays have the same count, print the subarray with a larger sum.This article is contributed by Aditi Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
nitin mittal
lokeshpotta20
akd3257
Arrays
School Programming
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Python Dictionary
Reverse a string in Java
Introduction To PYTHON
Interfaces in Java
Inheritance in C++
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 146,
"s": 52,
"text": "Given an array, return the length of the longest subarray of non-negative integersExamples : "
},
{
"code": null,
"e": 445,
"s": 146,
"text": "Input : {2, 3, 4, -1, -2, 1, 5, 6, 3}\nOutput : 4\n\nThe subarray [ 1, 5, 6, 3] has length 4 and \ncontains no negative integers\n\nInput : {1, 0, 0, 1, -1, -1, 0, 0, 1, 0}\nOutput : 4\n\nSubarrays [1, 0, 0, 1] and [0, 0, 1, 0] have \nequal lengths but sum of first one is greater\nso that will be the output."
},
{
"code": null,
"e": 711,
"s": 445,
"text": "Naive Approach: The idea is to use two nested loops, one for choosing starting index of a valid subarray (where all elements are positive) and the other for finding the ending index of a valid subarray. Keep updating the result if we find any longer valid subarray."
},
{
"code": null,
"e": 761,
"s": 711,
"text": "Below is the implementation of the above approach"
},
{
"code": null,
"e": 766,
"s": 761,
"text": "Java"
},
{
"code": "// Longest Subarray of non-negative Integersimport java.io.*; class GFG { public static int longestSubarray(int[] A) { int n = A.length; int result = 0; // Iterating the array for choosing starting index // of required subarray for (int i = 0; i < n; i++) { if (A[i] < 0) continue; // Checking if the element is positive or // negative int j = i; for (; j < n; j++) { // if the element is negative if (A[j] < 0) { --j; break; } } // Finding the max length of the subarray if (j - i + 1 > result) { result = j - i + 1; } } return result; } // Driver code public static void main(String[] args) { int arr[] = { 1, 0, 4, 0, 1, -1, -1, 0, 0, 1, 0 }; int n = arr.length; System.out.println(longestSubarray(arr)); }}",
"e": 1795,
"s": 766,
"text": null
},
{
"code": null,
"e": 1798,
"s": 1795,
"text": "5\n"
},
{
"code": null,
"e": 1884,
"s": 1798,
"text": "Time Complexity: O(N2), Where N is the length of the given arrayAuxiliary Space: O(1)"
},
{
"code": null,
"e": 2338,
"s": 1884,
"text": "Efficient Approach: We follow a simple two-pointer window approach. Initially start index points to the starting of curr subarray i.e. a non-negative integer and traverses the array. Whenever a negative element occurs we compare it with the length of the max subarray so far and update the start and size if curr length is greater. finally, we return the subarray starting at the start of length size with the first element as the size of the subarray. "
},
{
"code": null,
"e": 2342,
"s": 2338,
"text": "C++"
},
{
"code": null,
"e": 2347,
"s": 2342,
"text": "Java"
},
{
"code": null,
"e": 2355,
"s": 2347,
"text": "Python3"
},
{
"code": null,
"e": 2358,
"s": 2355,
"text": "C#"
},
{
"code": null,
"e": 2362,
"s": 2358,
"text": "PHP"
},
{
"code": null,
"e": 2373,
"s": 2362,
"text": "Javascript"
},
{
"code": "// C++ program to find length of the longest// subarray with non-negative numbers.#include<iostream>using namespace std; // Function that returns the longest// subarray of non-negative integersint longestSubarry(int *arr, int n){ // Initialize result int res = 0; // Traverse array for (int i = 0; i < n; i++) { // Count of current // non-negative integers int curr_count = 0; while (i < n && arr[i] >= 0) { curr_count++; i++; } // Update result if required. res = max(res, curr_count); } return res;} // Driver codeint main(){ int arr[] = {1, 0, 4, 0, 1, -1, -1, 0, 0, 1, 0}; int n = sizeof(arr) / sizeof(arr[0]); cout << longestSubarry(arr, n); return 0;}",
"e": 3192,
"s": 2373,
"text": null
},
{
"code": "// Java program to find length of the longest// subarray with non-negative numbers. class GFG{ // Function that returns the longest // subarray of non-negative integers static int longestSubarry(int arr[], int n) { // Initialize result int res = 0; // Traverse array for (int i = 0; i < n; i++) { // Count of current non- // negative integers int curr_count = 0; while (i < n && arr[i] >= 0) { curr_count++; i++; } // Update result if required. res = Math.max(res, curr_count); } return res; } // Driver code public static void main(String[] args) { int arr[] = {1, 0, 4, 0, 1, -1, -1, 0, 0, 1, 0}; int n = arr.length; System.out.println(longestSubarry(arr, n)); }} // This code is contributed by prerna saini.",
"e": 4174,
"s": 3192,
"text": null
},
{
"code": "# Python program to find# length of the longest# subarray with# non-negative numbers. # Function that returns# the longest subarray# of non-negative integersdef longestSubarry(arr,n): # Initialize result res = 0 # Traverse array for i in range(n): # Count of current # non-negative integers curr_count = 0 while (i < n and arr[i] >= 0): curr_count+=1 i+=1 # Update result if required. res = max(res, curr_count) return res # Driver code arr= [1, 0, 4, 0, 1, -1, -1, 0, 0, 1, 0]n = len(arr)print(longestSubarry(arr, n)) # This code is contributed# by Anant Agarwal.",
"e": 4841,
"s": 4174,
"text": null
},
{
"code": "// C# program to find length of the longest// subarray with non-negative numbers.using System; class GFG{ // Function that returns the longest // subarray of non-negative integers static int longestSubarry(int []arr, int n) { // Initialize result int res = 0; // Traverse array for (int i = 0; i < n; i++) { // Count of current non- // negative integers int curr_count = 0; while (i < n && arr[i] >= 0) { curr_count++; i++; } // Update result if required. res = Math.Max(res, curr_count); } return res; } // Driver code public static void Main() { int []arr = {1, 0, 4, 0, 1, -1, -1, 0, 0, 1, 0}; int n = arr.Length; Console.Write(longestSubarry(arr, n)); }} // This code is contributed by nitin mittal",
"e": 5815,
"s": 4841,
"text": null
},
{
"code": "<?php// PHP program to find length// of the longest subarray with// non-negative numbers. // Function that returns the longest// subarray of non-negative integersfunction longestSubarry($arr, $n){ // Initialize result $res = 0; // Traverse array for ($i = 0; $i < $n; $i++) { // Count of current // non-negative integers $curr_count = 0; while ($i < $n && $arr[$i] >= 0) { $curr_count++; $i++; } // Update result if required. $res = max($res, $curr_count); } return $res;} // Driver code$arr = array(1, 0, 4, 0, 1, -1, -1, 0, 0, 1, 0);$n = sizeof($arr) / sizeof($arr[0]);echo longestSubarry($arr, $n); // This code is contributed by nitin mittal.?>",
"e": 6598,
"s": 5815,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function that returns the longest// subarray of non-negative integersfunction longestSubarry(arr, n){ // Initialize result let res = 0; // Traverse array for (let i = 0; i < n; i++) { // Count of current // non-negative integers let curr_count = 0; while (i < n && arr[i] >= 0) { curr_count++; i++; } // Update result if required. res = Math.max(res, curr_count); } return res;} // Driver code var arr = [1, 0, 4, 0, 1, -1, -1, 0, 0, 1, 0]; let n = arr.length; document.write(longestSubarry(arr, n)); // This code is contributed by Potta Lokesh </script>",
"e": 7378,
"s": 6598,
"text": null
},
{
"code": null,
"e": 7380,
"s": 7378,
"text": "5"
},
{
"code": null,
"e": 7465,
"s": 7380,
"text": "Time Complexity: O(N), Where N is the length of the given arrayAuxiliary Space: O(1)"
},
{
"code": null,
"e": 8041,
"s": 7465,
"text": "Exercise : Modify the above solution to print the result subarray. Also, in case two subarrays have the same count, print the subarray with a larger sum.This article is contributed by Aditi Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 8054,
"s": 8041,
"text": "nitin mittal"
},
{
"code": null,
"e": 8068,
"s": 8054,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 8076,
"s": 8068,
"text": "akd3257"
},
{
"code": null,
"e": 8083,
"s": 8076,
"text": "Arrays"
},
{
"code": null,
"e": 8102,
"s": 8083,
"text": "School Programming"
},
{
"code": null,
"e": 8109,
"s": 8102,
"text": "Arrays"
},
{
"code": null,
"e": 8207,
"s": 8109,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8275,
"s": 8207,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 8319,
"s": 8275,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 8351,
"s": 8319,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 8399,
"s": 8351,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 8413,
"s": 8399,
"text": "Linear Search"
},
{
"code": null,
"e": 8431,
"s": 8413,
"text": "Python Dictionary"
},
{
"code": null,
"e": 8456,
"s": 8431,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 8479,
"s": 8456,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 8498,
"s": 8479,
"text": "Interfaces in Java"
}
] |
Getting started with OpenGL
|
29 Jun, 2022
Open Graphics Library (OpenGL) is a cross-language (language independent), cross-platform (platform-independent) API for rendering 2D and 3D Vector Graphics(use of polygons to represent image). OpenGL API is designed mostly in hardware.
Design : This API is defined as a set of functions which may be called by the client program. Although functions are similar to those of C language but it is language independent.
Development : It is an evolving API and Khronos Group regularly releases its new version having some extended feature compare to previous one. GPU vendors may also provide some additional functionality in the form of extension.
Associated Libraries : The earliest version is released with a companion library called OpenGL utility library. But since OpenGL is quite a complex process. So in order to make it easier other library such as OpenGL Utility Toolkit is added which is later superseded by free glut. Later included library were GLEE, GLEW, and gliding.
Implementation : Mesa 3D is an open source implementation of OpenGL. It can do pure software rendering and it may also use hardware acceleration on BSD, Linux, and other platforms by taking advantage of Direct Rendering Infrastructure.
Install OpenGL on UbuntuFor installing OpenGL on Ubuntu, just execute the following command (like installing any other thing) in terminal :
sudo apt-get install freeglut3-dev
For working on Ubuntu operating system:
gcc filename.c -lGL -lGLU -lglut
where filename.c is the name of the file
with which this program is saved.
Install OpenGL on windows in Code::Blocks
Download code block and install itGo to the link and download zip file from the download link that appears after freeglut MinGW package with having link name as Download freeglut 3.0.0 for MinGW and extract it.Open notepad with run as administrator and open file from This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > share > CodeBlocks > templates, (then click to show All Files)Next, open glut.cbp and search all glut32 and replace with freeglut.Then, open from This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > share > CodeBlocks > templates > wizard > glut (then click to show All Files)Open wizard.script and here, also replace all glut32 with freeglut Then go to freeglut folder (where it was downloaded) and Include > GL and copy all four file from thereGo to This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > MinGW > include > GL and paste it.Then, from download folder freeglut > lib, copy two files and go to This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > MinGW > lib and paste it.Again go to downloaded folder freeglut > bin and copy one file (freeglut.dll) from here and go to This PC > C:(C-drive) > Windows > SysWOW64 and paste this file.Now open Code::Blocks. Select File > New > Project > GLUT project > Next.Give project title anything and then choose Next.For selecting GLUT’s location : This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > MinGW.Press OK > Next > Finish.
Download code block and install it
Go to the link and download zip file from the download link that appears after freeglut MinGW package with having link name as Download freeglut 3.0.0 for MinGW and extract it.
Open notepad with run as administrator and open file from This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > share > CodeBlocks > templates, (then click to show All Files)Next, open glut.cbp and search all glut32 and replace with freeglut.Then, open from This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > share > CodeBlocks > templates > wizard > glut (then click to show All Files)Open wizard.script and here, also replace all glut32 with freeglut
This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > share > CodeBlocks > templates, (then click to show All Files)Next, open glut.cbp and search all glut32 and replace with freeglut.Then, open from This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > share > CodeBlocks > templates > wizard > glut (then click to show All Files)Open wizard.script and here, also replace all glut32 with freeglut
This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > share > CodeBlocks > templates, (then click to show All Files)
Next, open glut.cbp and search all glut32 and replace with freeglut.
Then, open from This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > share > CodeBlocks > templates > wizard > glut (then click to show All Files)
Open wizard.script and here, also replace all glut32 with freeglut
Then go to freeglut folder (where it was downloaded) and Include > GL and copy all four file from thereGo to This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > MinGW > include > GL and paste it.Then, from download folder freeglut > lib, copy two files and go to This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > MinGW > lib and paste it.Again go to downloaded folder freeglut > bin and copy one file (freeglut.dll) from here and go to This PC > C:(C-drive) > Windows > SysWOW64 and paste this file.
Include > GL and copy all four file from thereGo to This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > MinGW > include > GL and paste it.Then, from download folder freeglut > lib, copy two files and go to This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > MinGW > lib and paste it.Again go to downloaded folder freeglut > bin and copy one file (freeglut.dll) from here and go to This PC > C:(C-drive) > Windows > SysWOW64 and paste this file.
Include > GL and copy all four file from there
Go to This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > MinGW > include > GL and paste it.
Then, from download folder freeglut > lib, copy two files and go to This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > MinGW > lib and paste it.
Again go to downloaded folder freeglut > bin and copy one file (freeglut.dll) from here and go to This PC > C:(C-drive) > Windows > SysWOW64 and paste this file.
Now open Code::Blocks. Select File > New > Project > GLUT project > Next.Give project title anything and then choose Next.For selecting GLUT’s location : This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > MinGW.Press OK > Next > Finish.
Select File > New > Project > GLUT project > Next.Give project title anything and then choose Next.For selecting GLUT’s location : This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > MinGW.Press OK > Next > Finish.
Select File > New > Project > GLUT project > Next.
Give project title anything and then choose Next.
For selecting GLUT’s location : This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > MinGW.
Press OK > Next > Finish.
Now, Code::Blocks is ready to test for OpenGL File.
Demonstrate working with OpenGL
To show how OpenGL works, a simple program of circle – drawing is added in C using OpenGL platform.
C
// C program to demonstrate// drawing a circle using// OpenGL#include<stdio.h>#include<GL/glut.h>#include<math.h>#define pi 3.142857 // function to initializevoid myInit (void){ // making background color black as first // 3 arguments all are 0.0 glClearColor(0.0, 0.0, 0.0, 1.0); // making picture color green (in RGB mode), as middle argument is 1.0 glColor3f(0.0, 1.0, 0.0); // breadth of picture boundary is 1 pixel glPointSize(1.0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); // setting window dimension in X- and Y- direction gluOrtho2D(-780, 780, -420, 420);} void display (void) { glClear(GL_COLOR_BUFFER_BIT); glBegin(GL_POINTS); float x, y, i; // iterate y up to 2*pi, i.e., 360 degree // with small increment in angle as // glVertex2i just draws a point on specified co-ordinate for ( i = 0; i < (2 * pi); i += 0.001) { // let 200 is radius of circle and as, // circle is defined as x=r*cos(i) and y=r*sin(i) x = 200 * cos(i); y = 200 * sin(i); glVertex2i(x, y); } glEnd(); glFlush();} int main (int argc, char** argv){ glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // giving window size in X- and Y- direction glutInitWindowSize(1366, 768); glutInitWindowPosition(0, 0); // Giving name to window glutCreateWindow("Circle Drawing"); myInit(); glutDisplayFunc(display); glutMainLoop();}
To compile the above program in Ubuntu,
gcc filename.c -lGL -lGLU -lglut -lm
where filename.c is the name of the file
with which this program is saved.
Output of above program is shown in below screenshot
Reference for installation in Code::Blocks : https://www.youtube.com/watch?v=NPcnymtP2SE
This article is contributed by Aditya Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
jainshubham766
computer-graphics
OpenGL
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n29 Jun, 2022"
},
{
"code": null,
"e": 290,
"s": 52,
"text": "Open Graphics Library (OpenGL) is a cross-language (language independent), cross-platform (platform-independent) API for rendering 2D and 3D Vector Graphics(use of polygons to represent image). OpenGL API is designed mostly in hardware. "
},
{
"code": null,
"e": 470,
"s": 290,
"text": "Design : This API is defined as a set of functions which may be called by the client program. Although functions are similar to those of C language but it is language independent."
},
{
"code": null,
"e": 698,
"s": 470,
"text": "Development : It is an evolving API and Khronos Group regularly releases its new version having some extended feature compare to previous one. GPU vendors may also provide some additional functionality in the form of extension."
},
{
"code": null,
"e": 1032,
"s": 698,
"text": "Associated Libraries : The earliest version is released with a companion library called OpenGL utility library. But since OpenGL is quite a complex process. So in order to make it easier other library such as OpenGL Utility Toolkit is added which is later superseded by free glut. Later included library were GLEE, GLEW, and gliding."
},
{
"code": null,
"e": 1268,
"s": 1032,
"text": "Implementation : Mesa 3D is an open source implementation of OpenGL. It can do pure software rendering and it may also use hardware acceleration on BSD, Linux, and other platforms by taking advantage of Direct Rendering Infrastructure."
},
{
"code": null,
"e": 1409,
"s": 1268,
"text": "Install OpenGL on UbuntuFor installing OpenGL on Ubuntu, just execute the following command (like installing any other thing) in terminal : "
},
{
"code": null,
"e": 1445,
"s": 1409,
"text": "sudo apt-get install freeglut3-dev\n"
},
{
"code": null,
"e": 1486,
"s": 1445,
"text": "For working on Ubuntu operating system: "
},
{
"code": null,
"e": 1596,
"s": 1486,
"text": "gcc filename.c -lGL -lGLU -lglut \nwhere filename.c is the name of the file\nwith which this program is saved.\n"
},
{
"code": null,
"e": 1639,
"s": 1596,
"text": "Install OpenGL on windows in Code::Blocks "
},
{
"code": null,
"e": 3070,
"s": 1639,
"text": "Download code block and install itGo to the link and download zip file from the download link that appears after freeglut MinGW package with having link name as Download freeglut 3.0.0 for MinGW and extract it.Open notepad with run as administrator and open file from This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > share > CodeBlocks > templates, (then click to show All Files)Next, open glut.cbp and search all glut32 and replace with freeglut.Then, open from This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > share > CodeBlocks > templates > wizard > glut (then click to show All Files)Open wizard.script and here, also replace all glut32 with freeglut Then go to freeglut folder (where it was downloaded) and Include > GL and copy all four file from thereGo to This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > MinGW > include > GL and paste it.Then, from download folder freeglut > lib, copy two files and go to This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > MinGW > lib and paste it.Again go to downloaded folder freeglut > bin and copy one file (freeglut.dll) from here and go to This PC > C:(C-drive) > Windows > SysWOW64 and paste this file.Now open Code::Blocks. Select File > New > Project > GLUT project > Next.Give project title anything and then choose Next.For selecting GLUT’s location : This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > MinGW.Press OK > Next > Finish."
},
{
"code": null,
"e": 3105,
"s": 3070,
"text": "Download code block and install it"
},
{
"code": null,
"e": 3282,
"s": 3105,
"text": "Go to the link and download zip file from the download link that appears after freeglut MinGW package with having link name as Download freeglut 3.0.0 for MinGW and extract it."
},
{
"code": null,
"e": 3747,
"s": 3282,
"text": "Open notepad with run as administrator and open file from This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > share > CodeBlocks > templates, (then click to show All Files)Next, open glut.cbp and search all glut32 and replace with freeglut.Then, open from This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > share > CodeBlocks > templates > wizard > glut (then click to show All Files)Open wizard.script and here, also replace all glut32 with freeglut "
},
{
"code": null,
"e": 4154,
"s": 3747,
"text": "This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > share > CodeBlocks > templates, (then click to show All Files)Next, open glut.cbp and search all glut32 and replace with freeglut.Then, open from This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > share > CodeBlocks > templates > wizard > glut (then click to show All Files)Open wizard.script and here, also replace all glut32 with freeglut "
},
{
"code": null,
"e": 4275,
"s": 4154,
"text": "This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > share > CodeBlocks > templates, (then click to show All Files)"
},
{
"code": null,
"e": 4344,
"s": 4275,
"text": "Next, open glut.cbp and search all glut32 and replace with freeglut."
},
{
"code": null,
"e": 4496,
"s": 4344,
"text": "Then, open from This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > share > CodeBlocks > templates > wizard > glut (then click to show All Files)"
},
{
"code": null,
"e": 4564,
"s": 4496,
"text": "Open wizard.script and here, also replace all glut32 with freeglut "
},
{
"code": null,
"e": 5078,
"s": 4564,
"text": "Then go to freeglut folder (where it was downloaded) and Include > GL and copy all four file from thereGo to This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > MinGW > include > GL and paste it.Then, from download folder freeglut > lib, copy two files and go to This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > MinGW > lib and paste it.Again go to downloaded folder freeglut > bin and copy one file (freeglut.dll) from here and go to This PC > C:(C-drive) > Windows > SysWOW64 and paste this file."
},
{
"code": null,
"e": 5535,
"s": 5078,
"text": "Include > GL and copy all four file from thereGo to This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > MinGW > include > GL and paste it.Then, from download folder freeglut > lib, copy two files and go to This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > MinGW > lib and paste it.Again go to downloaded folder freeglut > bin and copy one file (freeglut.dll) from here and go to This PC > C:(C-drive) > Windows > SysWOW64 and paste this file."
},
{
"code": null,
"e": 5582,
"s": 5535,
"text": "Include > GL and copy all four file from there"
},
{
"code": null,
"e": 5681,
"s": 5582,
"text": "Go to This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > MinGW > include > GL and paste it."
},
{
"code": null,
"e": 5833,
"s": 5681,
"text": "Then, from download folder freeglut > lib, copy two files and go to This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > MinGW > lib and paste it."
},
{
"code": null,
"e": 5995,
"s": 5833,
"text": "Again go to downloaded folder freeglut > bin and copy one file (freeglut.dll) from here and go to This PC > C:(C-drive) > Windows > SysWOW64 and paste this file."
},
{
"code": null,
"e": 6239,
"s": 5995,
"text": "Now open Code::Blocks. Select File > New > Project > GLUT project > Next.Give project title anything and then choose Next.For selecting GLUT’s location : This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > MinGW.Press OK > Next > Finish."
},
{
"code": null,
"e": 6460,
"s": 6239,
"text": "Select File > New > Project > GLUT project > Next.Give project title anything and then choose Next.For selecting GLUT’s location : This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > MinGW.Press OK > Next > Finish."
},
{
"code": null,
"e": 6511,
"s": 6460,
"text": "Select File > New > Project > GLUT project > Next."
},
{
"code": null,
"e": 6561,
"s": 6511,
"text": "Give project title anything and then choose Next."
},
{
"code": null,
"e": 6658,
"s": 6561,
"text": "For selecting GLUT’s location : This PC > C:(C-drive) > Program Files(x86) > CodeBlocks > MinGW."
},
{
"code": null,
"e": 6684,
"s": 6658,
"text": "Press OK > Next > Finish."
},
{
"code": null,
"e": 6737,
"s": 6684,
"text": "Now, Code::Blocks is ready to test for OpenGL File. "
},
{
"code": null,
"e": 6769,
"s": 6737,
"text": "Demonstrate working with OpenGL"
},
{
"code": null,
"e": 6869,
"s": 6769,
"text": "To show how OpenGL works, a simple program of circle – drawing is added in C using OpenGL platform."
},
{
"code": null,
"e": 6871,
"s": 6869,
"text": "C"
},
{
"code": "// C program to demonstrate// drawing a circle using// OpenGL#include<stdio.h>#include<GL/glut.h>#include<math.h>#define pi 3.142857 // function to initializevoid myInit (void){ // making background color black as first // 3 arguments all are 0.0 glClearColor(0.0, 0.0, 0.0, 1.0); // making picture color green (in RGB mode), as middle argument is 1.0 glColor3f(0.0, 1.0, 0.0); // breadth of picture boundary is 1 pixel glPointSize(1.0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); // setting window dimension in X- and Y- direction gluOrtho2D(-780, 780, -420, 420);} void display (void) { glClear(GL_COLOR_BUFFER_BIT); glBegin(GL_POINTS); float x, y, i; // iterate y up to 2*pi, i.e., 360 degree // with small increment in angle as // glVertex2i just draws a point on specified co-ordinate for ( i = 0; i < (2 * pi); i += 0.001) { // let 200 is radius of circle and as, // circle is defined as x=r*cos(i) and y=r*sin(i) x = 200 * cos(i); y = 200 * sin(i); glVertex2i(x, y); } glEnd(); glFlush();} int main (int argc, char** argv){ glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // giving window size in X- and Y- direction glutInitWindowSize(1366, 768); glutInitWindowPosition(0, 0); // Giving name to window glutCreateWindow(\"Circle Drawing\"); myInit(); glutDisplayFunc(display); glutMainLoop();}",
"e": 8382,
"s": 6871,
"text": null
},
{
"code": null,
"e": 8423,
"s": 8382,
"text": "To compile the above program in Ubuntu, "
},
{
"code": null,
"e": 8537,
"s": 8423,
"text": "gcc filename.c -lGL -lGLU -lglut -lm \nwhere filename.c is the name of the file\nwith which this program is saved.\n"
},
{
"code": null,
"e": 8590,
"s": 8537,
"text": "Output of above program is shown in below screenshot"
},
{
"code": null,
"e": 8679,
"s": 8590,
"text": "Reference for installation in Code::Blocks : https://www.youtube.com/watch?v=NPcnymtP2SE"
},
{
"code": null,
"e": 9100,
"s": 8679,
"text": "This article is contributed by Aditya Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 9115,
"s": 9100,
"text": "jainshubham766"
},
{
"code": null,
"e": 9133,
"s": 9115,
"text": "computer-graphics"
},
{
"code": null,
"e": 9140,
"s": 9133,
"text": "OpenGL"
},
{
"code": null,
"e": 9145,
"s": 9140,
"text": "Misc"
},
{
"code": null,
"e": 9150,
"s": 9145,
"text": "Misc"
},
{
"code": null,
"e": 9155,
"s": 9150,
"text": "Misc"
}
] |
Minimum distance to travel to cover all intervals
|
22 Jun, 2022
Given many intervals as ranges and our position. We need to find minimum distance to travel to reach such a point which covers all the intervals at once.
Examples:
Input : Intervals = [(0, 7), (2, 14), (4, 6)]
Position = 3
Output : 1
We can reach position 4 by traveling
distance 1, at which all intervals will
be covered. So answer will be 1
Input : Intervals = [(1, 2), (2, 3), (3, 4)]
Position = 2
Output : -1
It is not possible to cover all intervals
at once at any point
Input : Intervals = [(1, 2), (2, 3), (1, 4)]
Position = 2
Output : 0
All Intervals are covered at current
position only so no need travel and
answer will be 0
All above examples are shown in below diagram.
We can solve this problem by concentrating only on endpoints. Since the requirement is to cover all intervals by reaching a point, all intervals must a share a point for answer to exist. Even the interval with leftmost end point must overlap with the interval right most start point. First, we find right most start point and left most end point from all intervals. Then we can compare our position with these points to get the result which is explained below :
If this right most start point is to the right of left most end point then it is not possible to cover all intervals simultaneously. (as in example 2)If our position is in mid between to right most start and left most end then there is no need to travel and all intervals will be covered by current position only (as in example 3)If our position is left to both points then we need to travel up to the rightmost start point and if our position is right to both points then we need to travel up to leftmost end point.
If this right most start point is to the right of left most end point then it is not possible to cover all intervals simultaneously. (as in example 2)
If our position is in mid between to right most start and left most end then there is no need to travel and all intervals will be covered by current position only (as in example 3)
If our position is left to both points then we need to travel up to the rightmost start point and if our position is right to both points then we need to travel up to leftmost end point.
Refer above diagram to understand these cases. As in the first example, right most start is 4 and left most end is 6, so we need to reach 4 from current position 3 to cover all intervals.
Please see the below code for a better understanding.
C++
Java
Python3
C#
Javascript
// C++ program to find minimum distance to// travel to cover all intervals#include <bits/stdc++.h>using namespace std; // structure to store an intervalstruct Interval{ int start, end; Interval(int start, int end) : start(start), end(end) {}}; // Method returns minimum distance to travel// to cover all intervalsint minDistanceToCoverIntervals(Interval intervals[], int N, int x){ int rightMostStart = INT_MIN; int leftMostEnd = INT_MAX; // looping over all intervals to get right most // start and left most end for (int i = 0; i < N; i++) { if (rightMostStart < intervals[i].start) rightMostStart = intervals[i].start; if (leftMostEnd > intervals[i].end) leftMostEnd = intervals[i].end; } int res; /* if rightmost start > leftmost end then all intervals are not aligned and it is not possible to cover all of them */ if (rightMostStart > leftMostEnd) res = -1; // if x is in between rightmoststart and // leftmostend then no need to travel any distance else if (rightMostStart <= x && x <= leftMostEnd) res = 0; // choose minimum according to current position x else res = (x < rightMostStart) ? (rightMostStart - x) : (x - leftMostEnd); return res;} // Driver code to test above methodsint main(){ int x = 3; Interval intervals[] = {{0, 7}, {2, 14}, {4, 6}}; int N = sizeof(intervals) / sizeof(intervals[0]); int res = minDistanceToCoverIntervals(intervals, N, x); if (res == -1) cout << "Not Possible to cover all intervals\n"; else cout << res << endl;}
// Java program to find minimum distance// to travel to cover all intervalsimport java.util.*; class GFG{ // Structure to store an intervalstatic class Interval{ int start, end; Interval(int start, int end) { this.start = start; this.end = end; }}; // Method returns minimum distance to// travel to cover all intervalsstatic int minDistanceToCoverIntervals(Interval intervals[], int N, int x){ int rightMostStart = Integer.MIN_VALUE; int leftMostEnd = Integer.MAX_VALUE; // Looping over all intervals to get // right most start and left most end for(int i = 0; i < N; i++) { if (rightMostStart < intervals[i].start) rightMostStart = intervals[i].start; if (leftMostEnd > intervals[i].end) leftMostEnd = intervals[i].end; } int res; // If rightmost start > leftmost end then // all intervals are not aligned and it // is not possible to cover all of them if (rightMostStart > leftMostEnd) res = -1; // If x is in between rightmoststart and // leftmostend then no need to travel // any distance else if (rightMostStart <= x && x <= leftMostEnd) res = 0; // Choose minimum according to // current position x else res = (x < rightMostStart) ? (rightMostStart - x) : (x - leftMostEnd); return res;} // Driver codepublic static void main(String[] args){ int x = 3; Interval []intervals = { new Interval(0, 7), new Interval(2, 14), new Interval(4, 6) }; int N = intervals.length; int res = minDistanceToCoverIntervals( intervals, N, x); if (res == -1) System.out.print("Not Possible to " + "cover all intervals\n"); else System.out.print(res + "\n");}} // This code is contributed by Rajput-Ji
# Python program to find minimum distance to# travel to cover all intervals # Method returns minimum distance to travel# to cover all intervalsdef minDistanceToCoverIntervals(Intervals, N, x): rightMostStart = Intervals[0][0] leftMostStart = Intervals[0][1] # looping over all intervals to get right most # start and left most end for curr in Intervals: if rightMostStart < curr[0]: rightMostStart = curr[0] if leftMostStart > curr[1]: leftMostStart = curr[1] # if rightmost start > leftmost end then all # intervals are not aligned and it is not # possible to cover all of them if rightMostStart > leftMostStart: res = -1 # if x is in between rightmoststart and # leftmostend then no need to travel any distance else if rightMostStart <= x and x <= leftMostStart: res = 0 # choose minimum according to current position x else: res = rightMostStart-x if x < rightMostStart else x-leftMostStart return res # Driver code to test above methodsIntervals = [[0, 7], [2, 14], [4, 6]]N = len(Intervals)x = 3 res = minDistanceToCoverIntervals(Intervals, N, x)if res == -1: print("Not Possible to cover all intervals")else: print(res) # This code is contributed by rj13to.
// C# program to find minimum distance// to travel to cover all intervalsusing System; class GFG{ // Structure to store an intervalpublic class Interval{ public int start, end; public Interval(int start, int end) { this.start = start; this.end = end; }}; // Method returns minimum distance to// travel to cover all intervalsstatic int minDistanceToCoverIntervals( Interval []intervals, int N, int x){ int rightMostStart = int.MinValue; int leftMostEnd = int.MaxValue; // Looping over all intervals to get // right most start and left most end for(int i = 0; i < N; i++) { if (rightMostStart < intervals[i].start) rightMostStart = intervals[i].start; if (leftMostEnd > intervals[i].end) leftMostEnd = intervals[i].end; } int res; // If rightmost start > leftmost end then // all intervals are not aligned and it // is not possible to cover all of them if (rightMostStart > leftMostEnd) res = -1; // If x is in between rightmoststart and // leftmostend then no need to travel // any distance else if (rightMostStart <= x && x <= leftMostEnd) res = 0; // Choose minimum according to // current position x else res = (x < rightMostStart) ? (rightMostStart - x) : (x - leftMostEnd); return res;} // Driver codepublic static void Main(String[] args){ int x = 3; Interval []intervals = { new Interval(0, 7), new Interval(2, 14), new Interval(4, 6) }; int N = intervals.Length; int res = minDistanceToCoverIntervals( intervals, N, x); if (res == -1) Console.Write("Not Possible to " + "cover all intervals\n"); else Console.Write(res + "\n");}} // This code is contributed by shikhasingrajput
<script> // JavaScript program to find minimum distance to// travel to cover all intervals // Method returns minimum distance to travel// to cover all intervalsfunction minDistanceToCoverIntervals(Intervals, N, x){ let rightMostStart = Intervals[0][0] let leftMostStart = Intervals[0][1] // looping over all intervals to get right most // start and left most end for(let curr of Intervals){ if(rightMostStart < curr[0]) rightMostStart = curr[0] if(leftMostStart > curr[1]) leftMostStart = curr[1] } let res; // if rightmost start > leftmost end then all // intervals are not aligned and it is not // possible to cover all of them if(rightMostStart > leftMostStart) res = -1 // if x is in between rightmoststart and // leftmostend then no need to travel any distance else if(rightMostStart <= x && x <= leftMostStart) res = 0 // choose minimum according to current position x else res = (x < rightMostStart)?rightMostStart-x : x-leftMostStart return res} // Driver code to test above methodslet Intervals = [[0, 7], [2, 14], [4, 6]]let N = Intervals.lengthlet x = 3 let res = minDistanceToCoverIntervals(Intervals, N, x)if(res == -1) document.write("Not Possible to cover all intervals","<br>")else document.write(res) // This code is contributed by shinjanpatra </script>
Output:
1
Time Complexity: O(N)
Auxiliary Space: O(N)This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Rajput-Ji
shikhasingrajput
rj13to
surinderdawra388
shinjanpatra
mailaruyashaswi
Geometric
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 207,
"s": 52,
"text": "Given many intervals as ranges and our position. We need to find minimum distance to travel to reach such a point which covers all the intervals at once. "
},
{
"code": null,
"e": 219,
"s": 207,
"text": "Examples: "
},
{
"code": null,
"e": 766,
"s": 219,
"text": "Input : Intervals = [(0, 7), (2, 14), (4, 6)]\n Position = 3\nOutput : 1\nWe can reach position 4 by traveling\ndistance 1, at which all intervals will\nbe covered. So answer will be 1\n\nInput : Intervals = [(1, 2), (2, 3), (3, 4)]\n Position = 2\nOutput : -1 \nIt is not possible to cover all intervals\nat once at any point\n\nInput : Intervals = [(1, 2), (2, 3), (1, 4)]\n Position = 2\nOutput : 0\nAll Intervals are covered at current \nposition only so no need travel and\nanswer will be 0\n\nAll above examples are shown in below diagram."
},
{
"code": null,
"e": 1229,
"s": 766,
"text": "We can solve this problem by concentrating only on endpoints. Since the requirement is to cover all intervals by reaching a point, all intervals must a share a point for answer to exist. Even the interval with leftmost end point must overlap with the interval right most start point. First, we find right most start point and left most end point from all intervals. Then we can compare our position with these points to get the result which is explained below : "
},
{
"code": null,
"e": 1746,
"s": 1229,
"text": "If this right most start point is to the right of left most end point then it is not possible to cover all intervals simultaneously. (as in example 2)If our position is in mid between to right most start and left most end then there is no need to travel and all intervals will be covered by current position only (as in example 3)If our position is left to both points then we need to travel up to the rightmost start point and if our position is right to both points then we need to travel up to leftmost end point."
},
{
"code": null,
"e": 1897,
"s": 1746,
"text": "If this right most start point is to the right of left most end point then it is not possible to cover all intervals simultaneously. (as in example 2)"
},
{
"code": null,
"e": 2078,
"s": 1897,
"text": "If our position is in mid between to right most start and left most end then there is no need to travel and all intervals will be covered by current position only (as in example 3)"
},
{
"code": null,
"e": 2265,
"s": 2078,
"text": "If our position is left to both points then we need to travel up to the rightmost start point and if our position is right to both points then we need to travel up to leftmost end point."
},
{
"code": null,
"e": 2454,
"s": 2265,
"text": "Refer above diagram to understand these cases. As in the first example, right most start is 4 and left most end is 6, so we need to reach 4 from current position 3 to cover all intervals. "
},
{
"code": null,
"e": 2510,
"s": 2454,
"text": "Please see the below code for a better understanding. "
},
{
"code": null,
"e": 2514,
"s": 2510,
"text": "C++"
},
{
"code": null,
"e": 2519,
"s": 2514,
"text": "Java"
},
{
"code": null,
"e": 2527,
"s": 2519,
"text": "Python3"
},
{
"code": null,
"e": 2530,
"s": 2527,
"text": "C#"
},
{
"code": null,
"e": 2541,
"s": 2530,
"text": "Javascript"
},
{
"code": "// C++ program to find minimum distance to// travel to cover all intervals#include <bits/stdc++.h>using namespace std; // structure to store an intervalstruct Interval{ int start, end; Interval(int start, int end) : start(start), end(end) {}}; // Method returns minimum distance to travel// to cover all intervalsint minDistanceToCoverIntervals(Interval intervals[], int N, int x){ int rightMostStart = INT_MIN; int leftMostEnd = INT_MAX; // looping over all intervals to get right most // start and left most end for (int i = 0; i < N; i++) { if (rightMostStart < intervals[i].start) rightMostStart = intervals[i].start; if (leftMostEnd > intervals[i].end) leftMostEnd = intervals[i].end; } int res; /* if rightmost start > leftmost end then all intervals are not aligned and it is not possible to cover all of them */ if (rightMostStart > leftMostEnd) res = -1; // if x is in between rightmoststart and // leftmostend then no need to travel any distance else if (rightMostStart <= x && x <= leftMostEnd) res = 0; // choose minimum according to current position x else res = (x < rightMostStart) ? (rightMostStart - x) : (x - leftMostEnd); return res;} // Driver code to test above methodsint main(){ int x = 3; Interval intervals[] = {{0, 7}, {2, 14}, {4, 6}}; int N = sizeof(intervals) / sizeof(intervals[0]); int res = minDistanceToCoverIntervals(intervals, N, x); if (res == -1) cout << \"Not Possible to cover all intervals\\n\"; else cout << res << endl;}",
"e": 4301,
"s": 2541,
"text": null
},
{
"code": "// Java program to find minimum distance// to travel to cover all intervalsimport java.util.*; class GFG{ // Structure to store an intervalstatic class Interval{ int start, end; Interval(int start, int end) { this.start = start; this.end = end; }}; // Method returns minimum distance to// travel to cover all intervalsstatic int minDistanceToCoverIntervals(Interval intervals[], int N, int x){ int rightMostStart = Integer.MIN_VALUE; int leftMostEnd = Integer.MAX_VALUE; // Looping over all intervals to get // right most start and left most end for(int i = 0; i < N; i++) { if (rightMostStart < intervals[i].start) rightMostStart = intervals[i].start; if (leftMostEnd > intervals[i].end) leftMostEnd = intervals[i].end; } int res; // If rightmost start > leftmost end then // all intervals are not aligned and it // is not possible to cover all of them if (rightMostStart > leftMostEnd) res = -1; // If x is in between rightmoststart and // leftmostend then no need to travel // any distance else if (rightMostStart <= x && x <= leftMostEnd) res = 0; // Choose minimum according to // current position x else res = (x < rightMostStart) ? (rightMostStart - x) : (x - leftMostEnd); return res;} // Driver codepublic static void main(String[] args){ int x = 3; Interval []intervals = { new Interval(0, 7), new Interval(2, 14), new Interval(4, 6) }; int N = intervals.length; int res = minDistanceToCoverIntervals( intervals, N, x); if (res == -1) System.out.print(\"Not Possible to \" + \"cover all intervals\\n\"); else System.out.print(res + \"\\n\");}} // This code is contributed by Rajput-Ji",
"e": 6269,
"s": 4301,
"text": null
},
{
"code": "# Python program to find minimum distance to# travel to cover all intervals # Method returns minimum distance to travel# to cover all intervalsdef minDistanceToCoverIntervals(Intervals, N, x): rightMostStart = Intervals[0][0] leftMostStart = Intervals[0][1] # looping over all intervals to get right most # start and left most end for curr in Intervals: if rightMostStart < curr[0]: rightMostStart = curr[0] if leftMostStart > curr[1]: leftMostStart = curr[1] # if rightmost start > leftmost end then all # intervals are not aligned and it is not # possible to cover all of them if rightMostStart > leftMostStart: res = -1 # if x is in between rightmoststart and # leftmostend then no need to travel any distance else if rightMostStart <= x and x <= leftMostStart: res = 0 # choose minimum according to current position x else: res = rightMostStart-x if x < rightMostStart else x-leftMostStart return res # Driver code to test above methodsIntervals = [[0, 7], [2, 14], [4, 6]]N = len(Intervals)x = 3 res = minDistanceToCoverIntervals(Intervals, N, x)if res == -1: print(\"Not Possible to cover all intervals\")else: print(res) # This code is contributed by rj13to.",
"e": 7566,
"s": 6269,
"text": null
},
{
"code": "// C# program to find minimum distance// to travel to cover all intervalsusing System; class GFG{ // Structure to store an intervalpublic class Interval{ public int start, end; public Interval(int start, int end) { this.start = start; this.end = end; }}; // Method returns minimum distance to// travel to cover all intervalsstatic int minDistanceToCoverIntervals( Interval []intervals, int N, int x){ int rightMostStart = int.MinValue; int leftMostEnd = int.MaxValue; // Looping over all intervals to get // right most start and left most end for(int i = 0; i < N; i++) { if (rightMostStart < intervals[i].start) rightMostStart = intervals[i].start; if (leftMostEnd > intervals[i].end) leftMostEnd = intervals[i].end; } int res; // If rightmost start > leftmost end then // all intervals are not aligned and it // is not possible to cover all of them if (rightMostStart > leftMostEnd) res = -1; // If x is in between rightmoststart and // leftmostend then no need to travel // any distance else if (rightMostStart <= x && x <= leftMostEnd) res = 0; // Choose minimum according to // current position x else res = (x < rightMostStart) ? (rightMostStart - x) : (x - leftMostEnd); return res;} // Driver codepublic static void Main(String[] args){ int x = 3; Interval []intervals = { new Interval(0, 7), new Interval(2, 14), new Interval(4, 6) }; int N = intervals.Length; int res = minDistanceToCoverIntervals( intervals, N, x); if (res == -1) Console.Write(\"Not Possible to \" + \"cover all intervals\\n\"); else Console.Write(res + \"\\n\");}} // This code is contributed by shikhasingrajput",
"e": 9499,
"s": 7566,
"text": null
},
{
"code": "<script> // JavaScript program to find minimum distance to// travel to cover all intervals // Method returns minimum distance to travel// to cover all intervalsfunction minDistanceToCoverIntervals(Intervals, N, x){ let rightMostStart = Intervals[0][0] let leftMostStart = Intervals[0][1] // looping over all intervals to get right most // start and left most end for(let curr of Intervals){ if(rightMostStart < curr[0]) rightMostStart = curr[0] if(leftMostStart > curr[1]) leftMostStart = curr[1] } let res; // if rightmost start > leftmost end then all // intervals are not aligned and it is not // possible to cover all of them if(rightMostStart > leftMostStart) res = -1 // if x is in between rightmoststart and // leftmostend then no need to travel any distance else if(rightMostStart <= x && x <= leftMostStart) res = 0 // choose minimum according to current position x else res = (x < rightMostStart)?rightMostStart-x : x-leftMostStart return res} // Driver code to test above methodslet Intervals = [[0, 7], [2, 14], [4, 6]]let N = Intervals.lengthlet x = 3 let res = minDistanceToCoverIntervals(Intervals, N, x)if(res == -1) document.write(\"Not Possible to cover all intervals\",\"<br>\")else document.write(res) // This code is contributed by shinjanpatra </script>",
"e": 10901,
"s": 9499,
"text": null
},
{
"code": null,
"e": 10910,
"s": 10901,
"text": "Output: "
},
{
"code": null,
"e": 10912,
"s": 10910,
"text": "1"
},
{
"code": null,
"e": 10934,
"s": 10912,
"text": "Time Complexity: O(N)"
},
{
"code": null,
"e": 11379,
"s": 10934,
"text": "Auxiliary Space: O(N)This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 11389,
"s": 11379,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 11406,
"s": 11389,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 11413,
"s": 11406,
"text": "rj13to"
},
{
"code": null,
"e": 11430,
"s": 11413,
"text": "surinderdawra388"
},
{
"code": null,
"e": 11443,
"s": 11430,
"text": "shinjanpatra"
},
{
"code": null,
"e": 11459,
"s": 11443,
"text": "mailaruyashaswi"
},
{
"code": null,
"e": 11469,
"s": 11459,
"text": "Geometric"
},
{
"code": null,
"e": 11479,
"s": 11469,
"text": "Geometric"
}
] |
Join statement in JCL
|
25 Jun, 2020
Prerequisite – Job Control Language (JCL)In RDBMS, SQL JOIN clause is used to join tables and perform multiple operations on it. To perform operations on records in different flat files, JOINKEYS are used. With the help of JOINKEYS in SORT JCL, various join operation on matched and non-matched records can be executed based on matching fields or Keys. Joining can be performed in number of ways like inner join, full outer join, left outer join, right outer join and unpaired combinations.
The join operation is controlled by three important control statements JOINKEYS, JOIN, and REFORMAT. The SORTJNF1 and SORTJNF2, are the DD statements used to specify the files which will be use to perform join operation.
Control Statements :
JOINKEYS FILES=F1, FIELDS=(1, 10, A) – Specifies the file1 join criteria.JOINKEYS FILES=F2, FIELDS=(1, 10, A) – Specifies the file2 join criteria.REFORMAT FIELDS=(F1:1, 71, F2:1, 9) – REFORMAT fields tells the sort utility, what fields to be written into output file from the input files by specifying starting and ending position.
JOINKEYS FILES=F1, FIELDS=(1, 10, A) – Specifies the file1 join criteria.
JOINKEYS FILES=F2, FIELDS=(1, 10, A) – Specifies the file2 join criteria.
REFORMAT FIELDS=(F1:1, 71, F2:1, 9) – REFORMAT fields tells the sort utility, what fields to be written into output file from the input files by specifying starting and ending position.
JCL SORT to join two files and writes records from both files :
Matched Records (Inner Join) –If join statement not specified in sort card, paired records from F1 and F2 are written into output file.//SYSIN DD *
SORT FIELDS=COPY
JOINKEYS FILES=F1, FIELDS=(1, 10, A)
JOINKEYS FILES=F2, FIELDS=(1, 10, A)
REFORMAT FIELDS=(F1:1, 71, F2:1, 9)
/*Matched Records and Non Matched Records from File1 –Sort card to retain unpaired records from F1 file along with paired records. This type of join is called a LEFT OUTER JOIN.//SYSIN DD *
SORT FIELDS=COPY
JOINKEYS FILES=F1, FIELDS=(1, 10, A)
JOINKEYS FILES=F2, FIELDS=(1, 10, A)
JOIN UNPAIRED, F1
REFORMAT FIELDS=(F1:1, 71, F2:1, 9)
/*Non Matched from File1 –Sort card to retain unpaired records from F1 file, cannot use reformat in F2.//SYSIN DD *
SORT FIELDS=COPY
JOINKEYS FILES=F1, FIELDS=(1, 10, A)
JOINKEYS FILES=F2, FIELDS=(1, 10, A)
JOIN UNPAIRED, F1, ONLY
REFORMAT FIELDS=(F1:1, 71)
/*Matched Records and Non Matched from File2 –Sort card to retain unpaired records from F2 file along with paired records. This type of join is called RIGHT OUTER JOIN.//SYSIN DD *
SORT FIELDS=COPY
JOINKEYS FILES=F1, FIELDS=(1, 10, A)
JOINKEYS FILES=F2, FIELDS=(1, 10, A)
JOIN UNPAIRED, F2
REFORMAT FIELDS=(F1:1, 71, F2:1, 9)
/*Non Matched from File2 –Sort card to retain unpaired records from F2 file, cannot use reformat in F1.//SYSIN DD *
SORT FIELDS=COPY
JOINKEYS FILES=F1, FIELDS=(1, 10, A)
JOINKEYS FILES=F2, FIELDS=(1, 10, A)
JOIN UNPAIRED, F2, ONLY
REFORMAT FIELDS=(F2:1, 9)
/*Matched Records and Non Matched Records from both files –Sort card to retain unpaired records from both F1 and F2 files along with paired records. This type of join is called as FULL OUTER JOIN.//SYSIN DD *
SORT FIELDS=COPY
JOINKEYS FILES=F1, FIELDS=(1, 10, A)
JOINKEYS FILES=F2, FIELDS=(1, 10, A)
JOIN UNPAIRED, F1, F2
REFORMAT FIELDS=(F1:1, 71, F2:1, 9)
/*Non Matched Records from both files –Sort card to retain only unpaired records from F1 and F2 files.//SYSIN DD *
SORT FIELDS=COPY
JOINKEYS FILES=F1, FIELDS=(1, 10, A)
JOINKEYS FILES=F2, FIELDS=(1, 10, A)
JOIN UNPAIRED, F1, F2, ONLY or JOIN UNPAIRED, ONLY
REFORMAT FIELDS=(F1:1, 71, F2:1, 9)
/*
Matched Records (Inner Join) –If join statement not specified in sort card, paired records from F1 and F2 are written into output file.//SYSIN DD *
SORT FIELDS=COPY
JOINKEYS FILES=F1, FIELDS=(1, 10, A)
JOINKEYS FILES=F2, FIELDS=(1, 10, A)
REFORMAT FIELDS=(F1:1, 71, F2:1, 9)
/*
//SYSIN DD *
SORT FIELDS=COPY
JOINKEYS FILES=F1, FIELDS=(1, 10, A)
JOINKEYS FILES=F2, FIELDS=(1, 10, A)
REFORMAT FIELDS=(F1:1, 71, F2:1, 9)
/*
Matched Records and Non Matched Records from File1 –Sort card to retain unpaired records from F1 file along with paired records. This type of join is called a LEFT OUTER JOIN.//SYSIN DD *
SORT FIELDS=COPY
JOINKEYS FILES=F1, FIELDS=(1, 10, A)
JOINKEYS FILES=F2, FIELDS=(1, 10, A)
JOIN UNPAIRED, F1
REFORMAT FIELDS=(F1:1, 71, F2:1, 9)
/*
//SYSIN DD *
SORT FIELDS=COPY
JOINKEYS FILES=F1, FIELDS=(1, 10, A)
JOINKEYS FILES=F2, FIELDS=(1, 10, A)
JOIN UNPAIRED, F1
REFORMAT FIELDS=(F1:1, 71, F2:1, 9)
/*
Non Matched from File1 –Sort card to retain unpaired records from F1 file, cannot use reformat in F2.//SYSIN DD *
SORT FIELDS=COPY
JOINKEYS FILES=F1, FIELDS=(1, 10, A)
JOINKEYS FILES=F2, FIELDS=(1, 10, A)
JOIN UNPAIRED, F1, ONLY
REFORMAT FIELDS=(F1:1, 71)
/*
//SYSIN DD *
SORT FIELDS=COPY
JOINKEYS FILES=F1, FIELDS=(1, 10, A)
JOINKEYS FILES=F2, FIELDS=(1, 10, A)
JOIN UNPAIRED, F1, ONLY
REFORMAT FIELDS=(F1:1, 71)
/*
Matched Records and Non Matched from File2 –Sort card to retain unpaired records from F2 file along with paired records. This type of join is called RIGHT OUTER JOIN.//SYSIN DD *
SORT FIELDS=COPY
JOINKEYS FILES=F1, FIELDS=(1, 10, A)
JOINKEYS FILES=F2, FIELDS=(1, 10, A)
JOIN UNPAIRED, F2
REFORMAT FIELDS=(F1:1, 71, F2:1, 9)
/*
//SYSIN DD *
SORT FIELDS=COPY
JOINKEYS FILES=F1, FIELDS=(1, 10, A)
JOINKEYS FILES=F2, FIELDS=(1, 10, A)
JOIN UNPAIRED, F2
REFORMAT FIELDS=(F1:1, 71, F2:1, 9)
/*
Non Matched from File2 –Sort card to retain unpaired records from F2 file, cannot use reformat in F1.//SYSIN DD *
SORT FIELDS=COPY
JOINKEYS FILES=F1, FIELDS=(1, 10, A)
JOINKEYS FILES=F2, FIELDS=(1, 10, A)
JOIN UNPAIRED, F2, ONLY
REFORMAT FIELDS=(F2:1, 9)
/*
//SYSIN DD *
SORT FIELDS=COPY
JOINKEYS FILES=F1, FIELDS=(1, 10, A)
JOINKEYS FILES=F2, FIELDS=(1, 10, A)
JOIN UNPAIRED, F2, ONLY
REFORMAT FIELDS=(F2:1, 9)
/*
Matched Records and Non Matched Records from both files –Sort card to retain unpaired records from both F1 and F2 files along with paired records. This type of join is called as FULL OUTER JOIN.//SYSIN DD *
SORT FIELDS=COPY
JOINKEYS FILES=F1, FIELDS=(1, 10, A)
JOINKEYS FILES=F2, FIELDS=(1, 10, A)
JOIN UNPAIRED, F1, F2
REFORMAT FIELDS=(F1:1, 71, F2:1, 9)
/*
//SYSIN DD *
SORT FIELDS=COPY
JOINKEYS FILES=F1, FIELDS=(1, 10, A)
JOINKEYS FILES=F2, FIELDS=(1, 10, A)
JOIN UNPAIRED, F1, F2
REFORMAT FIELDS=(F1:1, 71, F2:1, 9)
/*
Non Matched Records from both files –Sort card to retain only unpaired records from F1 and F2 files.//SYSIN DD *
SORT FIELDS=COPY
JOINKEYS FILES=F1, FIELDS=(1, 10, A)
JOINKEYS FILES=F2, FIELDS=(1, 10, A)
JOIN UNPAIRED, F1, F2, ONLY or JOIN UNPAIRED, ONLY
REFORMAT FIELDS=(F1:1, 71, F2:1, 9)
/*
//SYSIN DD *
SORT FIELDS=COPY
JOINKEYS FILES=F1, FIELDS=(1, 10, A)
JOINKEYS FILES=F2, FIELDS=(1, 10, A)
JOIN UNPAIRED, F1, F2, ONLY or JOIN UNPAIRED, ONLY
REFORMAT FIELDS=(F1:1, 71, F2:1, 9)
/*
DBMS
Write From Home
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n25 Jun, 2020"
},
{
"code": null,
"e": 545,
"s": 54,
"text": "Prerequisite – Job Control Language (JCL)In RDBMS, SQL JOIN clause is used to join tables and perform multiple operations on it. To perform operations on records in different flat files, JOINKEYS are used. With the help of JOINKEYS in SORT JCL, various join operation on matched and non-matched records can be executed based on matching fields or Keys. Joining can be performed in number of ways like inner join, full outer join, left outer join, right outer join and unpaired combinations."
},
{
"code": null,
"e": 766,
"s": 545,
"text": "The join operation is controlled by three important control statements JOINKEYS, JOIN, and REFORMAT. The SORTJNF1 and SORTJNF2, are the DD statements used to specify the files which will be use to perform join operation."
},
{
"code": null,
"e": 787,
"s": 766,
"text": "Control Statements :"
},
{
"code": null,
"e": 1119,
"s": 787,
"text": "JOINKEYS FILES=F1, FIELDS=(1, 10, A) – Specifies the file1 join criteria.JOINKEYS FILES=F2, FIELDS=(1, 10, A) – Specifies the file2 join criteria.REFORMAT FIELDS=(F1:1, 71, F2:1, 9) – REFORMAT fields tells the sort utility, what fields to be written into output file from the input files by specifying starting and ending position."
},
{
"code": null,
"e": 1193,
"s": 1119,
"text": "JOINKEYS FILES=F1, FIELDS=(1, 10, A) – Specifies the file1 join criteria."
},
{
"code": null,
"e": 1267,
"s": 1193,
"text": "JOINKEYS FILES=F2, FIELDS=(1, 10, A) – Specifies the file2 join criteria."
},
{
"code": null,
"e": 1453,
"s": 1267,
"text": "REFORMAT FIELDS=(F1:1, 71, F2:1, 9) – REFORMAT fields tells the sort utility, what fields to be written into output file from the input files by specifying starting and ending position."
},
{
"code": null,
"e": 1517,
"s": 1453,
"text": "JCL SORT to join two files and writes records from both files :"
},
{
"code": null,
"e": 3895,
"s": 1517,
"text": "Matched Records (Inner Join) –If join statement not specified in sort card, paired records from F1 and F2 are written into output file.//SYSIN DD *\n SORT FIELDS=COPY\n JOINKEYS FILES=F1, FIELDS=(1, 10, A)\n JOINKEYS FILES=F2, FIELDS=(1, 10, A)\n REFORMAT FIELDS=(F1:1, 71, F2:1, 9)\n/*Matched Records and Non Matched Records from File1 –Sort card to retain unpaired records from F1 file along with paired records. This type of join is called a LEFT OUTER JOIN.//SYSIN DD *\n SORT FIELDS=COPY\n JOINKEYS FILES=F1, FIELDS=(1, 10, A)\n JOINKEYS FILES=F2, FIELDS=(1, 10, A)\n JOIN UNPAIRED, F1\n REFORMAT FIELDS=(F1:1, 71, F2:1, 9)\n/*Non Matched from File1 –Sort card to retain unpaired records from F1 file, cannot use reformat in F2.//SYSIN DD * \n SORT FIELDS=COPY\n JOINKEYS FILES=F1, FIELDS=(1, 10, A)\n JOINKEYS FILES=F2, FIELDS=(1, 10, A)\n JOIN UNPAIRED, F1, ONLY\n REFORMAT FIELDS=(F1:1, 71)\n/*Matched Records and Non Matched from File2 –Sort card to retain unpaired records from F2 file along with paired records. This type of join is called RIGHT OUTER JOIN.//SYSIN DD *\n SORT FIELDS=COPY\n JOINKEYS FILES=F1, FIELDS=(1, 10, A)\n JOINKEYS FILES=F2, FIELDS=(1, 10, A)\n JOIN UNPAIRED, F2\n REFORMAT FIELDS=(F1:1, 71, F2:1, 9)\n/*Non Matched from File2 –Sort card to retain unpaired records from F2 file, cannot use reformat in F1.//SYSIN DD *\n SORT FIELDS=COPY\n JOINKEYS FILES=F1, FIELDS=(1, 10, A)\n JOINKEYS FILES=F2, FIELDS=(1, 10, A)\n JOIN UNPAIRED, F2, ONLY\n REFORMAT FIELDS=(F2:1, 9)\n/*Matched Records and Non Matched Records from both files –Sort card to retain unpaired records from both F1 and F2 files along with paired records. This type of join is called as FULL OUTER JOIN.//SYSIN DD *\n SORT FIELDS=COPY\n JOINKEYS FILES=F1, FIELDS=(1, 10, A)\n JOINKEYS FILES=F2, FIELDS=(1, 10, A)\n JOIN UNPAIRED, F1, F2\n REFORMAT FIELDS=(F1:1, 71, F2:1, 9)\n/*Non Matched Records from both files –Sort card to retain only unpaired records from F1 and F2 files.//SYSIN DD *\n SORT FIELDS=COPY\n JOINKEYS FILES=F1, FIELDS=(1, 10, A)\n JOINKEYS FILES=F2, FIELDS=(1, 10, A)\n JOIN UNPAIRED, F1, F2, ONLY or JOIN UNPAIRED, ONLY\n REFORMAT FIELDS=(F1:1, 71, F2:1, 9)\n/*"
},
{
"code": null,
"e": 4205,
"s": 3895,
"text": "Matched Records (Inner Join) –If join statement not specified in sort card, paired records from F1 and F2 are written into output file.//SYSIN DD *\n SORT FIELDS=COPY\n JOINKEYS FILES=F1, FIELDS=(1, 10, A)\n JOINKEYS FILES=F2, FIELDS=(1, 10, A)\n REFORMAT FIELDS=(F1:1, 71, F2:1, 9)\n/*"
},
{
"code": null,
"e": 4380,
"s": 4205,
"text": "//SYSIN DD *\n SORT FIELDS=COPY\n JOINKEYS FILES=F1, FIELDS=(1, 10, A)\n JOINKEYS FILES=F2, FIELDS=(1, 10, A)\n REFORMAT FIELDS=(F1:1, 71, F2:1, 9)\n/*"
},
{
"code": null,
"e": 4756,
"s": 4380,
"text": "Matched Records and Non Matched Records from File1 –Sort card to retain unpaired records from F1 file along with paired records. This type of join is called a LEFT OUTER JOIN.//SYSIN DD *\n SORT FIELDS=COPY\n JOINKEYS FILES=F1, FIELDS=(1, 10, A)\n JOINKEYS FILES=F2, FIELDS=(1, 10, A)\n JOIN UNPAIRED, F1\n REFORMAT FIELDS=(F1:1, 71, F2:1, 9)\n/*"
},
{
"code": null,
"e": 4957,
"s": 4756,
"text": "//SYSIN DD *\n SORT FIELDS=COPY\n JOINKEYS FILES=F1, FIELDS=(1, 10, A)\n JOINKEYS FILES=F2, FIELDS=(1, 10, A)\n JOIN UNPAIRED, F1\n REFORMAT FIELDS=(F1:1, 71, F2:1, 9)\n/*"
},
{
"code": null,
"e": 5257,
"s": 4957,
"text": "Non Matched from File1 –Sort card to retain unpaired records from F1 file, cannot use reformat in F2.//SYSIN DD * \n SORT FIELDS=COPY\n JOINKEYS FILES=F1, FIELDS=(1, 10, A)\n JOINKEYS FILES=F2, FIELDS=(1, 10, A)\n JOIN UNPAIRED, F1, ONLY\n REFORMAT FIELDS=(F1:1, 71)\n/*"
},
{
"code": null,
"e": 5456,
"s": 5257,
"text": "//SYSIN DD * \n SORT FIELDS=COPY\n JOINKEYS FILES=F1, FIELDS=(1, 10, A)\n JOINKEYS FILES=F2, FIELDS=(1, 10, A)\n JOIN UNPAIRED, F1, ONLY\n REFORMAT FIELDS=(F1:1, 71)\n/*"
},
{
"code": null,
"e": 5823,
"s": 5456,
"text": "Matched Records and Non Matched from File2 –Sort card to retain unpaired records from F2 file along with paired records. This type of join is called RIGHT OUTER JOIN.//SYSIN DD *\n SORT FIELDS=COPY\n JOINKEYS FILES=F1, FIELDS=(1, 10, A)\n JOINKEYS FILES=F2, FIELDS=(1, 10, A)\n JOIN UNPAIRED, F2\n REFORMAT FIELDS=(F1:1, 71, F2:1, 9)\n/*"
},
{
"code": null,
"e": 6024,
"s": 5823,
"text": "//SYSIN DD *\n SORT FIELDS=COPY\n JOINKEYS FILES=F1, FIELDS=(1, 10, A)\n JOINKEYS FILES=F2, FIELDS=(1, 10, A)\n JOIN UNPAIRED, F2\n REFORMAT FIELDS=(F1:1, 71, F2:1, 9)\n/*"
},
{
"code": null,
"e": 6322,
"s": 6024,
"text": "Non Matched from File2 –Sort card to retain unpaired records from F2 file, cannot use reformat in F1.//SYSIN DD *\n SORT FIELDS=COPY\n JOINKEYS FILES=F1, FIELDS=(1, 10, A)\n JOINKEYS FILES=F2, FIELDS=(1, 10, A)\n JOIN UNPAIRED, F2, ONLY\n REFORMAT FIELDS=(F2:1, 9)\n/*"
},
{
"code": null,
"e": 6519,
"s": 6322,
"text": "//SYSIN DD *\n SORT FIELDS=COPY\n JOINKEYS FILES=F1, FIELDS=(1, 10, A)\n JOINKEYS FILES=F2, FIELDS=(1, 10, A)\n JOIN UNPAIRED, F2, ONLY\n REFORMAT FIELDS=(F2:1, 9)\n/*"
},
{
"code": null,
"e": 6918,
"s": 6519,
"text": "Matched Records and Non Matched Records from both files –Sort card to retain unpaired records from both F1 and F2 files along with paired records. This type of join is called as FULL OUTER JOIN.//SYSIN DD *\n SORT FIELDS=COPY\n JOINKEYS FILES=F1, FIELDS=(1, 10, A)\n JOINKEYS FILES=F2, FIELDS=(1, 10, A)\n JOIN UNPAIRED, F1, F2\n REFORMAT FIELDS=(F1:1, 71, F2:1, 9)\n/*"
},
{
"code": null,
"e": 7123,
"s": 6918,
"text": "//SYSIN DD *\n SORT FIELDS=COPY\n JOINKEYS FILES=F1, FIELDS=(1, 10, A)\n JOINKEYS FILES=F2, FIELDS=(1, 10, A)\n JOIN UNPAIRED, F1, F2\n REFORMAT FIELDS=(F1:1, 71, F2:1, 9)\n/*"
},
{
"code": null,
"e": 7457,
"s": 7123,
"text": "Non Matched Records from both files –Sort card to retain only unpaired records from F1 and F2 files.//SYSIN DD *\n SORT FIELDS=COPY\n JOINKEYS FILES=F1, FIELDS=(1, 10, A)\n JOINKEYS FILES=F2, FIELDS=(1, 10, A)\n JOIN UNPAIRED, F1, F2, ONLY or JOIN UNPAIRED, ONLY\n REFORMAT FIELDS=(F1:1, 71, F2:1, 9)\n/*"
},
{
"code": null,
"e": 7691,
"s": 7457,
"text": "//SYSIN DD *\n SORT FIELDS=COPY\n JOINKEYS FILES=F1, FIELDS=(1, 10, A)\n JOINKEYS FILES=F2, FIELDS=(1, 10, A)\n JOIN UNPAIRED, F1, F2, ONLY or JOIN UNPAIRED, ONLY\n REFORMAT FIELDS=(F1:1, 71, F2:1, 9)\n/*"
},
{
"code": null,
"e": 7696,
"s": 7691,
"text": "DBMS"
},
{
"code": null,
"e": 7712,
"s": 7696,
"text": "Write From Home"
},
{
"code": null,
"e": 7717,
"s": 7712,
"text": "DBMS"
}
] |
Python | Count overlapping substring in a given string
|
20 Apr, 2020
Given a string and a sub-string, the task is to get the count of overlapping substring from the given string.
Note that in Python, the count() function returns the number of substrings in a given string, but it does not give correct results when two occurrences of the substring overlap. Consider this example –
string = "GeeksforGeeksforGeeksforGeeks" print(string.count("GeeksforGeeks"))
Output:
2
The output we got here is 2, but the expected output is 3 since we also wanted to count the occurrence of overlapped sub-string.
In order to solve this problem, we can use find() function in Python. It returns the start position of the first occurrence of substring in the given string, then we increment this position by 1 and continue the search from that position till the end of the string.
Below is the implementation –
def CountOccurrences(string, substring): # Initialize count and start to 0 count = 0 start = 0 # Search through the string till # we reach the end of it while start < len(string): # Check if a substring is present from # 'start' position till the end pos = string.find(substring, start) if pos != -1: # If a substring is present, move 'start' to # the next position from start of the substring start = pos + 1 # Increment the count count += 1 else: # If no further substring is present break # return the value of count return count # Driver Codestring = "GeeksforGeeksforGeeksforGeeks"print(CountOccurrences(string, "GeeksforGeeks"))
3
prituladima
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
Different ways to create Pandas Dataframe
How to Install PIP on Windows ?
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Apr, 2020"
},
{
"code": null,
"e": 138,
"s": 28,
"text": "Given a string and a sub-string, the task is to get the count of overlapping substring from the given string."
},
{
"code": null,
"e": 340,
"s": 138,
"text": "Note that in Python, the count() function returns the number of substrings in a given string, but it does not give correct results when two occurrences of the substring overlap. Consider this example –"
},
{
"code": "string = \"GeeksforGeeksforGeeksforGeeks\" print(string.count(\"GeeksforGeeks\"))",
"e": 419,
"s": 340,
"text": null
},
{
"code": null,
"e": 427,
"s": 419,
"text": "Output:"
},
{
"code": null,
"e": 429,
"s": 427,
"text": "2"
},
{
"code": null,
"e": 558,
"s": 429,
"text": "The output we got here is 2, but the expected output is 3 since we also wanted to count the occurrence of overlapped sub-string."
},
{
"code": null,
"e": 824,
"s": 558,
"text": "In order to solve this problem, we can use find() function in Python. It returns the start position of the first occurrence of substring in the given string, then we increment this position by 1 and continue the search from that position till the end of the string."
},
{
"code": null,
"e": 854,
"s": 824,
"text": "Below is the implementation –"
},
{
"code": "def CountOccurrences(string, substring): # Initialize count and start to 0 count = 0 start = 0 # Search through the string till # we reach the end of it while start < len(string): # Check if a substring is present from # 'start' position till the end pos = string.find(substring, start) if pos != -1: # If a substring is present, move 'start' to # the next position from start of the substring start = pos + 1 # Increment the count count += 1 else: # If no further substring is present break # return the value of count return count # Driver Codestring = \"GeeksforGeeksforGeeksforGeeks\"print(CountOccurrences(string, \"GeeksforGeeks\"))",
"e": 1636,
"s": 854,
"text": null
},
{
"code": null,
"e": 1639,
"s": 1636,
"text": "3\n"
},
{
"code": null,
"e": 1651,
"s": 1639,
"text": "prituladima"
},
{
"code": null,
"e": 1674,
"s": 1651,
"text": "Python string-programs"
},
{
"code": null,
"e": 1681,
"s": 1674,
"text": "Python"
},
{
"code": null,
"e": 1697,
"s": 1681,
"text": "Python Programs"
},
{
"code": null,
"e": 1795,
"s": 1697,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1813,
"s": 1795,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1835,
"s": 1813,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1877,
"s": 1835,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1909,
"s": 1877,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1935,
"s": 1909,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1978,
"s": 1935,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2000,
"s": 1978,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2039,
"s": 2000,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2077,
"s": 2039,
"text": "Python | Convert a list to dictionary"
}
] |
How to create a div that contains multiple fixed-size images ?
|
14 Jan, 2021
What is a <div> tag ?
A <div> tag can be defined as a divider of two blocks of HTML code. It is used as a container for HTML elements which can then be styled with CSS or Javascript. Class or id attribute can be used to easily style the element in the <div> tag.
Please read more about <div> tag from this article : https://www.geeksforgeeks.org/div-tag-html/
An example on how to use a <div> tag:
HTML
<!DOCTYPE html><html> <head> <style> .firstDiv { border: 5px outset black; background-color: green; text-align: center; } </style></head> <body> <div class="firstDiv"> <h2>Hello Geek!</h2> <p>How was your day like?</p> </div></body> </html>
Output:
Create a <div> that contains multiple fixed size images:
Approach:
First, create the <div> tag as mentioned in the previous example and insert multiple images inside a common <div> tag so that all the images have a separate <div> tag and a class name.
The following example shows how to make a <div> tag that contains multiple fixed-size images:
HTML
<!DOCTYPE html><html> <head> <style> .images { display: flex; flex-wrap: wrap; margin: 0 50px; padding: 30px; } .photo { max-width: 31.333%; padding: 0 10px; height: 240px; } .photo img { width: 100%; height: 100%; } </style></head> <body> <div class="images"> <div class="photo"> <img src="tom1.jpg" alt="photo" /> </div> <div class="photo"> <img src="tom2.jpg" alt="photo" /> </div> <div class="photo"> <img src="tom3.jpg" alt="photo" /> </div> </div></body> </html>
Explanation: In the above code, we have created a main container <div> class of “images” which is used to store all the images and each image has its own container <div> class of “photo” which can be later used to add special CSS properties to the images.
Images shown are contained in <div> tag of class=”images”
CSS-Misc
HTML-Misc
Picked
Technical Scripter 2020
CSS
HTML
Technical Scripter
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n14 Jan, 2021"
},
{
"code": null,
"e": 76,
"s": 54,
"text": "What is a <div> tag ?"
},
{
"code": null,
"e": 317,
"s": 76,
"text": "A <div> tag can be defined as a divider of two blocks of HTML code. It is used as a container for HTML elements which can then be styled with CSS or Javascript. Class or id attribute can be used to easily style the element in the <div> tag."
},
{
"code": null,
"e": 414,
"s": 317,
"text": "Please read more about <div> tag from this article : https://www.geeksforgeeks.org/div-tag-html/"
},
{
"code": null,
"e": 452,
"s": 414,
"text": "An example on how to use a <div> tag:"
},
{
"code": null,
"e": 457,
"s": 452,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> .firstDiv { border: 5px outset black; background-color: green; text-align: center; } </style></head> <body> <div class=\"firstDiv\"> <h2>Hello Geek!</h2> <p>How was your day like?</p> </div></body> </html>",
"e": 776,
"s": 457,
"text": null
},
{
"code": null,
"e": 784,
"s": 776,
"text": "Output:"
},
{
"code": null,
"e": 841,
"s": 784,
"text": "Create a <div> that contains multiple fixed size images:"
},
{
"code": null,
"e": 851,
"s": 841,
"text": "Approach:"
},
{
"code": null,
"e": 1037,
"s": 851,
"text": "First, create the <div> tag as mentioned in the previous example and insert multiple images inside a common <div> tag so that all the images have a separate <div> tag and a class name. "
},
{
"code": null,
"e": 1131,
"s": 1037,
"text": "The following example shows how to make a <div> tag that contains multiple fixed-size images:"
},
{
"code": null,
"e": 1136,
"s": 1131,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> .images { display: flex; flex-wrap: wrap; margin: 0 50px; padding: 30px; } .photo { max-width: 31.333%; padding: 0 10px; height: 240px; } .photo img { width: 100%; height: 100%; } </style></head> <body> <div class=\"images\"> <div class=\"photo\"> <img src=\"tom1.jpg\" alt=\"photo\" /> </div> <div class=\"photo\"> <img src=\"tom2.jpg\" alt=\"photo\" /> </div> <div class=\"photo\"> <img src=\"tom3.jpg\" alt=\"photo\" /> </div> </div></body> </html>",
"e": 1852,
"s": 1136,
"text": null
},
{
"code": null,
"e": 2108,
"s": 1852,
"text": "Explanation: In the above code, we have created a main container <div> class of “images” which is used to store all the images and each image has its own container <div> class of “photo” which can be later used to add special CSS properties to the images."
},
{
"code": null,
"e": 2166,
"s": 2108,
"text": "Images shown are contained in <div> tag of class=”images”"
},
{
"code": null,
"e": 2175,
"s": 2166,
"text": "CSS-Misc"
},
{
"code": null,
"e": 2185,
"s": 2175,
"text": "HTML-Misc"
},
{
"code": null,
"e": 2192,
"s": 2185,
"text": "Picked"
},
{
"code": null,
"e": 2216,
"s": 2192,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 2220,
"s": 2216,
"text": "CSS"
},
{
"code": null,
"e": 2225,
"s": 2220,
"text": "HTML"
},
{
"code": null,
"e": 2244,
"s": 2225,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2261,
"s": 2244,
"text": "Web Technologies"
},
{
"code": null,
"e": 2266,
"s": 2261,
"text": "HTML"
}
] |
FCFS Disk Scheduling Algorithms
|
28 May, 2021
Prerequisite: Disk scheduling algorithms.Given an array of disk track numbers and initial head position, our task is to find the total number of seek operations done to access all the requested tracks if First Come First Serve (FCFS) disk scheduling algorithm is used.
First Come First Serve (FCFS) FCFS is the simplest disk scheduling algorithm. As the name suggests, this algorithm entertains requests in the order they arrive in the disk queue. The algorithm looks very fair and there is no starvation (all requests are serviced sequentially) but generally, it does not provide the fastest service.
Algorithm:
Let Request array represents an array storing indexes of tracks that have been requested in ascending order of their time of arrival. ‘head’ is the position of disk head.Let us one by one take the tracks in default order and calculate the absolute distance of the track from the head.Increment the total seek count with this distance.Currently serviced track position now becomes the new head position.Go to step 2 until all tracks in request array have not been serviced.
Let Request array represents an array storing indexes of tracks that have been requested in ascending order of their time of arrival. ‘head’ is the position of disk head.
Let us one by one take the tracks in default order and calculate the absolute distance of the track from the head.
Increment the total seek count with this distance.
Currently serviced track position now becomes the new head position.
Go to step 2 until all tracks in request array have not been serviced.
Example:
Input:
Request sequence = {176, 79, 34, 60, 92, 11, 41, 114}
Initial head position = 50
Output:
Total number of seek operations = 510
Seek Sequence is
176
79
34
60
92
11
41
114
The following chart shows the sequence in which requested tracks are serviced using FCFS.
Therefore, the total seek count is calculated as:
= (176-50)+(176-79)+(79-34)+(60-34)+(92-60)+(92-11)+(41-11)+(114-41)
= 510
Implementation: Implementation of FCFS is given below. Note that distance is used to store absolute distance between head and current track position.
C++
Java
Python3
C#
Javascript
// C++ program to demonstrate// FCFS Disk Scheduling algorithm #include <bits/stdc++.h>using namespace std; int size = 8; void FCFS(int arr[], int head){ int seek_count = 0; int distance, cur_track; for (int i = 0; i < size; i++) { cur_track = arr[i]; // calculate absolute distance distance = abs(cur_track - head); // increase the total count seek_count += distance; // accessed track is now new head head = cur_track; } cout << "Total number of seek operations = " << seek_count << endl; // Seek sequence would be the same // as request array sequence cout << "Seek Sequence is" << endl; for (int i = 0; i < size; i++) { cout << arr[i] << endl; }} // Driver codeint main(){ // request array int arr[size] = { 176, 79, 34, 60, 92, 11, 41, 114 }; int head = 50; FCFS(arr, head); return 0;}
// Java program to demonstrate// FCFS Disk Scheduling algorithmclass GFG{static int size = 8; static void FCFS(int arr[], int head){ int seek_count = 0; int distance, cur_track; for (int i = 0; i < size; i++) { cur_track = arr[i]; // calculate absolute distance distance = Math.abs(cur_track - head); // increase the total count seek_count += distance; // accessed track is now new head head = cur_track; } System.out.println("Total number of " + "seek operations = " + seek_count); // Seek sequence would be the same // as request array sequence System.out.println("Seek Sequence is"); for (int i = 0; i < size; i++) { System.out.println(arr[i]); }} // Driver codepublic static void main(String[] args){ // request array int arr[] = { 176, 79, 34, 60, 92, 11, 41, 114 }; int head = 50; FCFS(arr, head);}} // This code is contributed by 29AjayKumar
# Python program to demonstrate# FCFS Disk Scheduling algorithm size = 8; def FCFS(arr, head): seek_count = 0; distance, cur_track = 0, 0; for i in range(size): cur_track = arr[i]; # calculate absolute distance distance = abs(cur_track - head); # increase the total count seek_count += distance; # accessed track is now new head head = cur_track; print("Total number of seek operations = ", seek_count); # Seek sequence would be the same # as request array sequence print("Seek Sequence is"); for i in range(size): print(arr[i]); # Driver codeif __name__ == '__main__': # request array arr = [ 176, 79, 34, 60, 92, 11, 41, 114 ]; head = 50; FCFS(arr, head); # This code contributed by Rajput-Ji
// C# program to demonstrate// FCFS Disk Scheduling algorithmusing System; class GFG{static int size = 8; static void FCFS(int []arr, int head){ int seek_count = 0; int distance, cur_track; for (int i = 0; i < size; i++) { cur_track = arr[i]; // calculate absolute distance distance = Math.Abs(cur_track - head); // increase the total count seek_count += distance; // accessed track is now new head head = cur_track; } Console.WriteLine("Total number of " + "seek operations = " + seek_count); // Seek sequence would be the same // as request array sequence Console.WriteLine("Seek Sequence is"); for (int i = 0; i < size; i++) { Console.WriteLine(arr[i]); }} // Driver codepublic static void Main(String[] args){ // request array int []arr = { 176, 79, 34, 60, 92, 11, 41, 114 }; int head = 50; FCFS(arr, head);}} // This code is contributed by PrinciRaj1992
<script> // Javascript program to demonstrate// FCFS Disk Scheduling algorithmvar size = 8; function FCFS(arr, head){ var seek_count = 0; var distance, cur_track; for(var i = 0; i < size; i++) { cur_track = arr[i]; // Calculate absolute distance distance = Math.abs(cur_track - head); // Increase the total count seek_count += distance; // Accessed track is now new head head = cur_track; } document.write("Total number of " + "seek operations = " + seek_count); // Seek sequence would be the same // as request array sequence document.write("<br>Seek Sequence is"); for(var i = 0; i < size; i++) { document.write("<br>" + arr[i]); }} // Driver code // request arrayvar arr = [ 176, 79, 34, 60, 92, 11, 41, 114 ];var head = 50; FCFS(arr, head); // This code is contributed by Amit Katiyar </script>
Total number of seek operations = 510
Seek Sequence is
176
79
34
60
92
11
41
114
mehul_02
29AjayKumar
princiraj1992
Rajput-Ji
itskawal2000
amit143katiyar
Algorithms
Operating Systems
Operating Systems
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 May, 2021"
},
{
"code": null,
"e": 323,
"s": 54,
"text": "Prerequisite: Disk scheduling algorithms.Given an array of disk track numbers and initial head position, our task is to find the total number of seek operations done to access all the requested tracks if First Come First Serve (FCFS) disk scheduling algorithm is used."
},
{
"code": null,
"e": 656,
"s": 323,
"text": "First Come First Serve (FCFS) FCFS is the simplest disk scheduling algorithm. As the name suggests, this algorithm entertains requests in the order they arrive in the disk queue. The algorithm looks very fair and there is no starvation (all requests are serviced sequentially) but generally, it does not provide the fastest service."
},
{
"code": null,
"e": 668,
"s": 656,
"text": "Algorithm: "
},
{
"code": null,
"e": 1141,
"s": 668,
"text": "Let Request array represents an array storing indexes of tracks that have been requested in ascending order of their time of arrival. ‘head’ is the position of disk head.Let us one by one take the tracks in default order and calculate the absolute distance of the track from the head.Increment the total seek count with this distance.Currently serviced track position now becomes the new head position.Go to step 2 until all tracks in request array have not been serviced."
},
{
"code": null,
"e": 1312,
"s": 1141,
"text": "Let Request array represents an array storing indexes of tracks that have been requested in ascending order of their time of arrival. ‘head’ is the position of disk head."
},
{
"code": null,
"e": 1427,
"s": 1312,
"text": "Let us one by one take the tracks in default order and calculate the absolute distance of the track from the head."
},
{
"code": null,
"e": 1478,
"s": 1427,
"text": "Increment the total seek count with this distance."
},
{
"code": null,
"e": 1547,
"s": 1478,
"text": "Currently serviced track position now becomes the new head position."
},
{
"code": null,
"e": 1618,
"s": 1547,
"text": "Go to step 2 until all tracks in request array have not been serviced."
},
{
"code": null,
"e": 1629,
"s": 1618,
"text": "Example: "
},
{
"code": null,
"e": 1808,
"s": 1629,
"text": "Input: \nRequest sequence = {176, 79, 34, 60, 92, 11, 41, 114}\nInitial head position = 50\n\nOutput:\nTotal number of seek operations = 510\nSeek Sequence is\n176\n79\n34\n60\n92\n11\n41\n114"
},
{
"code": null,
"e": 1900,
"s": 1808,
"text": "The following chart shows the sequence in which requested tracks are serviced using FCFS. "
},
{
"code": null,
"e": 1952,
"s": 1900,
"text": "Therefore, the total seek count is calculated as: "
},
{
"code": null,
"e": 2027,
"s": 1952,
"text": "= (176-50)+(176-79)+(79-34)+(60-34)+(92-60)+(92-11)+(41-11)+(114-41)\n= 510"
},
{
"code": null,
"e": 2178,
"s": 2027,
"text": "Implementation: Implementation of FCFS is given below. Note that distance is used to store absolute distance between head and current track position. "
},
{
"code": null,
"e": 2182,
"s": 2178,
"text": "C++"
},
{
"code": null,
"e": 2187,
"s": 2182,
"text": "Java"
},
{
"code": null,
"e": 2195,
"s": 2187,
"text": "Python3"
},
{
"code": null,
"e": 2198,
"s": 2195,
"text": "C#"
},
{
"code": null,
"e": 2209,
"s": 2198,
"text": "Javascript"
},
{
"code": "// C++ program to demonstrate// FCFS Disk Scheduling algorithm #include <bits/stdc++.h>using namespace std; int size = 8; void FCFS(int arr[], int head){ int seek_count = 0; int distance, cur_track; for (int i = 0; i < size; i++) { cur_track = arr[i]; // calculate absolute distance distance = abs(cur_track - head); // increase the total count seek_count += distance; // accessed track is now new head head = cur_track; } cout << \"Total number of seek operations = \" << seek_count << endl; // Seek sequence would be the same // as request array sequence cout << \"Seek Sequence is\" << endl; for (int i = 0; i < size; i++) { cout << arr[i] << endl; }} // Driver codeint main(){ // request array int arr[size] = { 176, 79, 34, 60, 92, 11, 41, 114 }; int head = 50; FCFS(arr, head); return 0;}",
"e": 3119,
"s": 2209,
"text": null
},
{
"code": "// Java program to demonstrate// FCFS Disk Scheduling algorithmclass GFG{static int size = 8; static void FCFS(int arr[], int head){ int seek_count = 0; int distance, cur_track; for (int i = 0; i < size; i++) { cur_track = arr[i]; // calculate absolute distance distance = Math.abs(cur_track - head); // increase the total count seek_count += distance; // accessed track is now new head head = cur_track; } System.out.println(\"Total number of \" + \"seek operations = \" + seek_count); // Seek sequence would be the same // as request array sequence System.out.println(\"Seek Sequence is\"); for (int i = 0; i < size; i++) { System.out.println(arr[i]); }} // Driver codepublic static void main(String[] args){ // request array int arr[] = { 176, 79, 34, 60, 92, 11, 41, 114 }; int head = 50; FCFS(arr, head);}} // This code is contributed by 29AjayKumar",
"e": 4142,
"s": 3119,
"text": null
},
{
"code": "# Python program to demonstrate# FCFS Disk Scheduling algorithm size = 8; def FCFS(arr, head): seek_count = 0; distance, cur_track = 0, 0; for i in range(size): cur_track = arr[i]; # calculate absolute distance distance = abs(cur_track - head); # increase the total count seek_count += distance; # accessed track is now new head head = cur_track; print(\"Total number of seek operations = \", seek_count); # Seek sequence would be the same # as request array sequence print(\"Seek Sequence is\"); for i in range(size): print(arr[i]); # Driver codeif __name__ == '__main__': # request array arr = [ 176, 79, 34, 60, 92, 11, 41, 114 ]; head = 50; FCFS(arr, head); # This code contributed by Rajput-Ji",
"e": 4992,
"s": 4142,
"text": null
},
{
"code": "// C# program to demonstrate// FCFS Disk Scheduling algorithmusing System; class GFG{static int size = 8; static void FCFS(int []arr, int head){ int seek_count = 0; int distance, cur_track; for (int i = 0; i < size; i++) { cur_track = arr[i]; // calculate absolute distance distance = Math.Abs(cur_track - head); // increase the total count seek_count += distance; // accessed track is now new head head = cur_track; } Console.WriteLine(\"Total number of \" + \"seek operations = \" + seek_count); // Seek sequence would be the same // as request array sequence Console.WriteLine(\"Seek Sequence is\"); for (int i = 0; i < size; i++) { Console.WriteLine(arr[i]); }} // Driver codepublic static void Main(String[] args){ // request array int []arr = { 176, 79, 34, 60, 92, 11, 41, 114 }; int head = 50; FCFS(arr, head);}} // This code is contributed by PrinciRaj1992",
"e": 6029,
"s": 4992,
"text": null
},
{
"code": "<script> // Javascript program to demonstrate// FCFS Disk Scheduling algorithmvar size = 8; function FCFS(arr, head){ var seek_count = 0; var distance, cur_track; for(var i = 0; i < size; i++) { cur_track = arr[i]; // Calculate absolute distance distance = Math.abs(cur_track - head); // Increase the total count seek_count += distance; // Accessed track is now new head head = cur_track; } document.write(\"Total number of \" + \"seek operations = \" + seek_count); // Seek sequence would be the same // as request array sequence document.write(\"<br>Seek Sequence is\"); for(var i = 0; i < size; i++) { document.write(\"<br>\" + arr[i]); }} // Driver code // request arrayvar arr = [ 176, 79, 34, 60, 92, 11, 41, 114 ];var head = 50; FCFS(arr, head); // This code is contributed by Amit Katiyar </script>",
"e": 6982,
"s": 6029,
"text": null
},
{
"code": null,
"e": 7063,
"s": 6982,
"text": "Total number of seek operations = 510\nSeek Sequence is\n176\n79\n34\n60\n92\n11\n41\n114"
},
{
"code": null,
"e": 7074,
"s": 7065,
"text": "mehul_02"
},
{
"code": null,
"e": 7086,
"s": 7074,
"text": "29AjayKumar"
},
{
"code": null,
"e": 7100,
"s": 7086,
"text": "princiraj1992"
},
{
"code": null,
"e": 7110,
"s": 7100,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 7123,
"s": 7110,
"text": "itskawal2000"
},
{
"code": null,
"e": 7138,
"s": 7123,
"text": "amit143katiyar"
},
{
"code": null,
"e": 7149,
"s": 7138,
"text": "Algorithms"
},
{
"code": null,
"e": 7167,
"s": 7149,
"text": "Operating Systems"
},
{
"code": null,
"e": 7185,
"s": 7167,
"text": "Operating Systems"
},
{
"code": null,
"e": 7196,
"s": 7185,
"text": "Algorithms"
}
] |
What is the difference between getter and setter in JavaScript?
|
When a property is accessed, the value gets through calling a function implicitly. The get keyword is used in JavaScript. An identifier, either a number or a string is allowed for set.
When a property is set, it implicitly calls a function and the value is passed as an argument. With that, the return value is set to the property itself. The set keyword is used in JavaScript. An identifier, either a number or a string is allowed for set.
Here’s an example showing how to implement both getter and setter
Live Demo
<html>
<body>
<script>
var department = {
deptName: "Finance",
deptZone: "South",
deptID: 105,
get details() {
return "Department Details<br>" + "Name: " + this.deptName + " <br>Zone: " + this.deptZone + "<br>ID: " + this.deptID;
},
set details(info) {
var res = info.toString().split(' ');
this.deptName = res[0] || '';
this.deptZone = res[1] || '';
this.deptID = res[2] || '';
}
}
department.details = 'Marketing North 001';
document.write(department.deptName);
document.write(department.deptZone);
document.write(department.deptID);
</script>
</body>
</html>
|
[
{
"code": null,
"e": 1247,
"s": 1062,
"text": "When a property is accessed, the value gets through calling a function implicitly. The get keyword is used in JavaScript. An identifier, either a number or a string is allowed for set."
},
{
"code": null,
"e": 1503,
"s": 1247,
"text": "When a property is set, it implicitly calls a function and the value is passed as an argument. With that, the return value is set to the property itself. The set keyword is used in JavaScript. An identifier, either a number or a string is allowed for set."
},
{
"code": null,
"e": 1569,
"s": 1503,
"text": "Here’s an example showing how to implement both getter and setter"
},
{
"code": null,
"e": 1579,
"s": 1569,
"text": "Live Demo"
},
{
"code": null,
"e": 2372,
"s": 1579,
"text": "<html>\n <body>\n <script>\n var department = {\n deptName: \"Finance\",\n deptZone: \"South\",\n deptID: 105,\n get details() {\n return \"Department Details<br>\" + \"Name: \" + this.deptName + \" <br>Zone: \" + this.deptZone + \"<br>ID: \" + this.deptID;\n },\n set details(info) {\n var res = info.toString().split(' ');\n this.deptName = res[0] || '';\n this.deptZone = res[1] || '';\n this.deptID = res[2] || '';\n }\n }\n department.details = 'Marketing North 001';\n document.write(department.deptName);\n document.write(department.deptZone);\n document.write(department.deptID);\n </script>\n </body>\n</html>"
}
] |
Python - end parameter in print()
|
The print() function in python always creates a newline. But there is also a parameter for this function which can put other characters instead of new line at the end. In this article we will explore various options for this parameter.
In the below example we see various ways we can assign values to the end parameter and see the result from it.
Live Demo
print("Welcome to ")
print("Tutorialspoint")
print("Welcome to ", end = ' ')
print("Tutorialspoint")
print("emailid",end='@')
print("tutorialspoint.com")
Running the above code gives us the following result −
Welcome to
Tutorialspoint
Welcome to Tutorialspoint
emailid@tutorialspoint.com
|
[
{
"code": null,
"e": 1298,
"s": 1062,
"text": "The print() function in python always creates a newline. But there is also a parameter for this function which can put other characters instead of new line at the end. In this article we will explore various options for this parameter."
},
{
"code": null,
"e": 1409,
"s": 1298,
"text": "In the below example we see various ways we can assign values to the end parameter and see the result from it."
},
{
"code": null,
"e": 1420,
"s": 1409,
"text": " Live Demo"
},
{
"code": null,
"e": 1576,
"s": 1420,
"text": "print(\"Welcome to \")\nprint(\"Tutorialspoint\")\n\nprint(\"Welcome to \", end = ' ')\nprint(\"Tutorialspoint\")\n\nprint(\"emailid\",end='@')\nprint(\"tutorialspoint.com\")"
},
{
"code": null,
"e": 1631,
"s": 1576,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 1710,
"s": 1631,
"text": "Welcome to\nTutorialspoint\nWelcome to Tutorialspoint\nemailid@tutorialspoint.com"
}
] |
Haskell - Basic Data Models
|
Haskell is a purely functional programing language, hence it is much more interactive and intelligent than other programming languages. In this chapter, we will learn about basic data models of Haskell which are actually predefined or somehow intelligently decoded into the computer memory.
Throughout this tutorial, we will use the Haskell online platform available on our website (https://www.tutorialspoint.com/codingground.htm).
Haskell is intelligent enough to decode some number as a number. Therefore, you need not mention its type externally as we usually do in case of other programing languages. As per example go to your prelude command prompt and just run "2+2" and hit enter.
sh-4.3$ ghci
GHCi, version 7.6.3: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Prelude> 2+2
You will receive the following output as a result.
4
In the above code, we just passed two numbers as arguments to the GHCI compiler without predefining their type, but compiler could easily decode these two entries as numbers.
Now, let us try a little more complex mathematical calculation and see whether our intelligent compiler give us the correct output or not. Try with "15+(5*5)-40"
Prelude> 15+(5*5)-40
The above expression yields "0" as per the expected output.
0
Like numbers, Haskell can intelligently identify a character given in as an input to it. Go to your Haskell command prompt and type any character with double or single quotation.
Let us provide following line as input and check its output.
Prelude> :t "a"
It will produce the following output −
"a" :: [Char]
Remember you use (:t) while supplying the input. In the above example, (:t) is to include the specific type related to the inputs. We will learn more about this type in the upcoming chapters.
Take a look at the following example where we are passing some invalid input as a char which in turn leads to an error.
Prelude> :t a
<interactive>:1:1: Not in scope: 'a'
Prelude> a
<interactive>:4:1: Not in scope: 'a'
By the error message "<interactive>:4:1: Not in scope: `a'" the Haskell compiler is warning us that it is not able to recognize your input. Haskell is a type of language where everything is represented using a number.
Haskell follows conventional ASCII encoding style. Let us take a look at the following example to understand more −
Prelude> '\97'
'a'
Prelude> '\67'
'C'
Look how your input gets decoded into ASCII format.
A string is nothing but a collection of characters. There is no specific syntax for using string, but Haskell follows the conventional style of representing a string with double quotation.
Take a look at the following example where we are passing the string “Tutorialspoint.com”.
Prelude> :t "tutorialspoint.com"
It will produce the following output on screen −
"tutorialspoint.com" :: [Char]
See how the entire string has been decoded as an array of Char only. Let us move to the other data type and its syntax. Once we start our actual practice, we will be habituated with all the data type and its use.
Boolean data type is also pretty much straightforward like other data type. Look at the following example where we will use different Boolean operations using some Boolean inputs such as "True" or "False".
Prelude> True && True
True
Prelude> True && False
False
Prelude> True || True
True
Prelude> True || False
True
In the above example, we need not mention that "True" and "False" are the Boolean values. Haskell itself can decode it and do the respective operations. Let us modify our inputs with "true" or "false".
Prelude> true
It will produce the following output −
<interactive>:9:1: Not in scope: 'true'
In the above example, Haskell could not differentiate between "true" and a number value, hence our input "true" is not a number. Hence, the Haskell compiler throws an error stating that our input is not its scope.
Like other data types, List is also a very useful data type used in Haskell. As per example, [a,b,c] is a list of characters, hence, by definition, List is a collection of same data type separated by comma.
Like other data types, you need not declare a List as a List. Haskell is intelligent enough to decode your input by looking at the syntax used in the expression.
Take a look at the following example which shows how Haskell treats a List.
Prelude> [1,2,3,4,5]
It will produce the following output −
[1,2,3,4,5]
Lists in Haskell are homogeneous in nature, which means they won’t allow you to declare a list of different kind of data type. Any list like [1,2,3,4,5,a,b,c,d,e,f] will produce an error.
Prelude> [1,2,3,4,5,a,b,c,d,e,f]
This code will produce the following error −
<interactive>:17:12: Not in scope: 'a'
<interactive>:17:14: Not in scope: 'b'
<interactive>:17:16: Not in scope: 'c'
<interactive>:17:18: Not in scope: 'd'
<interactive>:17:20: Not in scope: 'e'
<interactive>:17:22: Not in scope: 'f'
List comprehension is the process of generating a list using mathematical expression. Look at the following example where we are generating a list using mathematical expression in the format of [output | range ,condition].
Prelude> [x*2| x<-[1..10]]
[2,4,6,8,10,12,14,16,18,20]
Prelude> [x*2| x<-[1..5]]
[2,4,6,8,10]
Prelude> [x| x<-[1..5]]
[1,2,3,4,5]
This method of creating one List using mathematical expression is called as List Comprehension.
Haskell provides another way to declare multiple values in a single data type. It is known as Tuple. A Tuple can be considered as a List, however there are some technical differences in between a Tuple and a List.
A Tuple is an immutable data type, as we cannot modify the number of elements at runtime, whereas a List is a mutable data type.
On the other hand, List is a homogeneous data type, but Tuple is heterogeneous in nature, because a Tuple may contain different type of data inside it.
Tuples are represented by single parenthesis. Take a look at the following example to see how Haskell treats a Tuple.
Prelude> (1,1,'a')
It will produce the following output −
(1,1,'a')
In the above example, we have used one Tuple with two number type variables, and a char type variable.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2206,
"s": 1915,
"text": "Haskell is a purely functional programing language, hence it is much more interactive and intelligent than other programming languages. In this chapter, we will learn about basic data models of Haskell which are actually predefined or somehow intelligently decoded into the computer memory."
},
{
"code": null,
"e": 2348,
"s": 2206,
"text": "Throughout this tutorial, we will use the Haskell online platform available on our website (https://www.tutorialspoint.com/codingground.htm)."
},
{
"code": null,
"e": 2604,
"s": 2348,
"text": "Haskell is intelligent enough to decode some number as a number. Therefore, you need not mention its type externally as we usually do in case of other programing languages. As per example go to your prelude command prompt and just run \"2+2\" and hit enter."
},
{
"code": null,
"e": 2838,
"s": 2604,
"text": "sh-4.3$ ghci \nGHCi, version 7.6.3: http://www.haskell.org/ghc/ :? for help \nLoading package ghc-prim ... linking ... done. \nLoading package integer-gmp ... linking ... done. \nLoading package base ... linking ... done. \nPrelude> 2+2\n"
},
{
"code": null,
"e": 2889,
"s": 2838,
"text": "You will receive the following output as a result."
},
{
"code": null,
"e": 2892,
"s": 2889,
"text": "4\n"
},
{
"code": null,
"e": 3067,
"s": 2892,
"text": "In the above code, we just passed two numbers as arguments to the GHCI compiler without predefining their type, but compiler could easily decode these two entries as numbers."
},
{
"code": null,
"e": 3229,
"s": 3067,
"text": "Now, let us try a little more complex mathematical calculation and see whether our intelligent compiler give us the correct output or not. Try with \"15+(5*5)-40\""
},
{
"code": null,
"e": 3252,
"s": 3229,
"text": "Prelude> 15+(5*5)-40 \n"
},
{
"code": null,
"e": 3312,
"s": 3252,
"text": "The above expression yields \"0\" as per the expected output."
},
{
"code": null,
"e": 3315,
"s": 3312,
"text": "0\n"
},
{
"code": null,
"e": 3494,
"s": 3315,
"text": "Like numbers, Haskell can intelligently identify a character given in as an input to it. Go to your Haskell command prompt and type any character with double or single quotation."
},
{
"code": null,
"e": 3555,
"s": 3494,
"text": "Let us provide following line as input and check its output."
},
{
"code": null,
"e": 3573,
"s": 3555,
"text": "Prelude> :t \"a\" \n"
},
{
"code": null,
"e": 3612,
"s": 3573,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 3628,
"s": 3612,
"text": "\"a\" :: [Char] \n"
},
{
"code": null,
"e": 3820,
"s": 3628,
"text": "Remember you use (:t) while supplying the input. In the above example, (:t) is to include the specific type related to the inputs. We will learn more about this type in the upcoming chapters."
},
{
"code": null,
"e": 3940,
"s": 3820,
"text": "Take a look at the following example where we are passing some invalid input as a char which in turn leads to an error."
},
{
"code": null,
"e": 4045,
"s": 3940,
"text": "Prelude> :t a \n<interactive>:1:1: Not in scope: 'a' \n\nPrelude> a \n<interactive>:4:1: Not in scope: 'a' "
},
{
"code": null,
"e": 4263,
"s": 4045,
"text": "By the error message \"<interactive>:4:1: Not in scope: `a'\" the Haskell compiler is warning us that it is not able to recognize your input. Haskell is a type of language where everything is represented using a number."
},
{
"code": null,
"e": 4379,
"s": 4263,
"text": "Haskell follows conventional ASCII encoding style. Let us take a look at the following example to understand more −"
},
{
"code": null,
"e": 4422,
"s": 4379,
"text": "Prelude> '\\97' \n'a' \nPrelude> '\\67' \n'C' "
},
{
"code": null,
"e": 4474,
"s": 4422,
"text": "Look how your input gets decoded into ASCII format."
},
{
"code": null,
"e": 4663,
"s": 4474,
"text": "A string is nothing but a collection of characters. There is no specific syntax for using string, but Haskell follows the conventional style of representing a string with double quotation."
},
{
"code": null,
"e": 4754,
"s": 4663,
"text": "Take a look at the following example where we are passing the string “Tutorialspoint.com”."
},
{
"code": null,
"e": 4788,
"s": 4754,
"text": "Prelude> :t \"tutorialspoint.com\" "
},
{
"code": null,
"e": 4837,
"s": 4788,
"text": "It will produce the following output on screen −"
},
{
"code": null,
"e": 4870,
"s": 4837,
"text": "\"tutorialspoint.com\" :: [Char] \n"
},
{
"code": null,
"e": 5083,
"s": 4870,
"text": "See how the entire string has been decoded as an array of Char only. Let us move to the other data type and its syntax. Once we start our actual practice, we will be habituated with all the data type and its use."
},
{
"code": null,
"e": 5289,
"s": 5083,
"text": "Boolean data type is also pretty much straightforward like other data type. Look at the following example where we will use different Boolean operations using some Boolean inputs such as \"True\" or \"False\"."
},
{
"code": null,
"e": 5411,
"s": 5289,
"text": "Prelude> True && True \nTrue \nPrelude> True && False \nFalse \nPrelude> True || True \nTrue \nPrelude> True || False \nTrue"
},
{
"code": null,
"e": 5613,
"s": 5411,
"text": "In the above example, we need not mention that \"True\" and \"False\" are the Boolean values. Haskell itself can decode it and do the respective operations. Let us modify our inputs with \"true\" or \"false\"."
},
{
"code": null,
"e": 5628,
"s": 5613,
"text": "Prelude> true "
},
{
"code": null,
"e": 5667,
"s": 5628,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 5709,
"s": 5667,
"text": "<interactive>:9:1: Not in scope: 'true' \n"
},
{
"code": null,
"e": 5923,
"s": 5709,
"text": "In the above example, Haskell could not differentiate between \"true\" and a number value, hence our input \"true\" is not a number. Hence, the Haskell compiler throws an error stating that our input is not its scope."
},
{
"code": null,
"e": 6130,
"s": 5923,
"text": "Like other data types, List is also a very useful data type used in Haskell. As per example, [a,b,c] is a list of characters, hence, by definition, List is a collection of same data type separated by comma."
},
{
"code": null,
"e": 6292,
"s": 6130,
"text": "Like other data types, you need not declare a List as a List. Haskell is intelligent enough to decode your input by looking at the syntax used in the expression."
},
{
"code": null,
"e": 6368,
"s": 6292,
"text": "Take a look at the following example which shows how Haskell treats a List."
},
{
"code": null,
"e": 6390,
"s": 6368,
"text": "Prelude> [1,2,3,4,5] "
},
{
"code": null,
"e": 6429,
"s": 6390,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 6443,
"s": 6429,
"text": "[1,2,3,4,5] \n"
},
{
"code": null,
"e": 6631,
"s": 6443,
"text": "Lists in Haskell are homogeneous in nature, which means they won’t allow you to declare a list of different kind of data type. Any list like [1,2,3,4,5,a,b,c,d,e,f] will produce an error."
},
{
"code": null,
"e": 6665,
"s": 6631,
"text": "Prelude> [1,2,3,4,5,a,b,c,d,e,f] "
},
{
"code": null,
"e": 6710,
"s": 6665,
"text": "This code will produce the following error −"
},
{
"code": null,
"e": 6950,
"s": 6710,
"text": "<interactive>:17:12: Not in scope: 'a' \n<interactive>:17:14: Not in scope: 'b' \n<interactive>:17:16: Not in scope: 'c' \n<interactive>:17:18: Not in scope: 'd' \n<interactive>:17:20: Not in scope: 'e' \n<interactive>:17:22: Not in scope: 'f'\n"
},
{
"code": null,
"e": 7173,
"s": 6950,
"text": "List comprehension is the process of generating a list using mathematical expression. Look at the following example where we are generating a list using mathematical expression in the format of [output | range ,condition]."
},
{
"code": null,
"e": 7310,
"s": 7173,
"text": "Prelude> [x*2| x<-[1..10]] \n[2,4,6,8,10,12,14,16,18,20] \nPrelude> [x*2| x<-[1..5]] \n[2,4,6,8,10] \nPrelude> [x| x<-[1..5]] \n[1,2,3,4,5]"
},
{
"code": null,
"e": 7406,
"s": 7310,
"text": "This method of creating one List using mathematical expression is called as List Comprehension."
},
{
"code": null,
"e": 7620,
"s": 7406,
"text": "Haskell provides another way to declare multiple values in a single data type. It is known as Tuple. A Tuple can be considered as a List, however there are some technical differences in between a Tuple and a List."
},
{
"code": null,
"e": 7749,
"s": 7620,
"text": "A Tuple is an immutable data type, as we cannot modify the number of elements at runtime, whereas a List is a mutable data type."
},
{
"code": null,
"e": 7901,
"s": 7749,
"text": "On the other hand, List is a homogeneous data type, but Tuple is heterogeneous in nature, because a Tuple may contain different type of data inside it."
},
{
"code": null,
"e": 8019,
"s": 7901,
"text": "Tuples are represented by single parenthesis. Take a look at the following example to see how Haskell treats a Tuple."
},
{
"code": null,
"e": 8039,
"s": 8019,
"text": "Prelude> (1,1,'a') "
},
{
"code": null,
"e": 8078,
"s": 8039,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 8090,
"s": 8078,
"text": "(1,1,'a') \n"
},
{
"code": null,
"e": 8193,
"s": 8090,
"text": "In the above example, we have used one Tuple with two number type variables, and a char type variable."
},
{
"code": null,
"e": 8200,
"s": 8193,
"text": " Print"
},
{
"code": null,
"e": 8211,
"s": 8200,
"text": " Add Notes"
}
] |
Simple Guide to Data Cleaning with Python | by June Tao Ching | Towards Data Science
|
Data cleaning is the most crucial step in any project, if we do not take care of it properly, it might lead us to a completely different conclusion. Often than not, we might spend half of the time cleaning our data in most projects.
In this article, I am going to share some Python functions that can help us in data cleaning especially in:
Dropping unused column
Removing duplicate
Mapping of data
Dealing with null data
We are going to use pandas in this project, let’s install the package if we do not have it.
conda install pandas
I have modified the famous titanic dataset from Kaggle for demo purpose, you can download the dataset here.
Let’s import the package and read the dataset.
df.head() will display the first 5 rows of the dataframe, you can quickly take a glance at the dataset by using this function.
Based on our observation, there is an invalid/null Unnamed: 13 column that we do not need. We can drop it by using the function below.
If you wish to drop multiple columns, an array is needed to pass in columns parameter.
inplace = True will do the operation directly on the dataframe itself, by default it will create another copy and you have to assign it to the dataframe again like df = df.drop(columns="Unnamed: 13").
Let’s check for duplicates in this dataset by using this function.
df[df.duplicated(keep=False)]
keep allows a few parameters to check on duplicates.
first : Mark duplicates as True except for the first occurrence.
last : Mark duplicates as True except for the last occurrence.
False : Mark all duplicates as True.
In this case, I would like to show all duplicates, so False is passed as the parameter. Now we have seen there are duplicates in this dataset, I would like to remove them and keep the first occurrence. The following function is used to keep the first occurrence.
df = df.drop_duplicates(keep="first")
We can use len(df) or df[df.duplicated(keep=False)] to check if the duplicates are removed. df[df.duplicated(keep=False)] will return null if the duplicates are removed.
With the help of df["Sex"].unique and df["Sex"].hist(), we found out that there are other values such as m, m and F exist in this column. This might due to the wrong input from the data source and we have to assume these values are correct and map to male or female.
df["Sex"] = df["Sex"].map({ "male": "male", "m": "male", "m ": "male", "M": "male", "F": "female", "f": "female", "female": "female"})
The function above is used to map those values to male or female.
Note: please make sure the default values male and female are included in the mapping, else it will become nan after you perform the mapping.
In this column, there are 3 missing values: -, na and NaN. Pandas doesn’t recognize - and na as null. We have to replace them with null before dealing with them.
replace() is used to replace - and na to null.
If we found out this while reading the data, we actually can handle this missing value by passing the missing values to thena_values parameter. The results are the same.
Now we have replaced them with null values, how are we going to do with those missing value?
Solution 1: Drop the observation (row) / feature (column)
If we are sure about the missing data are not useful or the missing data are only a small portion of the data, we can drop the rows that contain missing values.
In statistics, this method is called listwise deletion, it is a method for handling missing data. In this method, an entire record is excluded from analysis if any single value is missing.
If we are confident that this feature (column) does not provide useful information or the missing value percentage is high, we can drop the entire column. This is very useful when doing statistical analysis, since filling in the missing values may yield unexpected or biased results.
Solution 2: Impute the missing values
It means to calculate the missing values based on other data. For example, we can compute missing values for age with the date of birth.
In this case, we do not have date of birth, we can replace the missing values with the mean or median (mode for categorical value) of the data.
Note: Mean is most useful when the data is not skewed, while the median is more robust, not sensitive to outliers, and thus used when data is skewed.
Let’s use median to replace the missing value in this case.
df["Age"].median is used to compute the median of the data while fillna is used to replace the missing value with the median.
Now you have learnt how to clean your data in Python with pandas. I hope this article is useful to you. Do drop me a comment if I made any mistakes or typos.
You can view the complete Jupyter notebook in my Github. Cheers!
If you enjoyed reading this piece, you might also enjoy these:
towardsdatascience.com
towardsdatascience.com
You can find links to my other works on Medium and follow me here. Thanks for reading!
|
[
{
"code": null,
"e": 405,
"s": 172,
"text": "Data cleaning is the most crucial step in any project, if we do not take care of it properly, it might lead us to a completely different conclusion. Often than not, we might spend half of the time cleaning our data in most projects."
},
{
"code": null,
"e": 513,
"s": 405,
"text": "In this article, I am going to share some Python functions that can help us in data cleaning especially in:"
},
{
"code": null,
"e": 536,
"s": 513,
"text": "Dropping unused column"
},
{
"code": null,
"e": 555,
"s": 536,
"text": "Removing duplicate"
},
{
"code": null,
"e": 571,
"s": 555,
"text": "Mapping of data"
},
{
"code": null,
"e": 594,
"s": 571,
"text": "Dealing with null data"
},
{
"code": null,
"e": 686,
"s": 594,
"text": "We are going to use pandas in this project, let’s install the package if we do not have it."
},
{
"code": null,
"e": 707,
"s": 686,
"text": "conda install pandas"
},
{
"code": null,
"e": 815,
"s": 707,
"text": "I have modified the famous titanic dataset from Kaggle for demo purpose, you can download the dataset here."
},
{
"code": null,
"e": 862,
"s": 815,
"text": "Let’s import the package and read the dataset."
},
{
"code": null,
"e": 989,
"s": 862,
"text": "df.head() will display the first 5 rows of the dataframe, you can quickly take a glance at the dataset by using this function."
},
{
"code": null,
"e": 1124,
"s": 989,
"text": "Based on our observation, there is an invalid/null Unnamed: 13 column that we do not need. We can drop it by using the function below."
},
{
"code": null,
"e": 1211,
"s": 1124,
"text": "If you wish to drop multiple columns, an array is needed to pass in columns parameter."
},
{
"code": null,
"e": 1412,
"s": 1211,
"text": "inplace = True will do the operation directly on the dataframe itself, by default it will create another copy and you have to assign it to the dataframe again like df = df.drop(columns=\"Unnamed: 13\")."
},
{
"code": null,
"e": 1479,
"s": 1412,
"text": "Let’s check for duplicates in this dataset by using this function."
},
{
"code": null,
"e": 1509,
"s": 1479,
"text": "df[df.duplicated(keep=False)]"
},
{
"code": null,
"e": 1562,
"s": 1509,
"text": "keep allows a few parameters to check on duplicates."
},
{
"code": null,
"e": 1627,
"s": 1562,
"text": "first : Mark duplicates as True except for the first occurrence."
},
{
"code": null,
"e": 1690,
"s": 1627,
"text": "last : Mark duplicates as True except for the last occurrence."
},
{
"code": null,
"e": 1727,
"s": 1690,
"text": "False : Mark all duplicates as True."
},
{
"code": null,
"e": 1990,
"s": 1727,
"text": "In this case, I would like to show all duplicates, so False is passed as the parameter. Now we have seen there are duplicates in this dataset, I would like to remove them and keep the first occurrence. The following function is used to keep the first occurrence."
},
{
"code": null,
"e": 2028,
"s": 1990,
"text": "df = df.drop_duplicates(keep=\"first\")"
},
{
"code": null,
"e": 2198,
"s": 2028,
"text": "We can use len(df) or df[df.duplicated(keep=False)] to check if the duplicates are removed. df[df.duplicated(keep=False)] will return null if the duplicates are removed."
},
{
"code": null,
"e": 2465,
"s": 2198,
"text": "With the help of df[\"Sex\"].unique and df[\"Sex\"].hist(), we found out that there are other values such as m, m and F exist in this column. This might due to the wrong input from the data source and we have to assume these values are correct and map to male or female."
},
{
"code": null,
"e": 2621,
"s": 2465,
"text": "df[\"Sex\"] = df[\"Sex\"].map({ \"male\": \"male\", \"m\": \"male\", \"m \": \"male\", \"M\": \"male\", \"F\": \"female\", \"f\": \"female\", \"female\": \"female\"})"
},
{
"code": null,
"e": 2687,
"s": 2621,
"text": "The function above is used to map those values to male or female."
},
{
"code": null,
"e": 2829,
"s": 2687,
"text": "Note: please make sure the default values male and female are included in the mapping, else it will become nan after you perform the mapping."
},
{
"code": null,
"e": 2991,
"s": 2829,
"text": "In this column, there are 3 missing values: -, na and NaN. Pandas doesn’t recognize - and na as null. We have to replace them with null before dealing with them."
},
{
"code": null,
"e": 3038,
"s": 2991,
"text": "replace() is used to replace - and na to null."
},
{
"code": null,
"e": 3208,
"s": 3038,
"text": "If we found out this while reading the data, we actually can handle this missing value by passing the missing values to thena_values parameter. The results are the same."
},
{
"code": null,
"e": 3301,
"s": 3208,
"text": "Now we have replaced them with null values, how are we going to do with those missing value?"
},
{
"code": null,
"e": 3359,
"s": 3301,
"text": "Solution 1: Drop the observation (row) / feature (column)"
},
{
"code": null,
"e": 3520,
"s": 3359,
"text": "If we are sure about the missing data are not useful or the missing data are only a small portion of the data, we can drop the rows that contain missing values."
},
{
"code": null,
"e": 3709,
"s": 3520,
"text": "In statistics, this method is called listwise deletion, it is a method for handling missing data. In this method, an entire record is excluded from analysis if any single value is missing."
},
{
"code": null,
"e": 3993,
"s": 3709,
"text": "If we are confident that this feature (column) does not provide useful information or the missing value percentage is high, we can drop the entire column. This is very useful when doing statistical analysis, since filling in the missing values may yield unexpected or biased results."
},
{
"code": null,
"e": 4031,
"s": 3993,
"text": "Solution 2: Impute the missing values"
},
{
"code": null,
"e": 4168,
"s": 4031,
"text": "It means to calculate the missing values based on other data. For example, we can compute missing values for age with the date of birth."
},
{
"code": null,
"e": 4312,
"s": 4168,
"text": "In this case, we do not have date of birth, we can replace the missing values with the mean or median (mode for categorical value) of the data."
},
{
"code": null,
"e": 4462,
"s": 4312,
"text": "Note: Mean is most useful when the data is not skewed, while the median is more robust, not sensitive to outliers, and thus used when data is skewed."
},
{
"code": null,
"e": 4522,
"s": 4462,
"text": "Let’s use median to replace the missing value in this case."
},
{
"code": null,
"e": 4648,
"s": 4522,
"text": "df[\"Age\"].median is used to compute the median of the data while fillna is used to replace the missing value with the median."
},
{
"code": null,
"e": 4806,
"s": 4648,
"text": "Now you have learnt how to clean your data in Python with pandas. I hope this article is useful to you. Do drop me a comment if I made any mistakes or typos."
},
{
"code": null,
"e": 4871,
"s": 4806,
"text": "You can view the complete Jupyter notebook in my Github. Cheers!"
},
{
"code": null,
"e": 4934,
"s": 4871,
"text": "If you enjoyed reading this piece, you might also enjoy these:"
},
{
"code": null,
"e": 4957,
"s": 4934,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 4980,
"s": 4957,
"text": "towardsdatascience.com"
}
] |
Bayesian Decision Theory. Oh! What are we if not patterns? | by Shivam Chaudhary | Towards Data Science
|
Oh! What are we if not patterns?
It’s amazing how we perform so many sophisticated tasks easily and yet yearn to teach machines how to do them. Telling the difference between apples and oranges is quite trivial for us but to teach this to someone who only understands ‘0’ and ‘1’ is troublesome. Now what would seem an strenous task can be made easy (or at least, feasible) using a very familiar mathematical formula. But the question is: Is the formula intuitive?
Bayes’ Theorem is like E=mc2 of probability theory. Everyone has seen it but only few understands it. If I had to choose one adjective for it, it’d be revolutionary! It changed the course of many applications we were fiddling with before. But before diving into the nitty dritty of the algorithm, we need to set our fundamentals straight.
P.S.: To explain the concepts I have taken the example of binary classification for the sake of simplicity but without any loss of generality.
Marginal Probability
When we usually talk about probability of an event, it is the marginal probability we are concerned with. In other words, it is the probability of an event irrespective of any other factor/event/circumstance. Basically, you ‘marginalize’ other events and hence the name. It is denoted by P(A) and read as “probability of A”.
Conditional Probability
Conditional probability is when the occurence of an event is wholly or partially affected by other event(s). Alternatively put, it is the probability of occurrence of an event A when an another event B has already taken place. It is denoted by P(A|B) and read as “probability of A given B”.
Joint Probability
Joint probability is calculated when we are interested in the occurrence of two different events simultaneously. It is also often referenced as probability of intersection of two events. It is denoted by P(A, B) and read as “probability of A and B”.
There is a very subtle difference between likelihood and probability and perhaps this is the very reason why people often consider them similar, if not same.
To understand the difference between them, we first need to understand what a model is, more specifically, statistical model.
A model can be viewed as any one of the process, relationship, equation or an approximation to understand and describe the data.
Consider the below graph:
This could be a model as it gives us a ‘description’ of how our data look like. We can see a relationship between the features (x and y) in the above graph i.e., the variation of the features w.r.t each other.
Now, if I try to approximate it with a mathematical equation, I get:
y = 1.3055 * x - 5.703
which when plotted gives:
This equation is also a model as it gives a more concrete description of the data (more specifically the relationship between the features).
A lot of statistics is dedicated to determining if a model is a good or bad approximation of the data.
Now that we have the intuition behind statistical model, we can address the difference between likelihood and probability.
Whenever we calculate the probability of an event in a stochastic process, it depends on the parameters of the model we are using to describe our process. Say, O is an observed outcome of the process and θ be the parameter describing the underlying model. Then the probability we are interested in calculating is denoted by P(O|θ) i.e., “the probability of a particular outcome given the parameter of the model used to describe the process”.
But seldom does it happens that we know the value of θ beforehand. We simply observe O and the goal then is to arrive at an estimate for θ that would be a plausible choice given the observed outcome O. Our best estimate for the parameter is the value which gives the maximum probability for the outcome O to occur. We can then define the likelihood function as L(θ|O) i.e., it is function of θ for the given set of outcomes, and then use it to find the optimal value of the parameter θ.
Graphical explanation:
Consider a Gaussian distribution as shown in above graph. Let X be the random variable for the process in concern. Then,
Probability of the random variable equals x given the underlying model is Gaussian:P(X = x | N(μ, σ)) = 0 # For continous random variable, but can be closely approximated to the dark pink areaProbability of the random variable to be greater than x given the underlying model is Gaussian::P(X > x | N(μ, σ)) = (Pink + Dark Pink) areaLikelihood of the random variable at x:L(N(μ, σ) | X = x) = y
In simple terms, the likelihood is how well the parameters (in this case, μ and σ) of the model (in this case, Gaussian Distribution) describes the outcomes (in this case, X). The model with the optimal parameters maximises the probability. On the other hand, the probability is how probable an event or observation is for the given parameters of the model used.
Now that we have gone through our fundamentals, we can finally dive into the working of Bayes’ Decision Theory.
Bayesian Decision Theory is a fundamental statistical approach to the problem of pattern classification. It is considered as the ideal pattern classifier and often used as the benchmark for other algorithms because its decision rule automatically minimizes its loss function. It might not make much sense right now, so hold on, we’ll unravel it all.
It makes the assumption that the decision problem is posed in probabilistic terms, and that all the relevant probability values are known.
Derivation of Bayes’ Theorem:
We know from the conditional probability:P(A|B) = P(A, B) / P(B)=> P(A, B) = P(A|B) * P(B) ... (i)Similarly,P(A, B) = P(B|A) * P(A) ... (ii)From equation (i) and (ii):P(A|B) * P(B) = P(B|A) * P(A)=> P(A|B) = [P(B|A) * P(A)] / P(B)
For the case of classification, let:
A ≡ ω (state of the nature or the class of an entry)
B ≡ x (input feature vector)
After substituting we get:
P(ω|x) = [P(x|ω) * P(ω)] / P(x)which becomes:P(ω|x) = [p(x|ω) * P(ω)] / p(x)because,* P(ω|x) ≡ called the posterior, it is the probability of the predicted class to be ω for a given entry of feature (x). Analogous to P(O|θ), because the class is the desired outcome to be predicted according to the data distribution (model). Capital 'P' because ω is a discrete random variable.* p(x|ω) ≡ class-conditional probability density function for the feature. We call it likelihood of ω with respect to x, a term chosen to indicate that, other things being equal, the category (or class) for which it is large is more "likely" to be the true category. It is a function of parameters within the parameteric space that describes the probability of obtaining the observed data (x). Small 'P' because x is a continous random variable. We usually assume it to be following Gaussian Distribution.* P(ω) ≡ a priori probability (or simply prior) of class ω. It is usually pre-determined and depends on the external factors. It means how probable the occurence of class ω out of all the classes.* p(x) ≡ called the evidence, it is merely a scaling factor that guarantees that the posterior probabilities sum to one. p(x) = sum(p(x|ω)*P(ω)) over all the classes.
So finally we get the following equation to frame our decision rule:
The above equation is the governing formula for our decision theory. The rule is as follows:
For each sample input, it calculates its posterior and assign it to the class corresponding to the maximum value of the posterior probability.
Mathematically it can be written as:
Now that you know what Bayesian Rule is and how it works, you might be wondering what so special here? Well, the very algorithm is remarkable, owing to its elegance and near ideal results. Bayes’ Decision Theory is considered as a benchmark for other classification algorithms.
Under Bayes’ theorem, no theory is perfect. Rather, it is a work in progress, always subject to further refinement and testing.
Let’s try to understand why is Bayes’ Classifier the best classifier!**
** (provided all the assumptions required by Bayes’ Decision Theory are true)
Let {ω1, ω2, ω3, ..., ωc} be the finite set of c categories and {α1, α2, α3, ..., αa} be the finite set of a possible actions. By an action I refer to a particular decision out of all possible decisions, for example, an action could be assigning an input feature vector to category (hereinafter class) 3 and another could be assigning an input to class 7.
We can generalize our loss function (λ) as follows:
which can be understood as follows:
λ is the loss incurred on assigning a feature vector to class ωi when its true class is ωj. In other words, it is the loss suffered on taking an action α of assigning an input to class ωi when it should have been in class ωj.
For example, in case of binary classification if we take an action of classifying an input feature vector into class 1 when it should have been in class 2, we incur the following loss:
If i = j, then we get a smaller value of the loss as compared to the alternative cases because it corresponds to a correct decision.
But it would be totally naive to accept this as the complete function we seek to find for our loss. As can be seen, the loss is conditional, it depends on the class under concern at any particular time. To understand it better, answer this question:
Will the loss be independent of how probable a class is for an input feature vector?
If you think the answer is ‘yes’, let me explain why the answer is ‘no’!
Say the posterior probability of class 2 is more than that of class 1 for a given feature vector, i.e.,
and let's consider an action of assigning x to class 1.Since λ is the loss associated with one particular action (here, assigning x to class 1) we get its two values:
Now are these two loss values equal?
You cannot answer this question without the knowledge of posterior probabilities. You need to know how likely a class is to be the true class to calculate the associated loss with it. This modifies our loss as follows:
This explains why it is called conditional loss.
λ can be any suitable function. It could be, for example, symmetrical or zero-one function.
Expected loss for a decision:
Now we are in a confortable position to define our expected loss for a particular decision (or action) over all the classes. That is to say, the loss that I would incur after taking a specific action and how it would be affected by the ‘presence’ of all the classes and not just the true class.
We can minimize our expected loss by selecting the action that minimizes the conditional risk. We shall now show that this Bayes decision procedure actually provides the optimal performance.
Our problem is to find a decision rule that minimizes the overall risk. A general decision rule is a function α(x) that tells us which action to take for every possible observation (x). To be more specific, for every x the decision function α(x) assumes one of the a values α1, α2, α3, ..., αa. Because conditional risk is associated with action αi and because the decision rule specifies the action, the overall risk is given by:
If α(x) is chosen so that conditional risk for each action is minimized, then the overall risk will be minimized too. This justify the Bayes decision rule.
Perhaps an example would be better...
Let λ be symmetrical or zero-one loss function,
Then the conditional risk becomes:
The very decision rule of Bayes’ Classifier automatically minimizes the conditional risk associated with an action.
And that’s Bayes’ Decision Theory!
I hope this article helped you in understanding this algorithm. Feel free to drop your suggestions and queries down below. And if you liked it, smash that clap button!
If you have any topic in mind and would like to see it here, leave it in the comment section. It would be my pleasure!
Godspeed!
(All the images but the thumbnail were created by the author.)
|
[
{
"code": null,
"e": 205,
"s": 172,
"text": "Oh! What are we if not patterns?"
},
{
"code": null,
"e": 637,
"s": 205,
"text": "It’s amazing how we perform so many sophisticated tasks easily and yet yearn to teach machines how to do them. Telling the difference between apples and oranges is quite trivial for us but to teach this to someone who only understands ‘0’ and ‘1’ is troublesome. Now what would seem an strenous task can be made easy (or at least, feasible) using a very familiar mathematical formula. But the question is: Is the formula intuitive?"
},
{
"code": null,
"e": 976,
"s": 637,
"text": "Bayes’ Theorem is like E=mc2 of probability theory. Everyone has seen it but only few understands it. If I had to choose one adjective for it, it’d be revolutionary! It changed the course of many applications we were fiddling with before. But before diving into the nitty dritty of the algorithm, we need to set our fundamentals straight."
},
{
"code": null,
"e": 1119,
"s": 976,
"text": "P.S.: To explain the concepts I have taken the example of binary classification for the sake of simplicity but without any loss of generality."
},
{
"code": null,
"e": 1140,
"s": 1119,
"text": "Marginal Probability"
},
{
"code": null,
"e": 1465,
"s": 1140,
"text": "When we usually talk about probability of an event, it is the marginal probability we are concerned with. In other words, it is the probability of an event irrespective of any other factor/event/circumstance. Basically, you ‘marginalize’ other events and hence the name. It is denoted by P(A) and read as “probability of A”."
},
{
"code": null,
"e": 1489,
"s": 1465,
"text": "Conditional Probability"
},
{
"code": null,
"e": 1780,
"s": 1489,
"text": "Conditional probability is when the occurence of an event is wholly or partially affected by other event(s). Alternatively put, it is the probability of occurrence of an event A when an another event B has already taken place. It is denoted by P(A|B) and read as “probability of A given B”."
},
{
"code": null,
"e": 1798,
"s": 1780,
"text": "Joint Probability"
},
{
"code": null,
"e": 2048,
"s": 1798,
"text": "Joint probability is calculated when we are interested in the occurrence of two different events simultaneously. It is also often referenced as probability of intersection of two events. It is denoted by P(A, B) and read as “probability of A and B”."
},
{
"code": null,
"e": 2206,
"s": 2048,
"text": "There is a very subtle difference between likelihood and probability and perhaps this is the very reason why people often consider them similar, if not same."
},
{
"code": null,
"e": 2332,
"s": 2206,
"text": "To understand the difference between them, we first need to understand what a model is, more specifically, statistical model."
},
{
"code": null,
"e": 2461,
"s": 2332,
"text": "A model can be viewed as any one of the process, relationship, equation or an approximation to understand and describe the data."
},
{
"code": null,
"e": 2487,
"s": 2461,
"text": "Consider the below graph:"
},
{
"code": null,
"e": 2697,
"s": 2487,
"text": "This could be a model as it gives us a ‘description’ of how our data look like. We can see a relationship between the features (x and y) in the above graph i.e., the variation of the features w.r.t each other."
},
{
"code": null,
"e": 2766,
"s": 2697,
"text": "Now, if I try to approximate it with a mathematical equation, I get:"
},
{
"code": null,
"e": 2789,
"s": 2766,
"text": "y = 1.3055 * x - 5.703"
},
{
"code": null,
"e": 2815,
"s": 2789,
"text": "which when plotted gives:"
},
{
"code": null,
"e": 2956,
"s": 2815,
"text": "This equation is also a model as it gives a more concrete description of the data (more specifically the relationship between the features)."
},
{
"code": null,
"e": 3059,
"s": 2956,
"text": "A lot of statistics is dedicated to determining if a model is a good or bad approximation of the data."
},
{
"code": null,
"e": 3182,
"s": 3059,
"text": "Now that we have the intuition behind statistical model, we can address the difference between likelihood and probability."
},
{
"code": null,
"e": 3624,
"s": 3182,
"text": "Whenever we calculate the probability of an event in a stochastic process, it depends on the parameters of the model we are using to describe our process. Say, O is an observed outcome of the process and θ be the parameter describing the underlying model. Then the probability we are interested in calculating is denoted by P(O|θ) i.e., “the probability of a particular outcome given the parameter of the model used to describe the process”."
},
{
"code": null,
"e": 4111,
"s": 3624,
"text": "But seldom does it happens that we know the value of θ beforehand. We simply observe O and the goal then is to arrive at an estimate for θ that would be a plausible choice given the observed outcome O. Our best estimate for the parameter is the value which gives the maximum probability for the outcome O to occur. We can then define the likelihood function as L(θ|O) i.e., it is function of θ for the given set of outcomes, and then use it to find the optimal value of the parameter θ."
},
{
"code": null,
"e": 4134,
"s": 4111,
"text": "Graphical explanation:"
},
{
"code": null,
"e": 4255,
"s": 4134,
"text": "Consider a Gaussian distribution as shown in above graph. Let X be the random variable for the process in concern. Then,"
},
{
"code": null,
"e": 4649,
"s": 4255,
"text": "Probability of the random variable equals x given the underlying model is Gaussian:P(X = x | N(μ, σ)) = 0 # For continous random variable, but can be closely approximated to the dark pink areaProbability of the random variable to be greater than x given the underlying model is Gaussian::P(X > x | N(μ, σ)) = (Pink + Dark Pink) areaLikelihood of the random variable at x:L(N(μ, σ) | X = x) = y"
},
{
"code": null,
"e": 5012,
"s": 4649,
"text": "In simple terms, the likelihood is how well the parameters (in this case, μ and σ) of the model (in this case, Gaussian Distribution) describes the outcomes (in this case, X). The model with the optimal parameters maximises the probability. On the other hand, the probability is how probable an event or observation is for the given parameters of the model used."
},
{
"code": null,
"e": 5124,
"s": 5012,
"text": "Now that we have gone through our fundamentals, we can finally dive into the working of Bayes’ Decision Theory."
},
{
"code": null,
"e": 5474,
"s": 5124,
"text": "Bayesian Decision Theory is a fundamental statistical approach to the problem of pattern classification. It is considered as the ideal pattern classifier and often used as the benchmark for other algorithms because its decision rule automatically minimizes its loss function. It might not make much sense right now, so hold on, we’ll unravel it all."
},
{
"code": null,
"e": 5613,
"s": 5474,
"text": "It makes the assumption that the decision problem is posed in probabilistic terms, and that all the relevant probability values are known."
},
{
"code": null,
"e": 5643,
"s": 5613,
"text": "Derivation of Bayes’ Theorem:"
},
{
"code": null,
"e": 5874,
"s": 5643,
"text": "We know from the conditional probability:P(A|B) = P(A, B) / P(B)=> P(A, B) = P(A|B) * P(B) ... (i)Similarly,P(A, B) = P(B|A) * P(A) ... (ii)From equation (i) and (ii):P(A|B) * P(B) = P(B|A) * P(A)=> P(A|B) = [P(B|A) * P(A)] / P(B)"
},
{
"code": null,
"e": 5911,
"s": 5874,
"text": "For the case of classification, let:"
},
{
"code": null,
"e": 5964,
"s": 5911,
"text": "A ≡ ω (state of the nature or the class of an entry)"
},
{
"code": null,
"e": 5993,
"s": 5964,
"text": "B ≡ x (input feature vector)"
},
{
"code": null,
"e": 6020,
"s": 5993,
"text": "After substituting we get:"
},
{
"code": null,
"e": 7266,
"s": 6020,
"text": "P(ω|x) = [P(x|ω) * P(ω)] / P(x)which becomes:P(ω|x) = [p(x|ω) * P(ω)] / p(x)because,* P(ω|x) ≡ called the posterior, it is the probability of the predicted class to be ω for a given entry of feature (x). Analogous to P(O|θ), because the class is the desired outcome to be predicted according to the data distribution (model). Capital 'P' because ω is a discrete random variable.* p(x|ω) ≡ class-conditional probability density function for the feature. We call it likelihood of ω with respect to x, a term chosen to indicate that, other things being equal, the category (or class) for which it is large is more \"likely\" to be the true category. It is a function of parameters within the parameteric space that describes the probability of obtaining the observed data (x). Small 'P' because x is a continous random variable. We usually assume it to be following Gaussian Distribution.* P(ω) ≡ a priori probability (or simply prior) of class ω. It is usually pre-determined and depends on the external factors. It means how probable the occurence of class ω out of all the classes.* p(x) ≡ called the evidence, it is merely a scaling factor that guarantees that the posterior probabilities sum to one. p(x) = sum(p(x|ω)*P(ω)) over all the classes."
},
{
"code": null,
"e": 7335,
"s": 7266,
"text": "So finally we get the following equation to frame our decision rule:"
},
{
"code": null,
"e": 7428,
"s": 7335,
"text": "The above equation is the governing formula for our decision theory. The rule is as follows:"
},
{
"code": null,
"e": 7571,
"s": 7428,
"text": "For each sample input, it calculates its posterior and assign it to the class corresponding to the maximum value of the posterior probability."
},
{
"code": null,
"e": 7608,
"s": 7571,
"text": "Mathematically it can be written as:"
},
{
"code": null,
"e": 7886,
"s": 7608,
"text": "Now that you know what Bayesian Rule is and how it works, you might be wondering what so special here? Well, the very algorithm is remarkable, owing to its elegance and near ideal results. Bayes’ Decision Theory is considered as a benchmark for other classification algorithms."
},
{
"code": null,
"e": 8014,
"s": 7886,
"text": "Under Bayes’ theorem, no theory is perfect. Rather, it is a work in progress, always subject to further refinement and testing."
},
{
"code": null,
"e": 8086,
"s": 8014,
"text": "Let’s try to understand why is Bayes’ Classifier the best classifier!**"
},
{
"code": null,
"e": 8164,
"s": 8086,
"text": "** (provided all the assumptions required by Bayes’ Decision Theory are true)"
},
{
"code": null,
"e": 8520,
"s": 8164,
"text": "Let {ω1, ω2, ω3, ..., ωc} be the finite set of c categories and {α1, α2, α3, ..., αa} be the finite set of a possible actions. By an action I refer to a particular decision out of all possible decisions, for example, an action could be assigning an input feature vector to category (hereinafter class) 3 and another could be assigning an input to class 7."
},
{
"code": null,
"e": 8572,
"s": 8520,
"text": "We can generalize our loss function (λ) as follows:"
},
{
"code": null,
"e": 8608,
"s": 8572,
"text": "which can be understood as follows:"
},
{
"code": null,
"e": 8834,
"s": 8608,
"text": "λ is the loss incurred on assigning a feature vector to class ωi when its true class is ωj. In other words, it is the loss suffered on taking an action α of assigning an input to class ωi when it should have been in class ωj."
},
{
"code": null,
"e": 9019,
"s": 8834,
"text": "For example, in case of binary classification if we take an action of classifying an input feature vector into class 1 when it should have been in class 2, we incur the following loss:"
},
{
"code": null,
"e": 9152,
"s": 9019,
"text": "If i = j, then we get a smaller value of the loss as compared to the alternative cases because it corresponds to a correct decision."
},
{
"code": null,
"e": 9402,
"s": 9152,
"text": "But it would be totally naive to accept this as the complete function we seek to find for our loss. As can be seen, the loss is conditional, it depends on the class under concern at any particular time. To understand it better, answer this question:"
},
{
"code": null,
"e": 9487,
"s": 9402,
"text": "Will the loss be independent of how probable a class is for an input feature vector?"
},
{
"code": null,
"e": 9560,
"s": 9487,
"text": "If you think the answer is ‘yes’, let me explain why the answer is ‘no’!"
},
{
"code": null,
"e": 9664,
"s": 9560,
"text": "Say the posterior probability of class 2 is more than that of class 1 for a given feature vector, i.e.,"
},
{
"code": null,
"e": 9831,
"s": 9664,
"text": "and let's consider an action of assigning x to class 1.Since λ is the loss associated with one particular action (here, assigning x to class 1) we get its two values:"
},
{
"code": null,
"e": 9868,
"s": 9831,
"text": "Now are these two loss values equal?"
},
{
"code": null,
"e": 10087,
"s": 9868,
"text": "You cannot answer this question without the knowledge of posterior probabilities. You need to know how likely a class is to be the true class to calculate the associated loss with it. This modifies our loss as follows:"
},
{
"code": null,
"e": 10136,
"s": 10087,
"text": "This explains why it is called conditional loss."
},
{
"code": null,
"e": 10228,
"s": 10136,
"text": "λ can be any suitable function. It could be, for example, symmetrical or zero-one function."
},
{
"code": null,
"e": 10258,
"s": 10228,
"text": "Expected loss for a decision:"
},
{
"code": null,
"e": 10553,
"s": 10258,
"text": "Now we are in a confortable position to define our expected loss for a particular decision (or action) over all the classes. That is to say, the loss that I would incur after taking a specific action and how it would be affected by the ‘presence’ of all the classes and not just the true class."
},
{
"code": null,
"e": 10744,
"s": 10553,
"text": "We can minimize our expected loss by selecting the action that minimizes the conditional risk. We shall now show that this Bayes decision procedure actually provides the optimal performance."
},
{
"code": null,
"e": 11175,
"s": 10744,
"text": "Our problem is to find a decision rule that minimizes the overall risk. A general decision rule is a function α(x) that tells us which action to take for every possible observation (x). To be more specific, for every x the decision function α(x) assumes one of the a values α1, α2, α3, ..., αa. Because conditional risk is associated with action αi and because the decision rule specifies the action, the overall risk is given by:"
},
{
"code": null,
"e": 11331,
"s": 11175,
"text": "If α(x) is chosen so that conditional risk for each action is minimized, then the overall risk will be minimized too. This justify the Bayes decision rule."
},
{
"code": null,
"e": 11369,
"s": 11331,
"text": "Perhaps an example would be better..."
},
{
"code": null,
"e": 11417,
"s": 11369,
"text": "Let λ be symmetrical or zero-one loss function,"
},
{
"code": null,
"e": 11452,
"s": 11417,
"text": "Then the conditional risk becomes:"
},
{
"code": null,
"e": 11568,
"s": 11452,
"text": "The very decision rule of Bayes’ Classifier automatically minimizes the conditional risk associated with an action."
},
{
"code": null,
"e": 11603,
"s": 11568,
"text": "And that’s Bayes’ Decision Theory!"
},
{
"code": null,
"e": 11771,
"s": 11603,
"text": "I hope this article helped you in understanding this algorithm. Feel free to drop your suggestions and queries down below. And if you liked it, smash that clap button!"
},
{
"code": null,
"e": 11890,
"s": 11771,
"text": "If you have any topic in mind and would like to see it here, leave it in the comment section. It would be my pleasure!"
},
{
"code": null,
"e": 11900,
"s": 11890,
"text": "Godspeed!"
}
] |
Output of Java program | Set 12(Exception Handling)
|
06 Feb, 2019
Prerequisites : Exception handling , control flow in try-catch-finally1) What is the output of the following program?
public class Test{ public static void main(String[] args) { try { System.out.printf("1"); int sum = 9 / 0; System.out.printf("2"); } catch(ArithmeticException e) { System.out.printf("3"); } catch(Exception e) { System.out.printf("4"); } finally { System.out.printf("5"); } }}
a) 1325b) 1345c) 1342d) 135
Ans. (d)Explanation: Once an exception occurs in try block, the execution passes to corresponding catch statement and doesn’t return back to try block. Only one of the catch blocks are executed at a time. finally block is always executed whether or not the exception occurred.2) What is the output of the following program?
public class Test{ private void m1() { m2(); System.out.printf("1"); } private void m2() { m3(); System.out.printf("2"); } private void m3() { System.out.printf("3"); try { int sum = 4/0; System.out.printf("4"); } catch(ArithmeticException e) { System.out.printf("5"); } System.out.printf("7"); } public static void main(String[] args) { Test obj = new Test(); obj.m1(); }}
a) 35721b) 354721c) 3521d) 35Ans. (a)Explanation: If an exception is handled in the catch statement, the program continues with its normal execution, after executing the catch statement corresponding to that exception. Also, when an exception occurs in the try block, the rest of the program in the try block is not executed.
3) What is the output of the following program?
public class Test{ public static void main(String[] args) { try { System.out.printf("1"); int data = 5 / 0; } catch(ArithmeticException e) { System.out.printf("2"); System.exit(0); } finally { System.out.printf("3"); } System.out.printf("4"); }}
a) 12b) 1234c) 124d) 123
Ans. (a)Explanation: The only case when the code inside finally block is not executed is when System.exit(0) is called explicitly in the program. Then exit statement is called and the program is terminated without executing any further.4) What is the output of the following program?
public class Test{ public static void main(String[] args) { try { System.out.printf("1"); int data = 5 / 0; } catch(ArithmeticException e) { Throwable obj = new Throwable("Sample"); try { throw obj; } catch (Throwable e1) { System.out.printf("8"); } } finally { System.out.printf("3"); } System.out.printf("4"); }}
a) Compilation errorb) Runtime errorc) 1834d) 134
Ans. (c)Explanation: Exceptions can be thrown in catch clause. This is done in order to change the exception type at run time. Exceptions in catch clause are thrown by creating instances of class Throwable as shown in the program.
5) What is the output of the following program?
import java.io.EOFException;import java.io.IOException; public class Test{ public static void main(String[] args) { try { System.out.printf("1"); int value = 10 / 0; throw new IOException(); } catch(EOFException e) { System.out.printf("2"); } catch(ArithmeticException e) { System.out.printf("3"); } catch(NullPointerException e) { System.out.printf("4"); } catch(IOException e) { System.out.printf("5"); } catch(Exception e) { System.out.printf("6"); } }}
a) 1346b) 136726c) 136d) 13Ans. (d)Explanation: In multi-catch statements, the exceptions must be listed from more specific to more general. Only one catch statement which is most specific to the occurred exception is executed.
This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Java-Exception Handling
Java-Exceptions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Set in Java
Stack Class in Java
Initializing a List in Java
Introduction to Java
Multithreading in Java
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Feb, 2019"
},
{
"code": null,
"e": 170,
"s": 52,
"text": "Prerequisites : Exception handling , control flow in try-catch-finally1) What is the output of the following program?"
},
{
"code": "public class Test{ public static void main(String[] args) { try { System.out.printf(\"1\"); int sum = 9 / 0; System.out.printf(\"2\"); } catch(ArithmeticException e) { System.out.printf(\"3\"); } catch(Exception e) { System.out.printf(\"4\"); } finally { System.out.printf(\"5\"); } }}",
"e": 605,
"s": 170,
"text": null
},
{
"code": null,
"e": 633,
"s": 605,
"text": "a) 1325b) 1345c) 1342d) 135"
},
{
"code": null,
"e": 957,
"s": 633,
"text": "Ans. (d)Explanation: Once an exception occurs in try block, the execution passes to corresponding catch statement and doesn’t return back to try block. Only one of the catch blocks are executed at a time. finally block is always executed whether or not the exception occurred.2) What is the output of the following program?"
},
{
"code": "public class Test{ private void m1() { m2(); System.out.printf(\"1\"); } private void m2() { m3(); System.out.printf(\"2\"); } private void m3() { System.out.printf(\"3\"); try { int sum = 4/0; System.out.printf(\"4\"); } catch(ArithmeticException e) { System.out.printf(\"5\"); } System.out.printf(\"7\"); } public static void main(String[] args) { Test obj = new Test(); obj.m1(); }}",
"e": 1518,
"s": 957,
"text": null
},
{
"code": null,
"e": 1844,
"s": 1518,
"text": "a) 35721b) 354721c) 3521d) 35Ans. (a)Explanation: If an exception is handled in the catch statement, the program continues with its normal execution, after executing the catch statement corresponding to that exception. Also, when an exception occurs in the try block, the rest of the program in the try block is not executed."
},
{
"code": null,
"e": 1892,
"s": 1844,
"text": "3) What is the output of the following program?"
},
{
"code": "public class Test{ public static void main(String[] args) { try { System.out.printf(\"1\"); int data = 5 / 0; } catch(ArithmeticException e) { System.out.printf(\"2\"); System.exit(0); } finally { System.out.printf(\"3\"); } System.out.printf(\"4\"); }}",
"e": 2272,
"s": 1892,
"text": null
},
{
"code": null,
"e": 2297,
"s": 2272,
"text": "a) 12b) 1234c) 124d) 123"
},
{
"code": null,
"e": 2581,
"s": 2297,
"text": "Ans. (a)Explanation: The only case when the code inside finally block is not executed is when System.exit(0) is called explicitly in the program. Then exit statement is called and the program is terminated without executing any further.4) What is the output of the following program?"
},
{
"code": "public class Test{ public static void main(String[] args) { try { System.out.printf(\"1\"); int data = 5 / 0; } catch(ArithmeticException e) { Throwable obj = new Throwable(\"Sample\"); try { throw obj; } catch (Throwable e1) { System.out.printf(\"8\"); } } finally { System.out.printf(\"3\"); } System.out.printf(\"4\"); }}",
"e": 3118,
"s": 2581,
"text": null
},
{
"code": null,
"e": 3168,
"s": 3118,
"text": "a) Compilation errorb) Runtime errorc) 1834d) 134"
},
{
"code": null,
"e": 3399,
"s": 3168,
"text": "Ans. (c)Explanation: Exceptions can be thrown in catch clause. This is done in order to change the exception type at run time. Exceptions in catch clause are thrown by creating instances of class Throwable as shown in the program."
},
{
"code": null,
"e": 3447,
"s": 3399,
"text": "5) What is the output of the following program?"
},
{
"code": "import java.io.EOFException;import java.io.IOException; public class Test{ public static void main(String[] args) { try { System.out.printf(\"1\"); int value = 10 / 0; throw new IOException(); } catch(EOFException e) { System.out.printf(\"2\"); } catch(ArithmeticException e) { System.out.printf(\"3\"); } catch(NullPointerException e) { System.out.printf(\"4\"); } catch(IOException e) { System.out.printf(\"5\"); } catch(Exception e) { System.out.printf(\"6\"); } }}",
"e": 4128,
"s": 3447,
"text": null
},
{
"code": null,
"e": 4356,
"s": 4128,
"text": "a) 1346b) 136726c) 136d) 13Ans. (d)Explanation: In multi-catch statements, the exceptions must be listed from more specific to more general. Only one catch statement which is most specific to the occurred exception is executed."
},
{
"code": null,
"e": 4656,
"s": 4356,
"text": "This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 4781,
"s": 4656,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 4805,
"s": 4781,
"text": "Java-Exception Handling"
},
{
"code": null,
"e": 4821,
"s": 4805,
"text": "Java-Exceptions"
},
{
"code": null,
"e": 4826,
"s": 4821,
"text": "Java"
},
{
"code": null,
"e": 4831,
"s": 4826,
"text": "Java"
},
{
"code": null,
"e": 4929,
"s": 4831,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4948,
"s": 4929,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 4963,
"s": 4948,
"text": "Stream In Java"
},
{
"code": null,
"e": 4981,
"s": 4963,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 5001,
"s": 4981,
"text": "Collections in Java"
},
{
"code": null,
"e": 5025,
"s": 5001,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 5037,
"s": 5025,
"text": "Set in Java"
},
{
"code": null,
"e": 5057,
"s": 5037,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 5085,
"s": 5057,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 5106,
"s": 5085,
"text": "Introduction to Java"
}
] |
Scraping Covid-19 statistics using BeautifulSoup
|
29 Dec, 2020
Coronavirus, one of the biggest pandemic has brought all the world to Danger. Along with this, it is one of the trending News, everyone has this day. In this article, we will be scraping data and printing Covid-19 statistics in human-readable form. The data will be scraped from this websitePrerequisites:
The libraries ‘requests’, ‘bs4’, and ‘texttable’ have to be installed –
pip install bs4
pip install requests
pip install texttable
Project : Let’s head over to code, create a file called run.py.
Python3
# importing modulesimport requestsfrom bs4 import BeautifulSoup # URL for scrapping dataurl = 'https://www.worldometers.info/coronavirus/countries-where-coronavirus-has-spread/' # get URL htmlpage = requests.get(url)soup = BeautifulSoup(page.text, 'html.parser') data = [] # soup.find_all('td') will scrape every# element in the url's tabledata_iterator = iter(soup.find_all('td')) # data_iterator is the iterator of the table# This loop will keep repeating till there is# data available in the iteratorwhile True: try: country = next(data_iterator).text confirmed = next(data_iterator).text deaths = next(data_iterator).text continent = next(data_iterator).text # For 'confirmed' and 'deaths', # make sure to remove the commas # and convert to int data.append(( country, int(confirmed.replace(', ', '')), int(deaths.replace(', ', '')), continent )) # StopIteration error is raised when # there are no more elements left to # iterate through except StopIteration: break # Sort the data by the number of confirmed casesdata.sort(key = lambda row: row[1], reverse = True)
To print the data in human-readable format, we will use the library ‘texttable‘
Python3
# create texttable objectimport texttable as tttable = tt.Texttable() # Add an empty row at the beginning for the headerstable.add_rows([(None, None, None, None)] + data) # 'l' denotes left, 'c' denotes center,# and 'r' denotes righttable.set_cols_align(('c', 'c', 'c', 'c')) table.header((' Country ', ' Number of cases ', ' Deaths ', ' Continent ')) print(table.draw())
Output:
+---------------------------+-------------------+----------+-------------------+
| Country | Number of cases | Deaths | Continent |
+===========================+===================+==========+===================+
| United States | 644348 | 28554 | North America |
+---------------------------+-------------------+----------+-------------------+
| Spain | 180659 | 18812 | Europe |
+---------------------------+-------------------+----------+-------------------+
| Italy | 165155 | 21645 | Europe |
+---------------------------+-------------------+----------+-------------------+
...
NOTE: The output depends on the current statisticsStay home, stay safe!
manroopparmar120
Python web-scraping-exercises
Python-BS3
Web-scraping
Python
Python Programs
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n29 Dec, 2020"
},
{
"code": null,
"e": 359,
"s": 52,
"text": "Coronavirus, one of the biggest pandemic has brought all the world to Danger. Along with this, it is one of the trending News, everyone has this day. In this article, we will be scraping data and printing Covid-19 statistics in human-readable form. The data will be scraped from this websitePrerequisites: "
},
{
"code": null,
"e": 432,
"s": 359,
"text": "The libraries ‘requests’, ‘bs4’, and ‘texttable’ have to be installed – "
},
{
"code": null,
"e": 492,
"s": 432,
"text": "pip install bs4\npip install requests\npip install texttable\n"
},
{
"code": null,
"e": 557,
"s": 492,
"text": "Project : Let’s head over to code, create a file called run.py. "
},
{
"code": null,
"e": 565,
"s": 557,
"text": "Python3"
},
{
"code": "# importing modulesimport requestsfrom bs4 import BeautifulSoup # URL for scrapping dataurl = 'https://www.worldometers.info/coronavirus/countries-where-coronavirus-has-spread/' # get URL htmlpage = requests.get(url)soup = BeautifulSoup(page.text, 'html.parser') data = [] # soup.find_all('td') will scrape every# element in the url's tabledata_iterator = iter(soup.find_all('td')) # data_iterator is the iterator of the table# This loop will keep repeating till there is# data available in the iteratorwhile True: try: country = next(data_iterator).text confirmed = next(data_iterator).text deaths = next(data_iterator).text continent = next(data_iterator).text # For 'confirmed' and 'deaths', # make sure to remove the commas # and convert to int data.append(( country, int(confirmed.replace(', ', '')), int(deaths.replace(', ', '')), continent )) # StopIteration error is raised when # there are no more elements left to # iterate through except StopIteration: break # Sort the data by the number of confirmed casesdata.sort(key = lambda row: row[1], reverse = True)",
"e": 1766,
"s": 565,
"text": null
},
{
"code": null,
"e": 1847,
"s": 1766,
"text": "To print the data in human-readable format, we will use the library ‘texttable‘ "
},
{
"code": null,
"e": 1855,
"s": 1847,
"text": "Python3"
},
{
"code": "# create texttable objectimport texttable as tttable = tt.Texttable() # Add an empty row at the beginning for the headerstable.add_rows([(None, None, None, None)] + data) # 'l' denotes left, 'c' denotes center,# and 'r' denotes righttable.set_cols_align(('c', 'c', 'c', 'c')) table.header((' Country ', ' Number of cases ', ' Deaths ', ' Continent ')) print(table.draw())",
"e": 2227,
"s": 1855,
"text": null
},
{
"code": null,
"e": 2236,
"s": 2227,
"text": "Output: "
},
{
"code": null,
"e": 2972,
"s": 2236,
"text": "+---------------------------+-------------------+----------+-------------------+\n| Country | Number of cases | Deaths | Continent |\n+===========================+===================+==========+===================+\n| United States | 644348 | 28554 | North America |\n+---------------------------+-------------------+----------+-------------------+\n| Spain | 180659 | 18812 | Europe |\n+---------------------------+-------------------+----------+-------------------+\n| Italy | 165155 | 21645 | Europe |\n+---------------------------+-------------------+----------+-------------------+\n...\n\n\n"
},
{
"code": null,
"e": 3045,
"s": 2972,
"text": "NOTE: The output depends on the current statisticsStay home, stay safe! "
},
{
"code": null,
"e": 3062,
"s": 3045,
"text": "manroopparmar120"
},
{
"code": null,
"e": 3092,
"s": 3062,
"text": "Python web-scraping-exercises"
},
{
"code": null,
"e": 3103,
"s": 3092,
"text": "Python-BS3"
},
{
"code": null,
"e": 3116,
"s": 3103,
"text": "Web-scraping"
},
{
"code": null,
"e": 3123,
"s": 3116,
"text": "Python"
},
{
"code": null,
"e": 3139,
"s": 3123,
"text": "Python Programs"
},
{
"code": null,
"e": 3155,
"s": 3139,
"text": "Write From Home"
},
{
"code": null,
"e": 3253,
"s": 3155,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3295,
"s": 3253,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3317,
"s": 3295,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3343,
"s": 3317,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3375,
"s": 3343,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3404,
"s": 3375,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3426,
"s": 3404,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 3465,
"s": 3426,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 3503,
"s": 3465,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 3540,
"s": 3503,
"text": "Python Program for Fibonacci numbers"
}
] |
How to Fix “class, interface, or enum expected” Error in Java with Examples?
|
28 Jan, 2021
In Java, the class interface or enum expected error is a compile-time error. There can be one of the following reasons we get “class, interface, or enum expected” error in Java:
Case 1: Extra curly Bracket
Java
class Hello { public static void main(String[] args) { System.out.println("Helloworld"); }}} // extra bracket.
In this case, the error can be removed by simply removing the extra bracket.
Java
class Hello { public static void main(String[] args) { System.out.println("Helloworld"); }}
Case 2: Function outside the class
Java
class Hello { public static void main(String args[]) { System.out.println("HI"); }}public static void func() { System.out.println("Hello"); }
In the earlier example, we get an error because the method func() is outside the Hello class. It can be removed by moving the closing curly braces “}” to the end of the file. In other words, move the func() method inside of Hello.
Java
class Hello { public static void main(String args[]) { System.out.println("HI"); } public static void func() { System.out.println("Hello"); }}
Case 3: Forgot to declare class at all
There might be a chance that we forgot to declare class at all. We will get this error. Check if you have declared class, interface, or enum in your java file or not.
Case 4: Declaring more than one package in the same file
Java
package A;class A { void fun1() { System.out.println("Hello"); }}package B; //getting class interface or enum expectedpublic class B { public static void main(String[] args) { System.out.println("HI"); }}
We can not put different packages into the same source file. In the source file, the package statement should be the first line.
Java
package A;class A { void fun1() { System.out.println("Hello"); }}public class B { public static void main(String[] args) { System.out.println("HI"); }}
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
List Interface in Java with Examples
Different ways of Reading a text file in Java
Constructors in Java
Strings in Java
HashMap containsKey() Method in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Traverse Through a HashMap in Java
Extends vs Implements in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jan, 2021"
},
{
"code": null,
"e": 207,
"s": 28,
"text": "In Java, the class interface or enum expected error is a compile-time error. There can be one of the following reasons we get “class, interface, or enum expected” error in Java: "
},
{
"code": null,
"e": 235,
"s": 207,
"text": "Case 1: Extra curly Bracket"
},
{
"code": null,
"e": 240,
"s": 235,
"text": "Java"
},
{
"code": "class Hello { public static void main(String[] args) { System.out.println(\"Helloworld\"); }}} // extra bracket.",
"e": 369,
"s": 240,
"text": null
},
{
"code": null,
"e": 448,
"s": 371,
"text": "In this case, the error can be removed by simply removing the extra bracket."
},
{
"code": null,
"e": 453,
"s": 448,
"text": "Java"
},
{
"code": "class Hello { public static void main(String[] args) { System.out.println(\"Helloworld\"); }}",
"e": 563,
"s": 453,
"text": null
},
{
"code": null,
"e": 600,
"s": 565,
"text": "Case 2: Function outside the class"
},
{
"code": null,
"e": 605,
"s": 600,
"text": "Java"
},
{
"code": "class Hello { public static void main(String args[]) { System.out.println(\"HI\"); }}public static void func() { System.out.println(\"Hello\"); }",
"e": 763,
"s": 605,
"text": null
},
{
"code": null,
"e": 997,
"s": 765,
"text": "In the earlier example, we get an error because the method func() is outside the Hello class. It can be removed by moving the closing curly braces “}” to the end of the file. In other words, move the func() method inside of Hello."
},
{
"code": null,
"e": 1002,
"s": 997,
"text": "Java"
},
{
"code": "class Hello { public static void main(String args[]) { System.out.println(\"HI\"); } public static void func() { System.out.println(\"Hello\"); }}",
"e": 1177,
"s": 1002,
"text": null
},
{
"code": null,
"e": 1218,
"s": 1179,
"text": "Case 3: Forgot to declare class at all"
},
{
"code": null,
"e": 1385,
"s": 1218,
"text": "There might be a chance that we forgot to declare class at all. We will get this error. Check if you have declared class, interface, or enum in your java file or not."
},
{
"code": null,
"e": 1442,
"s": 1385,
"text": "Case 4: Declaring more than one package in the same file"
},
{
"code": null,
"e": 1447,
"s": 1442,
"text": "Java"
},
{
"code": "package A;class A { void fun1() { System.out.println(\"Hello\"); }}package B; //getting class interface or enum expectedpublic class B { public static void main(String[] args) { System.out.println(\"HI\"); }}",
"e": 1671,
"s": 1447,
"text": null
},
{
"code": null,
"e": 1803,
"s": 1673,
"text": "We can not put different packages into the same source file. In the source file, the package statement should be the first line. "
},
{
"code": null,
"e": 1808,
"s": 1803,
"text": "Java"
},
{
"code": "package A;class A { void fun1() { System.out.println(\"Hello\"); }}public class B { public static void main(String[] args) { System.out.println(\"HI\"); }}",
"e": 1979,
"s": 1808,
"text": null
},
{
"code": null,
"e": 1986,
"s": 1979,
"text": "Picked"
},
{
"code": null,
"e": 1991,
"s": 1986,
"text": "Java"
},
{
"code": null,
"e": 2005,
"s": 1991,
"text": "Java Programs"
},
{
"code": null,
"e": 2010,
"s": 2005,
"text": "Java"
},
{
"code": null,
"e": 2108,
"s": 2010,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2145,
"s": 2108,
"text": "List Interface in Java with Examples"
},
{
"code": null,
"e": 2191,
"s": 2145,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 2212,
"s": 2191,
"text": "Constructors in Java"
},
{
"code": null,
"e": 2228,
"s": 2212,
"text": "Strings in Java"
},
{
"code": null,
"e": 2265,
"s": 2228,
"text": "HashMap containsKey() Method in Java"
},
{
"code": null,
"e": 2291,
"s": 2265,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 2325,
"s": 2291,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 2372,
"s": 2325,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 2407,
"s": 2372,
"text": "Traverse Through a HashMap in Java"
}
] |
How to set Cookie in ReactJS ?
|
16 Dec, 2020
Cookies are an important part of an application because cookies are used to set value in a key-value form which can be set in browser storage and used further for identifying the current user. The following example shows how to set the cookie in the ReactJS application, here we have taken the username as key, which is set in the cookie with its value.
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app setcookiedemo
Step 2: After creating your project folder i.e. setcookiedemo, move to it using the following command:
cd setcookiedemo
Project Structure: It will look like the following.
Project Structure
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code to set cookies in localStorage with basic UI.
Javascript
import React, { useState } from "react"; const App = () => { const [message, setMessage] = useState('') const setCookieFunction = (value) => { localStorage.setItem('username', value) setMessage('Username set as cookie!!') } return ( <div style={{ marginLeft: '200px', }}> <pre> <h2>Setting Cookie in ReactJS</h2> <span>Enter User Name: </span><input type="text" onChange={(e) => setCookieFunction(e.target.value)}></input> <br /> <span style={{ fontWeight: 'bold', color: 'red', }}>{message}</span> </pre> </div> );} export default App
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
The following will be the output if the user enters a username which is set as a cookie as shown below:Now go to your localStorage of browser by inspecting the browser page, there you can see our cookie which is set with key=’username’ and value=’gouravhammad’ as shown below:
The following will be the output if the user enters a username which is set as a cookie as shown below:
The following will be the output if the user enters a username which is set as a cookie as shown below:
Now go to your localStorage of browser by inspecting the browser page, there you can see our cookie which is set with key=’username’ and value=’gouravhammad’ as shown below:
Now go to your localStorage of browser by inspecting the browser page, there you can see our cookie which is set with key=’username’ and value=’gouravhammad’ as shown below:
react-js
JavaScript
Technical Scripter
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
Roadmap to Learn JavaScript For Beginners
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": 53,
"s": 25,
"text": "\n16 Dec, 2020"
},
{
"code": null,
"e": 407,
"s": 53,
"text": "Cookies are an important part of an application because cookies are used to set value in a key-value form which can be set in browser storage and used further for identifying the current user. The following example shows how to set the cookie in the ReactJS application, here we have taken the username as key, which is set in the cookie with its value."
},
{
"code": null,
"e": 435,
"s": 407,
"text": "Creating React Application:"
},
{
"code": null,
"e": 499,
"s": 435,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 534,
"s": 499,
"text": "npx create-react-app setcookiedemo"
},
{
"code": null,
"e": 637,
"s": 534,
"text": "Step 2: After creating your project folder i.e. setcookiedemo, move to it using the following command:"
},
{
"code": null,
"e": 654,
"s": 637,
"text": "cd setcookiedemo"
},
{
"code": null,
"e": 706,
"s": 654,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 724,
"s": 706,
"text": "Project Structure"
},
{
"code": null,
"e": 898,
"s": 724,
"text": "App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code to set cookies in localStorage with basic UI."
},
{
"code": null,
"e": 909,
"s": 898,
"text": "Javascript"
},
{
"code": "import React, { useState } from \"react\"; const App = () => { const [message, setMessage] = useState('') const setCookieFunction = (value) => { localStorage.setItem('username', value) setMessage('Username set as cookie!!') } return ( <div style={{ marginLeft: '200px', }}> <pre> <h2>Setting Cookie in ReactJS</h2> <span>Enter User Name: </span><input type=\"text\" onChange={(e) => setCookieFunction(e.target.value)}></input> <br /> <span style={{ fontWeight: 'bold', color: 'red', }}>{message}</span> </pre> </div> );} export default App",
"e": 1550,
"s": 909,
"text": null
},
{
"code": null,
"e": 1663,
"s": 1550,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 1673,
"s": 1663,
"text": "npm start"
},
{
"code": null,
"e": 1681,
"s": 1673,
"text": "Output:"
},
{
"code": null,
"e": 1958,
"s": 1681,
"text": "The following will be the output if the user enters a username which is set as a cookie as shown below:Now go to your localStorage of browser by inspecting the browser page, there you can see our cookie which is set with key=’username’ and value=’gouravhammad’ as shown below:"
},
{
"code": null,
"e": 2062,
"s": 1958,
"text": "The following will be the output if the user enters a username which is set as a cookie as shown below:"
},
{
"code": null,
"e": 2166,
"s": 2062,
"text": "The following will be the output if the user enters a username which is set as a cookie as shown below:"
},
{
"code": null,
"e": 2340,
"s": 2166,
"text": "Now go to your localStorage of browser by inspecting the browser page, there you can see our cookie which is set with key=’username’ and value=’gouravhammad’ as shown below:"
},
{
"code": null,
"e": 2514,
"s": 2340,
"text": "Now go to your localStorage of browser by inspecting the browser page, there you can see our cookie which is set with key=’username’ and value=’gouravhammad’ as shown below:"
},
{
"code": null,
"e": 2523,
"s": 2514,
"text": "react-js"
},
{
"code": null,
"e": 2534,
"s": 2523,
"text": "JavaScript"
},
{
"code": null,
"e": 2553,
"s": 2534,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2570,
"s": 2553,
"text": "Web Technologies"
},
{
"code": null,
"e": 2668,
"s": 2570,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2729,
"s": 2668,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2801,
"s": 2729,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2841,
"s": 2801,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2882,
"s": 2841,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2924,
"s": 2882,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 2986,
"s": 2924,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3019,
"s": 2986,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3080,
"s": 3019,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3130,
"s": 3080,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to Create a Spring Boot Project?
|
22 Dec, 2021
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time. Following are some of the features of Spring Boot:
It allows avoiding heavy configuration of XML which is present in spring
It provides easy maintenance and creation of REST endpoints
It includes embedded Tomcat-server
Deployment is very easy, war and jar files can be easily deployed in the tomcat server
For more information please refer to this article: Introduction to Spring Boot
Generally, to develop a Spring Boot Application we choose Eclipse, Spring Tool Suite, and IntelliJ IDEA IDE. So in this article, we are going to create our spring boot project in these 3 IDEs.
The Eclipse IDE is famous for the Java Integrated Development Environment (IDE), but it has a number of pretty cool IDEs, including the C/C++ IDE, JavaScript/TypeScript IDE, PHP IDE, and more.
Procedure:
Install Eclipse IDE for Enterprise Java and Web DeveloperCreate a Spring Boot Project in Spring InitializrImport Spring Boot Project in Eclipse IDESearch “maven” and choose Existing Maven ProjectChoose NextClick on the Browse button and select the extracted zip Click on the Finish button and we are done creating the Spring Boot project
Install Eclipse IDE for Enterprise Java and Web Developer
Create a Spring Boot Project in Spring Initializr
Import Spring Boot Project in Eclipse IDE
Search “maven” and choose Existing Maven Project
Choose Next
Click on the Browse button and select the extracted zip
Click on the Finish button and we are done creating the Spring Boot project
Let us discuss these steps in detail alongside visual aids
Step 1: Install Eclipse IDE for Enterprise Java and Web Developer
Please refer to this article How to Install Eclipse IDE for Enterprise Java and Web Development and install the Eclipse IDE.
Step 2: Create a Spring Boot Project in Spring Initializr
Go to this link and create a Spring Boot project. Please fill in all the details accordingly and at last click on the GENERATE button below. This will download your Spring Boot project in zip format. Now extract the folder into your local machine. For more details in Spring Initializr refer to this article: Spring Initializr
Step 3: Import Spring Boot Project in Eclipse IDE
Go to the Eclipse IDE for Enterprise Java and Web Developer > File > Import as shown in the below image.
Step 4: Search “maven” and choose Existing Maven Project and click on the Next button as shown in the below image.
Step 5: Now click on the Browse button and select the extracted zip file that has been generated.
Step 6. And at last click on the Finish button and we are done creating the Spring Boot project
By now, Spring Boot project has been created as depicted in the below media
Spring Tool Suite (STS) is a java IDE tailored for developing Spring-based enterprise applications. It is easier, faster, and more convenient. And most importantly it is based on Eclipse IDE. STS is free, open-source, and powered by VMware. Spring Tools 4 is the next generation of Spring tooling for the favorite coding environment. Largely rebuilt from scratch, it provides world-class support for developing Spring-based enterprise applications, whether you prefer Eclipse, Visual Studio Code, or Theia IDE.
Procedure:
Install Spring Tool Suite IDECreate a new Spring projectFill details in the pop-up window and press Next.Choose Spring Boot version and select dependencies and press Next.Click on the ‘Finish’ button.
Install Spring Tool Suite IDE
Create a new Spring project
Fill details in the pop-up window and press Next.
Choose Spring Boot version and select dependencies and press Next.
Click on the ‘Finish’ button.
Step 1: Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE
For this user must have pre-requisite knowledge of downloading and installing Spring Tool Suite IDE
Step 2: Go to the File > New > Spring Starter Project as shown in the below image as follows:
Step 3: In this pop-up window fill the detail below as follows and further click on the Next button as shown in the below image.
Service URL: Default
Name: Your Project Name
Type: Maven Project
Java Version: 11 or greater than 11
Packaging: As your need
Language: As your need
Group: A unique base name of the company or group that created the project
Artifact: A unique name of the project
Version: Default
Description: As your need
Package: Your package name
Step 4: Choose your required Spring Boot Version and select your dependencies as per your project requirement. And at last click on the Next button.
Step 5: Now simply click on the Finish button.
Here now, please wait for some time to download all the required files such as dependencies that you have selected in Step4 above.
Below is the Welcome screen after you have successfully Created and Setup Spring Boot Project in Spring Tool Suite
IntelliJ is an integrated development environment(IDE) written in Java. It is used for developing computer software. This IDE is developed by Jetbrains and is available as an Apache 2 Licensed community edition and a commercial edition.
Procedure:
Install IntelliJ IDEA on the local machine.Create a Spring Boot Project in Spring InitializrImport Spring Boot Project in IntelliJ IDEAChoose the project that you have created in above step 2.
Install IntelliJ IDEA on the local machine.
Create a Spring Boot Project in Spring Initializr
Import Spring Boot Project in IntelliJ IDEA
Choose the project that you have created in above step 2.
Step 1: Install IntelliJ IDEA on the local machine for that do go through pre-requisite for installing Intellij Idea on the system.
Step 2: Create a Spring Boot Project in Spring Initializr
Create a Spring Boot project and do fill in all the details accordingly and at last click on the GENERATE button below. This will download your Spring Boot project in zip format. Now extract the folder into your local machine and do go through the introduction to Spring Initializr before proceeding further.
Step 3: Import Spring Boot Project in IntelliJ IDEA
After successfully installing IntelliJ IDEA go to the File > Open as seen in the below image.
After this, a pop-up window will occur like the following.
Step 4: Here you have to choose the project that you have created in step 2. For example, here we have created the spring boot project named “demo” and stored it inside the Downloads folder and you can see we can find the same inside the Downloads folder. At last click on the OK button. And we are done creating the Spring Boot project in IntelliJ IDEA. Please wait for some time to download all the required files.
By now, the Spring Boot project has been created as depicted in the below media. The left side contains the Project file structure while in the middle you can see the Code Editor is present.
Java-Spring-Boot
Picked
How To
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Dec, 2021"
},
{
"code": null,
"e": 502,
"s": 28,
"text": "Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time. Following are some of the features of Spring Boot:"
},
{
"code": null,
"e": 575,
"s": 502,
"text": "It allows avoiding heavy configuration of XML which is present in spring"
},
{
"code": null,
"e": 635,
"s": 575,
"text": "It provides easy maintenance and creation of REST endpoints"
},
{
"code": null,
"e": 670,
"s": 635,
"text": "It includes embedded Tomcat-server"
},
{
"code": null,
"e": 757,
"s": 670,
"text": "Deployment is very easy, war and jar files can be easily deployed in the tomcat server"
},
{
"code": null,
"e": 836,
"s": 757,
"text": "For more information please refer to this article: Introduction to Spring Boot"
},
{
"code": null,
"e": 1030,
"s": 836,
"text": "Generally, to develop a Spring Boot Application we choose Eclipse, Spring Tool Suite, and IntelliJ IDEA IDE. So in this article, we are going to create our spring boot project in these 3 IDEs. "
},
{
"code": null,
"e": 1224,
"s": 1030,
"text": "The Eclipse IDE is famous for the Java Integrated Development Environment (IDE), but it has a number of pretty cool IDEs, including the C/C++ IDE, JavaScript/TypeScript IDE, PHP IDE, and more. "
},
{
"code": null,
"e": 1235,
"s": 1224,
"text": "Procedure:"
},
{
"code": null,
"e": 1573,
"s": 1235,
"text": "Install Eclipse IDE for Enterprise Java and Web DeveloperCreate a Spring Boot Project in Spring InitializrImport Spring Boot Project in Eclipse IDESearch “maven” and choose Existing Maven ProjectChoose NextClick on the Browse button and select the extracted zip Click on the Finish button and we are done creating the Spring Boot project"
},
{
"code": null,
"e": 1631,
"s": 1573,
"text": "Install Eclipse IDE for Enterprise Java and Web Developer"
},
{
"code": null,
"e": 1681,
"s": 1631,
"text": "Create a Spring Boot Project in Spring Initializr"
},
{
"code": null,
"e": 1723,
"s": 1681,
"text": "Import Spring Boot Project in Eclipse IDE"
},
{
"code": null,
"e": 1772,
"s": 1723,
"text": "Search “maven” and choose Existing Maven Project"
},
{
"code": null,
"e": 1784,
"s": 1772,
"text": "Choose Next"
},
{
"code": null,
"e": 1841,
"s": 1784,
"text": "Click on the Browse button and select the extracted zip "
},
{
"code": null,
"e": 1917,
"s": 1841,
"text": "Click on the Finish button and we are done creating the Spring Boot project"
},
{
"code": null,
"e": 1976,
"s": 1917,
"text": "Let us discuss these steps in detail alongside visual aids"
},
{
"code": null,
"e": 2042,
"s": 1976,
"text": "Step 1: Install Eclipse IDE for Enterprise Java and Web Developer"
},
{
"code": null,
"e": 2167,
"s": 2042,
"text": "Please refer to this article How to Install Eclipse IDE for Enterprise Java and Web Development and install the Eclipse IDE."
},
{
"code": null,
"e": 2225,
"s": 2167,
"text": "Step 2: Create a Spring Boot Project in Spring Initializr"
},
{
"code": null,
"e": 2552,
"s": 2225,
"text": "Go to this link and create a Spring Boot project. Please fill in all the details accordingly and at last click on the GENERATE button below. This will download your Spring Boot project in zip format. Now extract the folder into your local machine. For more details in Spring Initializr refer to this article: Spring Initializr"
},
{
"code": null,
"e": 2602,
"s": 2552,
"text": "Step 3: Import Spring Boot Project in Eclipse IDE"
},
{
"code": null,
"e": 2708,
"s": 2602,
"text": "Go to the Eclipse IDE for Enterprise Java and Web Developer > File > Import as shown in the below image. "
},
{
"code": null,
"e": 2824,
"s": 2708,
"text": "Step 4: Search “maven” and choose Existing Maven Project and click on the Next button as shown in the below image. "
},
{
"code": null,
"e": 2922,
"s": 2824,
"text": "Step 5: Now click on the Browse button and select the extracted zip file that has been generated."
},
{
"code": null,
"e": 3019,
"s": 2922,
"text": "Step 6. And at last click on the Finish button and we are done creating the Spring Boot project "
},
{
"code": null,
"e": 3097,
"s": 3019,
"text": "By now, Spring Boot project has been created as depicted in the below media "
},
{
"code": null,
"e": 3608,
"s": 3097,
"text": "Spring Tool Suite (STS) is a java IDE tailored for developing Spring-based enterprise applications. It is easier, faster, and more convenient. And most importantly it is based on Eclipse IDE. STS is free, open-source, and powered by VMware. Spring Tools 4 is the next generation of Spring tooling for the favorite coding environment. Largely rebuilt from scratch, it provides world-class support for developing Spring-based enterprise applications, whether you prefer Eclipse, Visual Studio Code, or Theia IDE."
},
{
"code": null,
"e": 3619,
"s": 3608,
"text": "Procedure:"
},
{
"code": null,
"e": 3820,
"s": 3619,
"text": "Install Spring Tool Suite IDECreate a new Spring projectFill details in the pop-up window and press Next.Choose Spring Boot version and select dependencies and press Next.Click on the ‘Finish’ button."
},
{
"code": null,
"e": 3850,
"s": 3820,
"text": "Install Spring Tool Suite IDE"
},
{
"code": null,
"e": 3878,
"s": 3850,
"text": "Create a new Spring project"
},
{
"code": null,
"e": 3928,
"s": 3878,
"text": "Fill details in the pop-up window and press Next."
},
{
"code": null,
"e": 3995,
"s": 3928,
"text": "Choose Spring Boot version and select dependencies and press Next."
},
{
"code": null,
"e": 4025,
"s": 3995,
"text": "Click on the ‘Finish’ button."
},
{
"code": null,
"e": 4092,
"s": 4025,
"text": "Step 1: Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE"
},
{
"code": null,
"e": 4192,
"s": 4092,
"text": "For this user must have pre-requisite knowledge of downloading and installing Spring Tool Suite IDE"
},
{
"code": null,
"e": 4286,
"s": 4192,
"text": "Step 2: Go to the File > New > Spring Starter Project as shown in the below image as follows:"
},
{
"code": null,
"e": 4416,
"s": 4286,
"text": "Step 3: In this pop-up window fill the detail below as follows and further click on the Next button as shown in the below image. "
},
{
"code": null,
"e": 4749,
"s": 4416,
"text": "Service URL: Default\nName: Your Project Name\nType: Maven Project\nJava Version: 11 or greater than 11\nPackaging: As your need\nLanguage: As your need\nGroup: A unique base name of the company or group that created the project\nArtifact: A unique name of the project\nVersion: Default\nDescription: As your need\nPackage: Your package name"
},
{
"code": null,
"e": 4898,
"s": 4749,
"text": "Step 4: Choose your required Spring Boot Version and select your dependencies as per your project requirement. And at last click on the Next button."
},
{
"code": null,
"e": 4945,
"s": 4898,
"text": "Step 5: Now simply click on the Finish button."
},
{
"code": null,
"e": 5076,
"s": 4945,
"text": "Here now, please wait for some time to download all the required files such as dependencies that you have selected in Step4 above."
},
{
"code": null,
"e": 5191,
"s": 5076,
"text": "Below is the Welcome screen after you have successfully Created and Setup Spring Boot Project in Spring Tool Suite"
},
{
"code": null,
"e": 5428,
"s": 5191,
"text": "IntelliJ is an integrated development environment(IDE) written in Java. It is used for developing computer software. This IDE is developed by Jetbrains and is available as an Apache 2 Licensed community edition and a commercial edition."
},
{
"code": null,
"e": 5439,
"s": 5428,
"text": "Procedure:"
},
{
"code": null,
"e": 5632,
"s": 5439,
"text": "Install IntelliJ IDEA on the local machine.Create a Spring Boot Project in Spring InitializrImport Spring Boot Project in IntelliJ IDEAChoose the project that you have created in above step 2."
},
{
"code": null,
"e": 5676,
"s": 5632,
"text": "Install IntelliJ IDEA on the local machine."
},
{
"code": null,
"e": 5726,
"s": 5676,
"text": "Create a Spring Boot Project in Spring Initializr"
},
{
"code": null,
"e": 5770,
"s": 5726,
"text": "Import Spring Boot Project in IntelliJ IDEA"
},
{
"code": null,
"e": 5828,
"s": 5770,
"text": "Choose the project that you have created in above step 2."
},
{
"code": null,
"e": 5960,
"s": 5828,
"text": "Step 1: Install IntelliJ IDEA on the local machine for that do go through pre-requisite for installing Intellij Idea on the system."
},
{
"code": null,
"e": 6018,
"s": 5960,
"text": "Step 2: Create a Spring Boot Project in Spring Initializr"
},
{
"code": null,
"e": 6327,
"s": 6018,
"text": "Create a Spring Boot project and do fill in all the details accordingly and at last click on the GENERATE button below. This will download your Spring Boot project in zip format. Now extract the folder into your local machine and do go through the introduction to Spring Initializr before proceeding further."
},
{
"code": null,
"e": 6379,
"s": 6327,
"text": "Step 3: Import Spring Boot Project in IntelliJ IDEA"
},
{
"code": null,
"e": 6474,
"s": 6379,
"text": "After successfully installing IntelliJ IDEA go to the File > Open as seen in the below image. "
},
{
"code": null,
"e": 6534,
"s": 6474,
"text": "After this, a pop-up window will occur like the following. "
},
{
"code": null,
"e": 6952,
"s": 6534,
"text": "Step 4: Here you have to choose the project that you have created in step 2. For example, here we have created the spring boot project named “demo” and stored it inside the Downloads folder and you can see we can find the same inside the Downloads folder. At last click on the OK button. And we are done creating the Spring Boot project in IntelliJ IDEA. Please wait for some time to download all the required files. "
},
{
"code": null,
"e": 7144,
"s": 6952,
"text": "By now, the Spring Boot project has been created as depicted in the below media. The left side contains the Project file structure while in the middle you can see the Code Editor is present. "
},
{
"code": null,
"e": 7161,
"s": 7144,
"text": "Java-Spring-Boot"
},
{
"code": null,
"e": 7168,
"s": 7161,
"text": "Picked"
},
{
"code": null,
"e": 7175,
"s": 7168,
"text": "How To"
},
{
"code": null,
"e": 7180,
"s": 7175,
"text": "Java"
},
{
"code": null,
"e": 7185,
"s": 7180,
"text": "Java"
}
] |
Perl | my keyword
|
07 May, 2019
my keyword in Perl declares the listed variable to be local to the enclosing block in which it is defined. The purpose of my is to define static scoping. This can be used to use the same variable name multiple times but with different values. Note: To specify more than one variable under my keyword, parentheses are used.
Syntax: my variable
Parameter:variable: to be defined as local
Returns:does not return any value.
Example 1:
#!/usr/bin/perl -w # Local variable outside of subroutinemy $string = "Geeks for Geeks";print "$string\n"; # Subroutine callmy_func();print "$string\n"; # defining subroutine sub my_func{ # Local variable inside the subroutine my $string = "This is in Function"; print "$string\n"; mysub();} # defining subroutine to show# the local effect of my keywordsub mysub { print "$string\n";}
Output:
Geeks for Geeks
This is in Function
Geeks for Geeks
Geeks for Geeks
Example 2:
#!/usr/bin/perl -w # Local variable outside of subroutinemy $string = "Welcome to Geeks";print "$string\n"; # Subroutine callmy_func();print "$string\n"; # defining subroutine sub my_func{ # Local variable inside the subroutine my $string = "Let's GO Geeky!!!"; print "$string\n"; mysub();} # defining subroutine to show# the local effect of my keywordsub mysub { print "$string\n";}
Output:
Welcome to Geeks
Let's GO Geeky!!!
Welcome to Geeks
Welcome to Geeks
How to define dynamic scoping?The opposite of “my” is “local”. The local keyword defines dynamic scoping.
# A perl code to demonstrate dynamic scoping $x = 10; sub f { return $x; } sub g { # Since local is used, x uses # dynamic scoping. local $x = 20; return f(); } print g()."\n";
perl-basics
Perl-Keywords
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 May, 2019"
},
{
"code": null,
"e": 351,
"s": 28,
"text": "my keyword in Perl declares the listed variable to be local to the enclosing block in which it is defined. The purpose of my is to define static scoping. This can be used to use the same variable name multiple times but with different values. Note: To specify more than one variable under my keyword, parentheses are used."
},
{
"code": null,
"e": 371,
"s": 351,
"text": "Syntax: my variable"
},
{
"code": null,
"e": 414,
"s": 371,
"text": "Parameter:variable: to be defined as local"
},
{
"code": null,
"e": 449,
"s": 414,
"text": "Returns:does not return any value."
},
{
"code": null,
"e": 460,
"s": 449,
"text": "Example 1:"
},
{
"code": "#!/usr/bin/perl -w # Local variable outside of subroutinemy $string = \"Geeks for Geeks\";print \"$string\\n\"; # Subroutine callmy_func();print \"$string\\n\"; # defining subroutine sub my_func{ # Local variable inside the subroutine my $string = \"This is in Function\"; print \"$string\\n\"; mysub();} # defining subroutine to show# the local effect of my keywordsub mysub { print \"$string\\n\";}",
"e": 864,
"s": 460,
"text": null
},
{
"code": null,
"e": 872,
"s": 864,
"text": "Output:"
},
{
"code": null,
"e": 940,
"s": 872,
"text": "Geeks for Geeks\nThis is in Function\nGeeks for Geeks\nGeeks for Geeks"
},
{
"code": null,
"e": 951,
"s": 940,
"text": "Example 2:"
},
{
"code": "#!/usr/bin/perl -w # Local variable outside of subroutinemy $string = \"Welcome to Geeks\";print \"$string\\n\"; # Subroutine callmy_func();print \"$string\\n\"; # defining subroutine sub my_func{ # Local variable inside the subroutine my $string = \"Let's GO Geeky!!!\"; print \"$string\\n\"; mysub();} # defining subroutine to show# the local effect of my keywordsub mysub { print \"$string\\n\";}",
"e": 1354,
"s": 951,
"text": null
},
{
"code": null,
"e": 1362,
"s": 1354,
"text": "Output:"
},
{
"code": null,
"e": 1431,
"s": 1362,
"text": "Welcome to Geeks\nLet's GO Geeky!!!\nWelcome to Geeks\nWelcome to Geeks"
},
{
"code": null,
"e": 1537,
"s": 1431,
"text": "How to define dynamic scoping?The opposite of “my” is “local”. The local keyword defines dynamic scoping."
},
{
"code": "# A perl code to demonstrate dynamic scoping $x = 10; sub f { return $x; } sub g { # Since local is used, x uses # dynamic scoping. local $x = 20; return f(); } print g().\"\\n\"; ",
"e": 1736,
"s": 1537,
"text": null
},
{
"code": null,
"e": 1748,
"s": 1736,
"text": "perl-basics"
},
{
"code": null,
"e": 1762,
"s": 1748,
"text": "Perl-Keywords"
},
{
"code": null,
"e": 1767,
"s": 1762,
"text": "Perl"
},
{
"code": null,
"e": 1772,
"s": 1767,
"text": "Perl"
}
] |
Python Program to check date in date range
|
06 Jun, 2021
Given a date list and date range, the task is to write a Python program to check whether any date exists in the list in a given range.
Example:
Input : test_list = [datetime(2019, 12, 30), datetime(2018, 4, 4), datetime(2016, 12, 21), datetime(2021, 2, 2), datetime(2020, 2, 3), datetime(2017, 1, 1)], date_strt, date_end = datetime(2019, 3, 14), datetime(2020, 1, 4)
Output : True
Explanation : 30 Dec’2019 lies in range of 14 March 2019 to 4 January 2020, hence True.
Input : test_list = [datetime(2018, 4, 4), datetime(2016, 12, 21), datetime(2021, 2, 2), datetime(2020, 2, 3), datetime(2017, 1, 1)], date_strt, date_end = datetime(2019, 3, 14), datetime(2020, 1, 4)
Output : False
Explanation : No date lies in range.
Method 1: Using loop
In this, for each element, we check using conditionals if any date falls in the range, if found, true is returned.
Python3
# Python3 code to demonstrate working of# Test for date in date range# Using loopfrom datetime import datetime # initializing listtest_list = [datetime(2019, 12, 30), datetime(2018, 4, 4), datetime(2016, 12, 21), datetime(2021, 2, 2), datetime(2020, 2, 3), datetime(2017, 1, 1)] # printing original listprint("The original list is : " + str(test_list)) # initializing date rangesdate_strt, date_end = datetime(2019, 3, 14), datetime(2020, 1, 4) res = Falsefor ele in test_list: # checking for date in range if ele >= date_strt and ele <= date_end: res = True # printing resultprint("Does list contain any date in range : " + str(res))
Output:
The original list is : [datetime.datetime(2019, 12, 30, 0, 0), datetime.datetime(2018, 4, 4, 0, 0), datetime.datetime(2016, 12, 21, 0, 0), datetime.datetime(2021, 2, 2, 0, 0), datetime.datetime(2020, 2, 3, 0, 0), datetime.datetime(2017, 1, 1, 0, 0)]
Does list contain any date in range : True
Method 2: Using any()
Similar to the above method, the only difference being any() is used to check for the presence of any date in range.
Python3
# Python3 code to demonstrate working of# Test for date in date range# Using any()from datetime import datetime # initializing listtest_list = [datetime(2019, 12, 30), datetime(2018, 4, 4), datetime(2016, 12, 21), datetime(2021, 2, 2), datetime(2020, 2, 3), datetime(2017, 1, 1)] # printing original listprint("The original list is : " + str(test_list)) # initializing date rangesdate_strt, date_end = datetime(2019, 3, 14), datetime(2020, 1, 4) # any() for checking presence of any date in rangeres = any(ele >= date_strt and ele <= date_end for ele in test_list) # printing resultprint("Does list contain any date in range : " + str(res))
Output:
The original list is : [datetime.datetime(2019, 12, 30, 0, 0), datetime.datetime(2018, 4, 4, 0, 0), datetime.datetime(2016, 12, 21, 0, 0), datetime.datetime(2021, 2, 2, 0, 0), datetime.datetime(2020, 2, 3, 0, 0), datetime.datetime(2017, 1, 1, 0, 0)]
Does list contain any date in range : True
Python datetime-program
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Jun, 2021"
},
{
"code": null,
"e": 163,
"s": 28,
"text": "Given a date list and date range, the task is to write a Python program to check whether any date exists in the list in a given range."
},
{
"code": null,
"e": 172,
"s": 163,
"text": "Example:"
},
{
"code": null,
"e": 396,
"s": 172,
"text": "Input : test_list = [datetime(2019, 12, 30), datetime(2018, 4, 4), datetime(2016, 12, 21), datetime(2021, 2, 2), datetime(2020, 2, 3), datetime(2017, 1, 1)], date_strt, date_end = datetime(2019, 3, 14), datetime(2020, 1, 4)"
},
{
"code": null,
"e": 410,
"s": 396,
"text": "Output : True"
},
{
"code": null,
"e": 498,
"s": 410,
"text": "Explanation : 30 Dec’2019 lies in range of 14 March 2019 to 4 January 2020, hence True."
},
{
"code": null,
"e": 698,
"s": 498,
"text": "Input : test_list = [datetime(2018, 4, 4), datetime(2016, 12, 21), datetime(2021, 2, 2), datetime(2020, 2, 3), datetime(2017, 1, 1)], date_strt, date_end = datetime(2019, 3, 14), datetime(2020, 1, 4)"
},
{
"code": null,
"e": 713,
"s": 698,
"text": "Output : False"
},
{
"code": null,
"e": 750,
"s": 713,
"text": "Explanation : No date lies in range."
},
{
"code": null,
"e": 771,
"s": 750,
"text": "Method 1: Using loop"
},
{
"code": null,
"e": 886,
"s": 771,
"text": "In this, for each element, we check using conditionals if any date falls in the range, if found, true is returned."
},
{
"code": null,
"e": 894,
"s": 886,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Test for date in date range# Using loopfrom datetime import datetime # initializing listtest_list = [datetime(2019, 12, 30), datetime(2018, 4, 4), datetime(2016, 12, 21), datetime(2021, 2, 2), datetime(2020, 2, 3), datetime(2017, 1, 1)] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing date rangesdate_strt, date_end = datetime(2019, 3, 14), datetime(2020, 1, 4) res = Falsefor ele in test_list: # checking for date in range if ele >= date_strt and ele <= date_end: res = True # printing resultprint(\"Does list contain any date in range : \" + str(res))",
"e": 1575,
"s": 894,
"text": null
},
{
"code": null,
"e": 1583,
"s": 1575,
"text": "Output:"
},
{
"code": null,
"e": 1833,
"s": 1583,
"text": "The original list is : [datetime.datetime(2019, 12, 30, 0, 0), datetime.datetime(2018, 4, 4, 0, 0), datetime.datetime(2016, 12, 21, 0, 0), datetime.datetime(2021, 2, 2, 0, 0), datetime.datetime(2020, 2, 3, 0, 0), datetime.datetime(2017, 1, 1, 0, 0)]"
},
{
"code": null,
"e": 1876,
"s": 1833,
"text": "Does list contain any date in range : True"
},
{
"code": null,
"e": 1898,
"s": 1876,
"text": "Method 2: Using any()"
},
{
"code": null,
"e": 2015,
"s": 1898,
"text": "Similar to the above method, the only difference being any() is used to check for the presence of any date in range."
},
{
"code": null,
"e": 2023,
"s": 2015,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Test for date in date range# Using any()from datetime import datetime # initializing listtest_list = [datetime(2019, 12, 30), datetime(2018, 4, 4), datetime(2016, 12, 21), datetime(2021, 2, 2), datetime(2020, 2, 3), datetime(2017, 1, 1)] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing date rangesdate_strt, date_end = datetime(2019, 3, 14), datetime(2020, 1, 4) # any() for checking presence of any date in rangeres = any(ele >= date_strt and ele <= date_end for ele in test_list) # printing resultprint(\"Does list contain any date in range : \" + str(res))",
"e": 2694,
"s": 2023,
"text": null
},
{
"code": null,
"e": 2702,
"s": 2694,
"text": "Output:"
},
{
"code": null,
"e": 2952,
"s": 2702,
"text": "The original list is : [datetime.datetime(2019, 12, 30, 0, 0), datetime.datetime(2018, 4, 4, 0, 0), datetime.datetime(2016, 12, 21, 0, 0), datetime.datetime(2021, 2, 2, 0, 0), datetime.datetime(2020, 2, 3, 0, 0), datetime.datetime(2017, 1, 1, 0, 0)]"
},
{
"code": null,
"e": 2995,
"s": 2952,
"text": "Does list contain any date in range : True"
},
{
"code": null,
"e": 3019,
"s": 2995,
"text": "Python datetime-program"
},
{
"code": null,
"e": 3026,
"s": 3019,
"text": "Python"
},
{
"code": null,
"e": 3042,
"s": 3026,
"text": "Python Programs"
}
] |
How to reverse the order of a dataframe in R?
|
23 Dec, 2021
Order reversal of the dataframe involves swapping of the rows or columns in such a way, that the elements are accessed from backward. In this article, we will discuss various ways of reversing the order of a dataframe both column and row-wise.
Method 1: Using the rev method
The rev() method in R is used to return the reversed order of the R object, be it dataframe or a vector. It computes the reverse columns by default. The resultant dataframe returns the last column first followed by the previous columns. The ordering of the rows remains unmodified. The result has to be stored in a new variable in order to retain the modifications.
Syntax:
rev (df)
Where df is the dataframe.
Example:
R
# declaring a dataframe in Rdata_frame <- data.frame(col1 = c(1:4), col2 = letters[1:4], col3 = c(8:11)) print ("Original Dataframe")print (data_frame) # calculating reverse of dataframerev_data_frame <- rev(data_frame) print ("Modified Dataframe")print (rev_data_frame)
Output
[1] "Original Dataframe"
col1 col2 col3
1 1 a 8
2 2 b 9
3 3 c 10
4 4 d 11
[1] "Modified Dataframe"
col3 col2 col1
1 8 a 1
2 9 b 2
3 10 c 3
4 11 d 4
Method 2: Using ncol method
ncol() method in R is used to return the number of columns of the specified dataframe. The dataframe is accessed from the last column index to the first column index range, that is 1.
Example:
R
# declaring a dataframe in Rdata_frame <- data.frame(col1 = c(1:4), col2 = letters[1:4], col3 = c(8:11)) print ("Original Dataframe")print (data_frame) # computing reverserev_data_frame <- data_frame[,ncol(data_frame):1 ] print ("Modified Dataframe")print (rev_data_frame)
Output
[1] "Original Dataframe"
col1 col2 col3
1 1 a 8
2 2 b 9
3 3 c 10
4 4 d 11
[1] "Modified Dataframe"
col3 col2 col1
1 8 a 1
2 9 b 2
3 10 c 3
4 11 d 4
Method 1: Using transpose and rev methods
The rev() method reverses the order of the matrix on the basis of columns. The idea here lays its approach towards the foundational concepts that transpose of a transposed matrix is equivalent to the original matrix.
Syntax:
t( t( M) ) = M
Where M is the matrix or dataframe.
The transpose of the dataframe is taken, which interchanges the order of rows and columns of the dataframe. Now, the rows become the columns and columns become rows respectively. The resultant transposed matrix is converted to a dataframe using the as.data.frame() method. The rev() method is applied over this transposed dataframe. This reverses the order of rows in the dataframe. The reversed dataframe needs to be transposed again in order to display the dataframe properly. Hence, the dataframe is returned to the original format. The explicit conversion of this output to a dataframe using as.data.frame() is then made.
Example:
R
# declaring a dataframe in Rdata_frame <- data.frame(col1 = c(1:4), col2 = letters[1:4], col3 = c(8:11)) print ("Original Dataframe")print (data_frame) # transpose of dataframetranspose <- t(data_frame) # converting the result to dataframetranspose <- as.data.frame(transpose) # calculating reverse of dataframerev_data_frame <- rev(transpose) # transpose of reverse dataframerev_data_frame <- t(rev_data_frame) # converting the result to dataframerev_data_frame <- as.data.frame(rev_data_frame) print ("Modified Dataframe")print (rev_data_frame)
Output
[1] "Original Dataframe"
col1 col2 col3
1 1 a 8
2 2 b 9
3 3 c 10
4 4 d 11
[1] "Modified Dataframe"
col1 col2 col3
V4 4 d 11
V3 3 c 10
V2 2 b 9
V1 1 a 8
Method 2: Using apply method
apply() method in R is used to apply a specified function over the R object, vector, dataframe, or matrix. This method returns a vector or array or list of values obtained by applying the function to the corresponding of an array or matrix.
Syntax:
apply(df , axis, FUN, ...)
Parameter :
df – A dataframe or matrix
axis – The axis over which to apply the function. For a dataframe, 1 indicates rows, 2 indicates columns and c(1, 2) indicates rows and columns.
FUN – The function to be applied.
In this approach, the rev function computes the reverse of the dataframe across the rows’ axis.
Example:
R
# declaring a dataframe in Rdata_frame <- data.frame(col1 = c(1:4), col2 = letters[1:4], col3 = c(8:11)) print ("Original Dataframe")print (data_frame) # calculating reverserev_data_frame <- apply(data_frame, 2, rev) # converting the result to dataframerev_data_frame <- as.data.frame(rev_data_frame) print ("Modified Dataframe")print (rev_data_frame)
Output
[1] "Original Dataframe"
col1 col2 col3
1 1 a 8
2 2 b 9
3 3 c 10
4 4 d 11
[1] "Modified Dataframe"
col1 col2 col3
1 4 d 11
2 3 c 10
3 2 b 9
4 1 a 8
sweetyty
sagartomar9927
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Dec, 2021"
},
{
"code": null,
"e": 272,
"s": 28,
"text": "Order reversal of the dataframe involves swapping of the rows or columns in such a way, that the elements are accessed from backward. In this article, we will discuss various ways of reversing the order of a dataframe both column and row-wise."
},
{
"code": null,
"e": 303,
"s": 272,
"text": "Method 1: Using the rev method"
},
{
"code": null,
"e": 670,
"s": 303,
"text": "The rev() method in R is used to return the reversed order of the R object, be it dataframe or a vector. It computes the reverse columns by default. The resultant dataframe returns the last column first followed by the previous columns. The ordering of the rows remains unmodified. The result has to be stored in a new variable in order to retain the modifications. "
},
{
"code": null,
"e": 678,
"s": 670,
"text": "Syntax:"
},
{
"code": null,
"e": 687,
"s": 678,
"text": "rev (df)"
},
{
"code": null,
"e": 714,
"s": 687,
"text": "Where df is the dataframe."
},
{
"code": null,
"e": 723,
"s": 714,
"text": "Example:"
},
{
"code": null,
"e": 725,
"s": 723,
"text": "R"
},
{
"code": "# declaring a dataframe in Rdata_frame <- data.frame(col1 = c(1:4), col2 = letters[1:4], col3 = c(8:11)) print (\"Original Dataframe\")print (data_frame) # calculating reverse of dataframerev_data_frame <- rev(data_frame) print (\"Modified Dataframe\")print (rev_data_frame)",
"e": 1044,
"s": 725,
"text": null
},
{
"code": null,
"e": 1051,
"s": 1044,
"text": "Output"
},
{
"code": null,
"e": 1269,
"s": 1051,
"text": "[1] \"Original Dataframe\"\n col1 col2 col3\n1 1 a 8\n2 2 b 9\n3 3 c 10\n4 4 d 11\n[1] \"Modified Dataframe\"\n col3 col2 col1\n1 8 a 1\n2 9 b 2\n3 10 c 3\n4 11 d 4"
},
{
"code": null,
"e": 1297,
"s": 1269,
"text": "Method 2: Using ncol method"
},
{
"code": null,
"e": 1482,
"s": 1297,
"text": "ncol() method in R is used to return the number of columns of the specified dataframe. The dataframe is accessed from the last column index to the first column index range, that is 1. "
},
{
"code": null,
"e": 1491,
"s": 1482,
"text": "Example:"
},
{
"code": null,
"e": 1493,
"s": 1491,
"text": "R"
},
{
"code": "# declaring a dataframe in Rdata_frame <- data.frame(col1 = c(1:4), col2 = letters[1:4], col3 = c(8:11)) print (\"Original Dataframe\")print (data_frame) # computing reverserev_data_frame <- data_frame[,ncol(data_frame):1 ] print (\"Modified Dataframe\")print (rev_data_frame)",
"e": 1814,
"s": 1493,
"text": null
},
{
"code": null,
"e": 1821,
"s": 1814,
"text": "Output"
},
{
"code": null,
"e": 2037,
"s": 1821,
"text": "[1] \"Original Dataframe\"\ncol1 col2 col3\n1 1 a 8\n2 2 b 9\n3 3 c 10\n4 4 d 11\n[1] \"Modified Dataframe\"\ncol3 col2 col1\n1 8 a 1\n2 9 b 2\n3 10 c 3\n4 11 d 4"
},
{
"code": null,
"e": 2079,
"s": 2037,
"text": "Method 1: Using transpose and rev methods"
},
{
"code": null,
"e": 2296,
"s": 2079,
"text": "The rev() method reverses the order of the matrix on the basis of columns. The idea here lays its approach towards the foundational concepts that transpose of a transposed matrix is equivalent to the original matrix."
},
{
"code": null,
"e": 2305,
"s": 2296,
"text": "Syntax: "
},
{
"code": null,
"e": 2321,
"s": 2305,
"text": "t( t( M) ) = M "
},
{
"code": null,
"e": 2357,
"s": 2321,
"text": "Where M is the matrix or dataframe."
},
{
"code": null,
"e": 2984,
"s": 2357,
"text": "The transpose of the dataframe is taken, which interchanges the order of rows and columns of the dataframe. Now, the rows become the columns and columns become rows respectively. The resultant transposed matrix is converted to a dataframe using the as.data.frame() method. The rev() method is applied over this transposed dataframe. This reverses the order of rows in the dataframe. The reversed dataframe needs to be transposed again in order to display the dataframe properly. Hence, the dataframe is returned to the original format. The explicit conversion of this output to a dataframe using as.data.frame() is then made. "
},
{
"code": null,
"e": 2993,
"s": 2984,
"text": "Example:"
},
{
"code": null,
"e": 2995,
"s": 2993,
"text": "R"
},
{
"code": "# declaring a dataframe in Rdata_frame <- data.frame(col1 = c(1:4), col2 = letters[1:4], col3 = c(8:11)) print (\"Original Dataframe\")print (data_frame) # transpose of dataframetranspose <- t(data_frame) # converting the result to dataframetranspose <- as.data.frame(transpose) # calculating reverse of dataframerev_data_frame <- rev(transpose) # transpose of reverse dataframerev_data_frame <- t(rev_data_frame) # converting the result to dataframerev_data_frame <- as.data.frame(rev_data_frame) print (\"Modified Dataframe\")print (rev_data_frame)",
"e": 3590,
"s": 2995,
"text": null
},
{
"code": null,
"e": 3597,
"s": 3590,
"text": "Output"
},
{
"code": null,
"e": 3820,
"s": 3597,
"text": "[1] \"Original Dataframe\"\n col1 col2 col3\n1 1 a 8\n2 2 b 9\n3 3 c 10\n4 4 d 11\n[1] \"Modified Dataframe\"\n col1 col2 col3\nV4 4 d 11\nV3 3 c 10\nV2 2 b 9\nV1 1 a 8"
},
{
"code": null,
"e": 3849,
"s": 3820,
"text": "Method 2: Using apply method"
},
{
"code": null,
"e": 4090,
"s": 3849,
"text": "apply() method in R is used to apply a specified function over the R object, vector, dataframe, or matrix. This method returns a vector or array or list of values obtained by applying the function to the corresponding of an array or matrix."
},
{
"code": null,
"e": 4098,
"s": 4090,
"text": "Syntax:"
},
{
"code": null,
"e": 4125,
"s": 4098,
"text": "apply(df , axis, FUN, ...)"
},
{
"code": null,
"e": 4138,
"s": 4125,
"text": "Parameter : "
},
{
"code": null,
"e": 4165,
"s": 4138,
"text": "df – A dataframe or matrix"
},
{
"code": null,
"e": 4310,
"s": 4165,
"text": "axis – The axis over which to apply the function. For a dataframe, 1 indicates rows, 2 indicates columns and c(1, 2) indicates rows and columns."
},
{
"code": null,
"e": 4345,
"s": 4310,
"text": "FUN – The function to be applied. "
},
{
"code": null,
"e": 4442,
"s": 4345,
"text": "In this approach, the rev function computes the reverse of the dataframe across the rows’ axis. "
},
{
"code": null,
"e": 4451,
"s": 4442,
"text": "Example:"
},
{
"code": null,
"e": 4453,
"s": 4451,
"text": "R"
},
{
"code": "# declaring a dataframe in Rdata_frame <- data.frame(col1 = c(1:4), col2 = letters[1:4], col3 = c(8:11)) print (\"Original Dataframe\")print (data_frame) # calculating reverserev_data_frame <- apply(data_frame, 2, rev) # converting the result to dataframerev_data_frame <- as.data.frame(rev_data_frame) print (\"Modified Dataframe\")print (rev_data_frame)",
"e": 4853,
"s": 4453,
"text": null
},
{
"code": null,
"e": 4860,
"s": 4853,
"text": "Output"
},
{
"code": null,
"e": 5078,
"s": 4860,
"text": "[1] \"Original Dataframe\"\n col1 col2 col3\n1 1 a 8\n2 2 b 9\n3 3 c 10\n4 4 d 11\n[1] \"Modified Dataframe\"\n col1 col2 col3\n1 4 d 11\n2 3 c 10\n3 2 b 9\n4 1 a 8"
},
{
"code": null,
"e": 5087,
"s": 5078,
"text": "sweetyty"
},
{
"code": null,
"e": 5102,
"s": 5087,
"text": "sagartomar9927"
},
{
"code": null,
"e": 5109,
"s": 5102,
"text": "Picked"
},
{
"code": null,
"e": 5130,
"s": 5109,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 5142,
"s": 5130,
"text": "R-DataFrame"
},
{
"code": null,
"e": 5153,
"s": 5142,
"text": "R Language"
},
{
"code": null,
"e": 5164,
"s": 5153,
"text": "R Programs"
}
] |
Servers, streams and sockets in Node
|
30 Apr, 2019
Node.js is a javascript framework for writing Server-side applications.A Node.js server provides the mechanisms for connecting to a service and sending/receiving data. It achieves this through TCP or UDP connections. Developers can hence create their own server and test their app deployment.NodeJS comes with a simple HTTP server built-in. This HTTP server allows us to listen on an arbitrary port(specified by us) and receive callbacks via a callback function that will be invoked every time a request is made to the server.The callback will receive two arguments: a Request object and a Response object. The Request object will be filled with useful properties about the request, and the Response object will be used to send a response to the client.
const http = require('http'); const hostname = '127.0.0.1';const port = 8081; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello, Welcome to GeeksforGeeks !\n');}); server.listen(port, hostname, () => { console.log(`Your Node.js server is running at http://${hostname}:${port}/`);});
Now to execute this file from terminal simply write:-
node server.js
and you’ll see:
And on navigating to the specified url a simple HTML page will open displaying :
Hence, we created a local Node.js web server listening on port 8081.
Streams are collections of data — just like arrays or strings. A stream is an abstract interface for working with streaming data in Node.js. The stream module provides a base API that makes it easy to build objects that implement the stream interface. In Node.js, there are four types of streams –
Writable – streams to which data can be written.Readable – streams from which data can be read.Duplex – streams that are both Readable and Writable.Transform – Duplex streams that can modify or transform the data as it is written and read
Using Node.js streams we can modify and transform data.
Create a text file with any arbitrary content. For example – Node.txt with the following content-
Welcome to Nodejs streams usage. Read this file.
Create a js file ,example- read.js ,with the following content-
var fs = require("fs"); //using the Node fs module you can read a filevar data = ''; // Create a read stream with your text file name in quotes (Node.txt)var readerStream = fs.createReadStream('Node.txt'); readerStream.setEncoding('UTF8'); //Stream events-//'data','end','error'----see details at https://nodejs.org/api/stream.html#stream_class_stream_readable readerStream.on('data', function(chunk) { data += chunk;}); readerStream.on('end',function() { console.log(data);}); readerStream.on('error', function(err) { console.log(err.stack);}); console.log("Reading complete");
Now run the above read.js file to see the output-
Create a js file ,example- write.js ,with the following content-
var fs = require("fs"); //data variable containing the data to be written to the filevar data = 'Hello welcome to Node.js tutorials on GeeksforGeeks'; // Create a writable stream with the output file name in quotes (Node1.txt)var writerStream = fs.createWriteStream('Node1.txt'); // utf8 encodingwriterStream.write(data,'UTF8'); //end of filewriterStream.end(); // Handle stream events --> finish, and errorwriterStream.on('finish', function() { console.log("Write completed.");}); writerStream.on('error', function(err) { console.log(err.stack);}); console.log("You've successfully created Node1.txt");
Execute the above file-
And the text file has been created. To check-
Here we are talking in reference to “net” module of Node.js and not referring Socket.IO -a library that enables real-time, bidirectional and event-based communication between the browser and the server.
The net module provides an asynchronous network API for creating stream-based TCP or IPC servers (net.createServer()) and clients (net.createConnection()).
“net.Socket” is a class that is an abstraction of a TCP socket or a streaming IPC endpoint, and is also a duplex stream so it can be used for both reading and writing data.
A net.Socket can be created by the user and used directly to interact with a server. For example, it is returned by net.createConnection(), so the user can use it to talk to the server.
It can also be created by Node.js and passed to the user when a connection is received. For example, it is passed to the listeners of a ‘connection’ event emitted on a net.Server, so the user can use it to interact with the client.
For example to create a test socket in Node.js create a file ,example- test.js, with the following content-
// serverrequire('net').createServer(function (socket) { console.log("connected"); socket.on('data', function (data) { console.log(data.toString()); });}) .listen(8082); // clientvar s = require('net').Socket();s.connect(8082);s.write('Hello');s.end();
Running the above file creates a client-server model and returns-
net.Socket comes with many functions and events like-
Event: ‘close’-Added in: v0.1.90hadError true if the socket had a transmission error.Emitted once the socket is fully closed. The argument hadError is a boolean which says if the socket was closed due to a transmission error.
Event: ‘connect’-Added in: v0.1.90Emitted when a socket connection is successfully established. See net.createConnection().
socket.address()[src]-Added in: v0.1.90Returns:Returns the bound address, the address family name and port of the socket as reported by the operating system: { port: 12346, family: ‘IPv4’, address: ‘127.0.0.1’ }
socket.bytesRead-Added in: v0.5.3The amount of received bytes.
socket.bytesWritten-Added in: v0.5.3The number of bytes sent.
Further can be explored at the official documentation of Node.js mentioned in the references.
1.)https://nodejs.org/api/2.)https://nodejs.org/en/docs/
Picked
Web technologies
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 Apr, 2019"
},
{
"code": null,
"e": 806,
"s": 52,
"text": "Node.js is a javascript framework for writing Server-side applications.A Node.js server provides the mechanisms for connecting to a service and sending/receiving data. It achieves this through TCP or UDP connections. Developers can hence create their own server and test their app deployment.NodeJS comes with a simple HTTP server built-in. This HTTP server allows us to listen on an arbitrary port(specified by us) and receive callbacks via a callback function that will be invoked every time a request is made to the server.The callback will receive two arguments: a Request object and a Response object. The Request object will be filled with useful properties about the request, and the Response object will be used to send a response to the client."
},
{
"code": "const http = require('http'); const hostname = '127.0.0.1';const port = 8081; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello, Welcome to GeeksforGeeks !\\n');}); server.listen(port, hostname, () => { console.log(`Your Node.js server is running at http://${hostname}:${port}/`);});",
"e": 1177,
"s": 806,
"text": null
},
{
"code": null,
"e": 1231,
"s": 1177,
"text": "Now to execute this file from terminal simply write:-"
},
{
"code": "node server.js",
"e": 1246,
"s": 1231,
"text": null
},
{
"code": null,
"e": 1262,
"s": 1246,
"text": "and you’ll see:"
},
{
"code": null,
"e": 1343,
"s": 1262,
"text": "And on navigating to the specified url a simple HTML page will open displaying :"
},
{
"code": null,
"e": 1412,
"s": 1343,
"text": "Hence, we created a local Node.js web server listening on port 8081."
},
{
"code": null,
"e": 1710,
"s": 1412,
"text": "Streams are collections of data — just like arrays or strings. A stream is an abstract interface for working with streaming data in Node.js. The stream module provides a base API that makes it easy to build objects that implement the stream interface. In Node.js, there are four types of streams –"
},
{
"code": null,
"e": 1949,
"s": 1710,
"text": "Writable – streams to which data can be written.Readable – streams from which data can be read.Duplex – streams that are both Readable and Writable.Transform – Duplex streams that can modify or transform the data as it is written and read"
},
{
"code": null,
"e": 2005,
"s": 1949,
"text": "Using Node.js streams we can modify and transform data."
},
{
"code": null,
"e": 2103,
"s": 2005,
"text": "Create a text file with any arbitrary content. For example – Node.txt with the following content-"
},
{
"code": null,
"e": 2153,
"s": 2103,
"text": "Welcome to Nodejs streams usage. Read this file.\n"
},
{
"code": null,
"e": 2217,
"s": 2153,
"text": "Create a js file ,example- read.js ,with the following content-"
},
{
"code": "var fs = require(\"fs\"); //using the Node fs module you can read a filevar data = ''; // Create a read stream with your text file name in quotes (Node.txt)var readerStream = fs.createReadStream('Node.txt'); readerStream.setEncoding('UTF8'); //Stream events-//'data','end','error'----see details at https://nodejs.org/api/stream.html#stream_class_stream_readable readerStream.on('data', function(chunk) { data += chunk;}); readerStream.on('end',function() { console.log(data);}); readerStream.on('error', function(err) { console.log(err.stack);}); console.log(\"Reading complete\");",
"e": 2810,
"s": 2217,
"text": null
},
{
"code": null,
"e": 2860,
"s": 2810,
"text": "Now run the above read.js file to see the output-"
},
{
"code": null,
"e": 2925,
"s": 2860,
"text": "Create a js file ,example- write.js ,with the following content-"
},
{
"code": "var fs = require(\"fs\"); //data variable containing the data to be written to the filevar data = 'Hello welcome to Node.js tutorials on GeeksforGeeks'; // Create a writable stream with the output file name in quotes (Node1.txt)var writerStream = fs.createWriteStream('Node1.txt'); // utf8 encodingwriterStream.write(data,'UTF8'); //end of filewriterStream.end(); // Handle stream events --> finish, and errorwriterStream.on('finish', function() { console.log(\"Write completed.\");}); writerStream.on('error', function(err) { console.log(err.stack);}); console.log(\"You've successfully created Node1.txt\");",
"e": 3541,
"s": 2925,
"text": null
},
{
"code": null,
"e": 3565,
"s": 3541,
"text": "Execute the above file-"
},
{
"code": null,
"e": 3611,
"s": 3565,
"text": "And the text file has been created. To check-"
},
{
"code": null,
"e": 3814,
"s": 3611,
"text": "Here we are talking in reference to “net” module of Node.js and not referring Socket.IO -a library that enables real-time, bidirectional and event-based communication between the browser and the server."
},
{
"code": null,
"e": 3970,
"s": 3814,
"text": "The net module provides an asynchronous network API for creating stream-based TCP or IPC servers (net.createServer()) and clients (net.createConnection())."
},
{
"code": null,
"e": 4143,
"s": 3970,
"text": "“net.Socket” is a class that is an abstraction of a TCP socket or a streaming IPC endpoint, and is also a duplex stream so it can be used for both reading and writing data."
},
{
"code": null,
"e": 4329,
"s": 4143,
"text": "A net.Socket can be created by the user and used directly to interact with a server. For example, it is returned by net.createConnection(), so the user can use it to talk to the server."
},
{
"code": null,
"e": 4561,
"s": 4329,
"text": "It can also be created by Node.js and passed to the user when a connection is received. For example, it is passed to the listeners of a ‘connection’ event emitted on a net.Server, so the user can use it to interact with the client."
},
{
"code": null,
"e": 4669,
"s": 4561,
"text": "For example to create a test socket in Node.js create a file ,example- test.js, with the following content-"
},
{
"code": "// serverrequire('net').createServer(function (socket) { console.log(\"connected\"); socket.on('data', function (data) { console.log(data.toString()); });}) .listen(8082); // clientvar s = require('net').Socket();s.connect(8082);s.write('Hello');s.end();",
"e": 4942,
"s": 4669,
"text": null
},
{
"code": null,
"e": 5008,
"s": 4942,
"text": "Running the above file creates a client-server model and returns-"
},
{
"code": null,
"e": 5062,
"s": 5008,
"text": "net.Socket comes with many functions and events like-"
},
{
"code": null,
"e": 5288,
"s": 5062,
"text": "Event: ‘close’-Added in: v0.1.90hadError true if the socket had a transmission error.Emitted once the socket is fully closed. The argument hadError is a boolean which says if the socket was closed due to a transmission error."
},
{
"code": null,
"e": 5412,
"s": 5288,
"text": "Event: ‘connect’-Added in: v0.1.90Emitted when a socket connection is successfully established. See net.createConnection()."
},
{
"code": null,
"e": 5624,
"s": 5412,
"text": "socket.address()[src]-Added in: v0.1.90Returns:Returns the bound address, the address family name and port of the socket as reported by the operating system: { port: 12346, family: ‘IPv4’, address: ‘127.0.0.1’ }"
},
{
"code": null,
"e": 5687,
"s": 5624,
"text": "socket.bytesRead-Added in: v0.5.3The amount of received bytes."
},
{
"code": null,
"e": 5749,
"s": 5687,
"text": "socket.bytesWritten-Added in: v0.5.3The number of bytes sent."
},
{
"code": null,
"e": 5843,
"s": 5749,
"text": "Further can be explored at the official documentation of Node.js mentioned in the references."
},
{
"code": null,
"e": 5900,
"s": 5843,
"text": "1.)https://nodejs.org/api/2.)https://nodejs.org/en/docs/"
},
{
"code": null,
"e": 5907,
"s": 5900,
"text": "Picked"
},
{
"code": null,
"e": 5924,
"s": 5907,
"text": "Web technologies"
},
{
"code": null,
"e": 5941,
"s": 5924,
"text": "Web Technologies"
}
] |
How to refresh a file in Node.js ?
|
13 Feb, 2020
Node.js has seen an important growth in past years and is still increasing its value in many organizations and business models. Companies like Walmart or PayPal have already started to adopt it.NPM, the package manager of Node.js has been already installed when you install Node.js and is ready to run on your computer. Node.js doesn’t offer you the privilege of automatic restart like other languages such as PHP or Ruby. Whenever you make changes in your source code, you need to run the code again and again by using command.
Most of us are used to save the file in Editor and then hit [ctrl + c] (To stop application) & then restart by hitting again [UP arrow + Enter]. However rather than doing this repetitive task manually, we can certainly automate it and can make the process more easier by using some tools:
nodemonnode-supervisorforever
nodemon
node-supervisor
forever
1. nodemin: Among all those tools, we would like to start with nodemon first. Basically, Nodemon is a utility that monitor for any changes in your source and automatically restart your server.
Installation Command:
npm install nodemon -g
After installing the nodemon utility we will use the following command to run the code.
nodemon filename.js
2. node-supervisor:Installation Command
npm install supervisor -g
After installing the node-supervisor we will use the following command to run the code.
supervisor filename.js
3. forever: The remaining tool so called forever is a node.js package that is used to keep server alive even when it crashes or stops because of some error/exception. Forever automatically restarts it.Installation Command
npm install forever -g
frorever start filename.js
Picked
Technical Scripter 2019
Node.js
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 Feb, 2020"
},
{
"code": null,
"e": 583,
"s": 54,
"text": "Node.js has seen an important growth in past years and is still increasing its value in many organizations and business models. Companies like Walmart or PayPal have already started to adopt it.NPM, the package manager of Node.js has been already installed when you install Node.js and is ready to run on your computer. Node.js doesn’t offer you the privilege of automatic restart like other languages such as PHP or Ruby. Whenever you make changes in your source code, you need to run the code again and again by using command."
},
{
"code": null,
"e": 872,
"s": 583,
"text": "Most of us are used to save the file in Editor and then hit [ctrl + c] (To stop application) & then restart by hitting again [UP arrow + Enter]. However rather than doing this repetitive task manually, we can certainly automate it and can make the process more easier by using some tools:"
},
{
"code": null,
"e": 902,
"s": 872,
"text": "nodemonnode-supervisorforever"
},
{
"code": null,
"e": 910,
"s": 902,
"text": "nodemon"
},
{
"code": null,
"e": 926,
"s": 910,
"text": "node-supervisor"
},
{
"code": null,
"e": 934,
"s": 926,
"text": "forever"
},
{
"code": null,
"e": 1127,
"s": 934,
"text": "1. nodemin: Among all those tools, we would like to start with nodemon first. Basically, Nodemon is a utility that monitor for any changes in your source and automatically restart your server."
},
{
"code": null,
"e": 1149,
"s": 1127,
"text": "Installation Command:"
},
{
"code": null,
"e": 1172,
"s": 1149,
"text": "npm install nodemon -g"
},
{
"code": null,
"e": 1260,
"s": 1172,
"text": "After installing the nodemon utility we will use the following command to run the code."
},
{
"code": null,
"e": 1280,
"s": 1260,
"text": "nodemon filename.js"
},
{
"code": null,
"e": 1320,
"s": 1280,
"text": "2. node-supervisor:Installation Command"
},
{
"code": null,
"e": 1346,
"s": 1320,
"text": "npm install supervisor -g"
},
{
"code": null,
"e": 1434,
"s": 1346,
"text": "After installing the node-supervisor we will use the following command to run the code."
},
{
"code": null,
"e": 1457,
"s": 1434,
"text": "supervisor filename.js"
},
{
"code": null,
"e": 1679,
"s": 1457,
"text": "3. forever: The remaining tool so called forever is a node.js package that is used to keep server alive even when it crashes or stops because of some error/exception. Forever automatically restarts it.Installation Command"
},
{
"code": null,
"e": 1702,
"s": 1679,
"text": "npm install forever -g"
},
{
"code": null,
"e": 1729,
"s": 1702,
"text": "frorever start filename.js"
},
{
"code": null,
"e": 1736,
"s": 1729,
"text": "Picked"
},
{
"code": null,
"e": 1760,
"s": 1736,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 1768,
"s": 1760,
"text": "Node.js"
},
{
"code": null,
"e": 1787,
"s": 1768,
"text": "Technical Scripter"
},
{
"code": null,
"e": 1804,
"s": 1787,
"text": "Web Technologies"
}
] |
Data cleaning in Python: examples from cleaning Airbnb data | Towards Data Science
|
Airbnb fascinates me. I previously worked for a year and a half at an Airbnb property management company, as head of the team responsible for pricing, revenue and analysis. One thing I find particularly interesting is how to figure out what price to charge for a listing on the site. Although ‘it’s a two bedroom in Manchester’ will get you reasonably far, there are actually a huge number of factors that can influence a listing’s price.
As part of a bigger project on using deep learning to predict Airbnb prices, I found myself thrown back into the murky world of property data. Geospatial data can be very complex and messy — and user-entered geospatial data doubly so. This post will explain how I went about sourcing and preparing the data for my project, including some thoughts on dealing with UK geographic data (it’s surprisingly complicated) and extracting relevant information from long text strings.
The dataset used for this project comes from Insideairbnb.com, an anti-Airbnb lobby group that scrapes Airbnb listings, reviews and calendar data from multiple cities around the world. The dataset was scraped on 9 April 2019 and contains information on all London Airbnb listings that were live on the site on that date (about 80,000).
For the full exciting details (disclosure: level of excitement may vary) of data cleaning, feel free to check out my GitHub repo. In the interests of brevity, I’ll discuss three particular areas of data pre-processing that might be of interest.
The original dataset contained 106 features, including quite a few text columns of all the different description fields that you can fill in for an Airbnb listing. Due to time constraints I did not do any natural language processing (NLP) in this model, so all these features were dropped. However, an interesting avenue of future development for this model would be to augment it with NLP — perhaps for sentiment analysis, or looking for keywords, or some sort of fancy Word2Vec type situation that looks for similar listing descriptions and uses this to help guess price based on similar listings.
Another potential direction of future work could include reviews. Insideairbnb.com also scrapes reviews, which can be matched to listings with their listing IDs. Although most guests tend to give most listings high ratings, more nuanced ratings could perhaps be derived from the reviews themselves.
Postcodes in the UK are complicated and messy. They can be various lengths, and consist of letters and numbers in various orders. The first half of a postcode is called the outcode or postcode district, and refers to areas as shown here:
Just to make things more complicated, the main geographic division of London is into 32 boroughs plus the City of London (technically a Corporation rather than a borough due to some quirks of 12th Century English history), which do not align with postcode districts (because that would be too easy, right?):
There also aren’t any easy ways of classifying London areas on a less granular level. In fact, there is not even agreement on what counts as ‘inner London’:
And to make matters even worse, it turns out Airbnb allows hosts to enter postcodes in a free text entry box, precluding any easy separation of parts of postcodes, and allowing hosts to write all kinds of nonsense (my favourite is just the word ‘no’).
In the end, after discarding a bunch of regex experimentation with postcodes, I settled on using borough as the unit of geography. Location is very important for Airbnb listings, and so I was not entirely happy about having to use borough. It is not on a particularly fine-grained level, and does not always express well whether a property is in central London or out in the sticks — which makes a huge difference to price. For example, the famous Shard skyscraper is in Southwark, but so is Dulwich , where the tube doesn’t even reach (disclaimer: Dulwich is actually lovely, but is probably less well known to tourists in London).
I did also experiment with using latitude and longitude instead of borough in order to get more fine-grained results — but as a future blog post will show, it was not entirely successful.
In the dataset from Insiderairbnb.com, amenities were stored as one big block of text— here’s one example:
In order to figure out what the various options were and which listings had them, I first made a giant string of all the amenities values, tidied it up a bit, split out the individual amenities separated by commas, and created a set of the resultant list (fortunately the dataset was small enough to allow this, but I would have needed a more efficient way to do this with a much larger dataset):
And here’s a list of all the amenities it is possible to have:
'24-hour check-in', 'Accessible-height bed', 'Accessible-height toilet', 'Air conditioning', 'Air purifier', 'Alfresco bathtub', 'Amazon Echo', 'Apple TV', 'BBQ grill', 'Baby bath', 'Baby monitor', 'Babysitter recommendations', 'Balcony', 'Bath towel', 'Bathroom essentials', 'Bathtub', 'Bathtub with bath chair', 'Beach essentials', 'Beach view', 'Beachfront', 'Bed linens', 'Bedroom comforts', 'Bidet', 'Body soap', 'Breakfast', 'Breakfast bar', 'Breakfast table', 'Building staff', 'Buzzer/wireless intercom', 'Cable TV', 'Carbon monoxide detector', 'Cat(s)', 'Ceiling fan', 'Ceiling hoist', 'Central air conditioning', 'Changing table', "Chef's kitchen", 'Children’s books and toys', 'Children’s dinnerware', 'Cleaning before checkout', 'Coffee maker', 'Convection oven', 'Cooking basics', 'Crib', 'DVD player', 'Day bed', 'Dining area', 'Disabled parking spot', 'Dishes and silverware', 'Dishwasher', 'Dog(s)', 'Doorman', 'Double oven', 'Dryer', 'EV charger', 'Electric profiling bed', 'Elevator', 'En suite bathroom', 'Espresso machine', 'Essentials', 'Ethernet connection', 'Exercise equipment', 'Extra pillows and blankets', 'Family/kid friendly', 'Fax machine', 'Fire extinguisher', 'Fire pit', 'Fireplace guards', 'Firm mattress', 'First aid kit', 'Fixed grab bars for shower', 'Fixed grab bars for toilet', 'Flat path to front door', 'Formal dining area', 'Free parking on premises', 'Free street parking', 'Full kitchen', 'Game console', 'Garden or backyard', 'Gas oven', 'Ground floor access', 'Gym', 'HBO GO', 'Hair dryer', 'Hammock', 'Handheld shower head', 'Hangers', 'Heat lamps', 'Heated floors', 'Heated towel rack', 'Heating', 'High chair', 'High-resolution computer monitor', 'Host greets you', 'Hot tub', 'Hot water', 'Hot water kettle', 'Indoor fireplace', 'Internet', 'Iron', 'Ironing Board', 'Jetted tub', 'Keypad', 'Kitchen', 'Kitchenette', 'Lake access', 'Laptop friendly workspace', 'Lock on bedroom door', 'Lockbox', 'Long term stays allowed', 'Luggage dropoff allowed', 'Memory foam mattress', 'Microwave', 'Mini fridge', 'Mobile hoist', 'Mountain view', 'Mudroom', 'Murphy bed', 'Netflix', 'Office', 'Other', 'Other pet(s)', 'Outdoor kitchen', 'Outdoor parking', 'Outdoor seating', 'Outlet covers', 'Oven', 'Pack ’n Play/travel crib', 'Paid parking off premises', 'Paid parking on premises', 'Patio or balcony', 'Pets allowed', 'Pets live on this property', 'Pillow-top mattress', 'Pocket wifi', 'Pool', 'Pool cover', 'Pool with pool hoist', 'Printer', 'Private bathroom', 'Private entrance', 'Private gym', 'Private hot tub', 'Private living room', 'Private pool', 'Projector and screen', 'Propane barbeque', 'Rain shower', 'Refrigerator', 'Roll-in shower', 'Room-darkening shades', 'Safe', 'Safety card', 'Sauna', 'Security system', 'Self check-in', 'Shampoo', 'Shared gym', 'Shared hot tub', 'Shared pool', 'Shower chair', 'Single level home', 'Ski-in/Ski-out', 'Smart TV', 'Smart lock', 'Smoke detector', 'Smoking allowed', 'Soaking tub', 'Sound system', 'Stair gates', 'Stand alone steam shower', 'Standing valet', 'Steam oven', 'Step-free access', 'Stove', 'Suitable for events', 'Sun loungers', 'TV', 'Table corner guards', 'Tennis court', 'Terrace', 'Toilet paper', 'Touchless faucets', 'Walk-in shower', 'Warming drawer', 'Washer', 'Washer / Dryer', 'Waterfront', 'Well-lit path to entrance', 'Wheelchair accessible', 'Wide clearance to bed', 'Wide clearance to shower', 'Wide doorway', 'Wide entryway', 'Wide hallway clearance', 'Wifi', 'Window guards', 'Wine cooler', 'toilet',
In the list above, some amenities are more important than others (e.g. a balcony is more likely to increase price than a fax machine), and some are likely to be fairly uncommon (e.g. ‘Electric profiling bed’). Based on previous experience in the industry, and furtherresearch into which amenities are considered by guests to be more important, a selection of the more important amenities were extracted. These were then selected from for inclusion in the final model depending on how sparse the data was. For example, if it turns out that almost all properties have/do not have a particular amenity, that feature will not be very useful in differentiating between listings or helping explain differences in prices.
The whole convoluted code for this can be found on GitHub, but this is the final section where I removed columns where over 90% of the listings either had or did not have a particular amenity:
These are the amenities that I ended up keeping:
Balcony
Bed linen
Breakfast
TV
Coffee machine
Basic cooking equipment
White goods (specifically a washer, dryer and/or dishwasher)
Child-friendly
Parking
Outdoor space
Greeted by host
Internet
Long term stays allowed
Pets allowed
Private entrance
Safe or security system
Self check-in
After these (and many other) cleaning and pre-processing steps, the Airbnb was in suitable form to begin exploration and modelling, and you can read more about this in my next post on data exploration, and another post I wrote about building a predictive model.
If you found this post interesting or helpful, please let me know via the medium of claps and/or comments, and you can follow me in order to be notified about future posts. Thanks for reading!
|
[
{
"code": null,
"e": 611,
"s": 172,
"text": "Airbnb fascinates me. I previously worked for a year and a half at an Airbnb property management company, as head of the team responsible for pricing, revenue and analysis. One thing I find particularly interesting is how to figure out what price to charge for a listing on the site. Although ‘it’s a two bedroom in Manchester’ will get you reasonably far, there are actually a huge number of factors that can influence a listing’s price."
},
{
"code": null,
"e": 1085,
"s": 611,
"text": "As part of a bigger project on using deep learning to predict Airbnb prices, I found myself thrown back into the murky world of property data. Geospatial data can be very complex and messy — and user-entered geospatial data doubly so. This post will explain how I went about sourcing and preparing the data for my project, including some thoughts on dealing with UK geographic data (it’s surprisingly complicated) and extracting relevant information from long text strings."
},
{
"code": null,
"e": 1421,
"s": 1085,
"text": "The dataset used for this project comes from Insideairbnb.com, an anti-Airbnb lobby group that scrapes Airbnb listings, reviews and calendar data from multiple cities around the world. The dataset was scraped on 9 April 2019 and contains information on all London Airbnb listings that were live on the site on that date (about 80,000)."
},
{
"code": null,
"e": 1666,
"s": 1421,
"text": "For the full exciting details (disclosure: level of excitement may vary) of data cleaning, feel free to check out my GitHub repo. In the interests of brevity, I’ll discuss three particular areas of data pre-processing that might be of interest."
},
{
"code": null,
"e": 2266,
"s": 1666,
"text": "The original dataset contained 106 features, including quite a few text columns of all the different description fields that you can fill in for an Airbnb listing. Due to time constraints I did not do any natural language processing (NLP) in this model, so all these features were dropped. However, an interesting avenue of future development for this model would be to augment it with NLP — perhaps for sentiment analysis, or looking for keywords, or some sort of fancy Word2Vec type situation that looks for similar listing descriptions and uses this to help guess price based on similar listings."
},
{
"code": null,
"e": 2565,
"s": 2266,
"text": "Another potential direction of future work could include reviews. Insideairbnb.com also scrapes reviews, which can be matched to listings with their listing IDs. Although most guests tend to give most listings high ratings, more nuanced ratings could perhaps be derived from the reviews themselves."
},
{
"code": null,
"e": 2803,
"s": 2565,
"text": "Postcodes in the UK are complicated and messy. They can be various lengths, and consist of letters and numbers in various orders. The first half of a postcode is called the outcode or postcode district, and refers to areas as shown here:"
},
{
"code": null,
"e": 3111,
"s": 2803,
"text": "Just to make things more complicated, the main geographic division of London is into 32 boroughs plus the City of London (technically a Corporation rather than a borough due to some quirks of 12th Century English history), which do not align with postcode districts (because that would be too easy, right?):"
},
{
"code": null,
"e": 3268,
"s": 3111,
"text": "There also aren’t any easy ways of classifying London areas on a less granular level. In fact, there is not even agreement on what counts as ‘inner London’:"
},
{
"code": null,
"e": 3520,
"s": 3268,
"text": "And to make matters even worse, it turns out Airbnb allows hosts to enter postcodes in a free text entry box, precluding any easy separation of parts of postcodes, and allowing hosts to write all kinds of nonsense (my favourite is just the word ‘no’)."
},
{
"code": null,
"e": 4153,
"s": 3520,
"text": "In the end, after discarding a bunch of regex experimentation with postcodes, I settled on using borough as the unit of geography. Location is very important for Airbnb listings, and so I was not entirely happy about having to use borough. It is not on a particularly fine-grained level, and does not always express well whether a property is in central London or out in the sticks — which makes a huge difference to price. For example, the famous Shard skyscraper is in Southwark, but so is Dulwich , where the tube doesn’t even reach (disclaimer: Dulwich is actually lovely, but is probably less well known to tourists in London)."
},
{
"code": null,
"e": 4341,
"s": 4153,
"text": "I did also experiment with using latitude and longitude instead of borough in order to get more fine-grained results — but as a future blog post will show, it was not entirely successful."
},
{
"code": null,
"e": 4448,
"s": 4341,
"text": "In the dataset from Insiderairbnb.com, amenities were stored as one big block of text— here’s one example:"
},
{
"code": null,
"e": 4845,
"s": 4448,
"text": "In order to figure out what the various options were and which listings had them, I first made a giant string of all the amenities values, tidied it up a bit, split out the individual amenities separated by commas, and created a set of the resultant list (fortunately the dataset was small enough to allow this, but I would have needed a more efficient way to do this with a much larger dataset):"
},
{
"code": null,
"e": 4908,
"s": 4845,
"text": "And here’s a list of all the amenities it is possible to have:"
},
{
"code": null,
"e": 8429,
"s": 4908,
"text": " '24-hour check-in', 'Accessible-height bed', 'Accessible-height toilet', 'Air conditioning', 'Air purifier', 'Alfresco bathtub', 'Amazon Echo', 'Apple TV', 'BBQ grill', 'Baby bath', 'Baby monitor', 'Babysitter recommendations', 'Balcony', 'Bath towel', 'Bathroom essentials', 'Bathtub', 'Bathtub with bath chair', 'Beach essentials', 'Beach view', 'Beachfront', 'Bed linens', 'Bedroom comforts', 'Bidet', 'Body soap', 'Breakfast', 'Breakfast bar', 'Breakfast table', 'Building staff', 'Buzzer/wireless intercom', 'Cable TV', 'Carbon monoxide detector', 'Cat(s)', 'Ceiling fan', 'Ceiling hoist', 'Central air conditioning', 'Changing table', \"Chef's kitchen\", 'Children’s books and toys', 'Children’s dinnerware', 'Cleaning before checkout', 'Coffee maker', 'Convection oven', 'Cooking basics', 'Crib', 'DVD player', 'Day bed', 'Dining area', 'Disabled parking spot', 'Dishes and silverware', 'Dishwasher', 'Dog(s)', 'Doorman', 'Double oven', 'Dryer', 'EV charger', 'Electric profiling bed', 'Elevator', 'En suite bathroom', 'Espresso machine', 'Essentials', 'Ethernet connection', 'Exercise equipment', 'Extra pillows and blankets', 'Family/kid friendly', 'Fax machine', 'Fire extinguisher', 'Fire pit', 'Fireplace guards', 'Firm mattress', 'First aid kit', 'Fixed grab bars for shower', 'Fixed grab bars for toilet', 'Flat path to front door', 'Formal dining area', 'Free parking on premises', 'Free street parking', 'Full kitchen', 'Game console', 'Garden or backyard', 'Gas oven', 'Ground floor access', 'Gym', 'HBO GO', 'Hair dryer', 'Hammock', 'Handheld shower head', 'Hangers', 'Heat lamps', 'Heated floors', 'Heated towel rack', 'Heating', 'High chair', 'High-resolution computer monitor', 'Host greets you', 'Hot tub', 'Hot water', 'Hot water kettle', 'Indoor fireplace', 'Internet', 'Iron', 'Ironing Board', 'Jetted tub', 'Keypad', 'Kitchen', 'Kitchenette', 'Lake access', 'Laptop friendly workspace', 'Lock on bedroom door', 'Lockbox', 'Long term stays allowed', 'Luggage dropoff allowed', 'Memory foam mattress', 'Microwave', 'Mini fridge', 'Mobile hoist', 'Mountain view', 'Mudroom', 'Murphy bed', 'Netflix', 'Office', 'Other', 'Other pet(s)', 'Outdoor kitchen', 'Outdoor parking', 'Outdoor seating', 'Outlet covers', 'Oven', 'Pack ’n Play/travel crib', 'Paid parking off premises', 'Paid parking on premises', 'Patio or balcony', 'Pets allowed', 'Pets live on this property', 'Pillow-top mattress', 'Pocket wifi', 'Pool', 'Pool cover', 'Pool with pool hoist', 'Printer', 'Private bathroom', 'Private entrance', 'Private gym', 'Private hot tub', 'Private living room', 'Private pool', 'Projector and screen', 'Propane barbeque', 'Rain shower', 'Refrigerator', 'Roll-in shower', 'Room-darkening shades', 'Safe', 'Safety card', 'Sauna', 'Security system', 'Self check-in', 'Shampoo', 'Shared gym', 'Shared hot tub', 'Shared pool', 'Shower chair', 'Single level home', 'Ski-in/Ski-out', 'Smart TV', 'Smart lock', 'Smoke detector', 'Smoking allowed', 'Soaking tub', 'Sound system', 'Stair gates', 'Stand alone steam shower', 'Standing valet', 'Steam oven', 'Step-free access', 'Stove', 'Suitable for events', 'Sun loungers', 'TV', 'Table corner guards', 'Tennis court', 'Terrace', 'Toilet paper', 'Touchless faucets', 'Walk-in shower', 'Warming drawer', 'Washer', 'Washer / Dryer', 'Waterfront', 'Well-lit path to entrance', 'Wheelchair accessible', 'Wide clearance to bed', 'Wide clearance to shower', 'Wide doorway', 'Wide entryway', 'Wide hallway clearance', 'Wifi', 'Window guards', 'Wine cooler', 'toilet',"
},
{
"code": null,
"e": 9144,
"s": 8429,
"text": "In the list above, some amenities are more important than others (e.g. a balcony is more likely to increase price than a fax machine), and some are likely to be fairly uncommon (e.g. ‘Electric profiling bed’). Based on previous experience in the industry, and furtherresearch into which amenities are considered by guests to be more important, a selection of the more important amenities were extracted. These were then selected from for inclusion in the final model depending on how sparse the data was. For example, if it turns out that almost all properties have/do not have a particular amenity, that feature will not be very useful in differentiating between listings or helping explain differences in prices."
},
{
"code": null,
"e": 9337,
"s": 9144,
"text": "The whole convoluted code for this can be found on GitHub, but this is the final section where I removed columns where over 90% of the listings either had or did not have a particular amenity:"
},
{
"code": null,
"e": 9386,
"s": 9337,
"text": "These are the amenities that I ended up keeping:"
},
{
"code": null,
"e": 9394,
"s": 9386,
"text": "Balcony"
},
{
"code": null,
"e": 9404,
"s": 9394,
"text": "Bed linen"
},
{
"code": null,
"e": 9414,
"s": 9404,
"text": "Breakfast"
},
{
"code": null,
"e": 9417,
"s": 9414,
"text": "TV"
},
{
"code": null,
"e": 9432,
"s": 9417,
"text": "Coffee machine"
},
{
"code": null,
"e": 9456,
"s": 9432,
"text": "Basic cooking equipment"
},
{
"code": null,
"e": 9517,
"s": 9456,
"text": "White goods (specifically a washer, dryer and/or dishwasher)"
},
{
"code": null,
"e": 9532,
"s": 9517,
"text": "Child-friendly"
},
{
"code": null,
"e": 9540,
"s": 9532,
"text": "Parking"
},
{
"code": null,
"e": 9554,
"s": 9540,
"text": "Outdoor space"
},
{
"code": null,
"e": 9570,
"s": 9554,
"text": "Greeted by host"
},
{
"code": null,
"e": 9579,
"s": 9570,
"text": "Internet"
},
{
"code": null,
"e": 9603,
"s": 9579,
"text": "Long term stays allowed"
},
{
"code": null,
"e": 9616,
"s": 9603,
"text": "Pets allowed"
},
{
"code": null,
"e": 9633,
"s": 9616,
"text": "Private entrance"
},
{
"code": null,
"e": 9657,
"s": 9633,
"text": "Safe or security system"
},
{
"code": null,
"e": 9671,
"s": 9657,
"text": "Self check-in"
},
{
"code": null,
"e": 9933,
"s": 9671,
"text": "After these (and many other) cleaning and pre-processing steps, the Airbnb was in suitable form to begin exploration and modelling, and you can read more about this in my next post on data exploration, and another post I wrote about building a predictive model."
}
] |
Explain array of pointers in C programming language
|
Pointer is a variable that stores the address of another variable.
Pointer saves the memory space.
Execution time of pointer is faster because of direct access to memory location.
With the help of pointers, the memory is accessed efficiently, i.e., memory is allocated and deallocated dynamically.
Pointers are used with data structures.
Consider the following statement −
int qty = 179;
In memory, the variable can be represented as follows −
It means ‘p’ is a pointer variable, which holds the address of another integer variable, as shown below −
Int *p;
Address operator (&) is used to initialise a pointer variable.
For Example − int qty = 175;
int *p;
p= &qty;
It is collection of addresses (or) collection of pointers
Following is the declaration for array of pointers −
datatype *pointername [size];
For example,
int *p[5];
It represents an array of pointers that can hold 5 integer element addresses.
‘&’ is used for initialisation.
For Example,
int a[3] = {10,20,30};
int *p[3], i;
for (i=0; i<3; i++) (or) for (i=0; i<3,i++)
p[i] = &a[i];
p[i] = a+i;
Indirection operator (*) is used for accessing.
For Example,
for (i=0, i<3; i++)
printf ("%d", *p[i]);
Given below is the program for array of pointers −
Live Demo
#include<stdio.h>
main ( ){
int a[3] = {10,20,30};
int *p[3],i;
for (i=0; i<3; i++)
p[i] = &a[i];
printf ("elements of the array are \n");
for (i=0; i<3; i++)
printf ("%d \t", *p[i]);
}
When the above program is executed, it produces the following result −
elements at the array are : 10 20 30
Given below is the program for the array of pointers to strings −
Live Demo
#include <stdio.h>
#include <stdlib.h>
int main(void){
char *a[5] = {"one", "two", "three", "four", "five"};
int i;
printf ( "the strings are at locations:\n");
for (i=0; i<5; i++)
printf ("%d\n", a[i]);
return 0;
}
When the above program is executed, it produces the following result −
The strings are at locations:
4210688
4210692
4210696
4210702
4210707
|
[
{
"code": null,
"e": 1129,
"s": 1062,
"text": "Pointer is a variable that stores the address of another variable."
},
{
"code": null,
"e": 1161,
"s": 1129,
"text": "Pointer saves the memory space."
},
{
"code": null,
"e": 1242,
"s": 1161,
"text": "Execution time of pointer is faster because of direct access to memory location."
},
{
"code": null,
"e": 1360,
"s": 1242,
"text": "With the help of pointers, the memory is accessed efficiently, i.e., memory is allocated and deallocated dynamically."
},
{
"code": null,
"e": 1400,
"s": 1360,
"text": "Pointers are used with data structures."
},
{
"code": null,
"e": 1435,
"s": 1400,
"text": "Consider the following statement −"
},
{
"code": null,
"e": 1450,
"s": 1435,
"text": "int qty = 179;"
},
{
"code": null,
"e": 1506,
"s": 1450,
"text": "In memory, the variable can be represented as follows −"
},
{
"code": null,
"e": 1612,
"s": 1506,
"text": "It means ‘p’ is a pointer variable, which holds the address of another integer variable, as shown below −"
},
{
"code": null,
"e": 1620,
"s": 1612,
"text": "Int *p;"
},
{
"code": null,
"e": 1683,
"s": 1620,
"text": "Address operator (&) is used to initialise a pointer variable."
},
{
"code": null,
"e": 1712,
"s": 1683,
"text": "For Example − int qty = 175;"
},
{
"code": null,
"e": 1728,
"s": 1712,
"text": " int *p;"
},
{
"code": null,
"e": 1745,
"s": 1728,
"text": " p= &qty;"
},
{
"code": null,
"e": 1803,
"s": 1745,
"text": "It is collection of addresses (or) collection of pointers"
},
{
"code": null,
"e": 1856,
"s": 1803,
"text": "Following is the declaration for array of pointers −"
},
{
"code": null,
"e": 1886,
"s": 1856,
"text": "datatype *pointername [size];"
},
{
"code": null,
"e": 1899,
"s": 1886,
"text": "For example,"
},
{
"code": null,
"e": 1910,
"s": 1899,
"text": "int *p[5];"
},
{
"code": null,
"e": 1988,
"s": 1910,
"text": "It represents an array of pointers that can hold 5 integer element addresses."
},
{
"code": null,
"e": 2020,
"s": 1988,
"text": "‘&’ is used for initialisation."
},
{
"code": null,
"e": 2033,
"s": 2020,
"text": "For Example,"
},
{
"code": null,
"e": 2140,
"s": 2033,
"text": "int a[3] = {10,20,30};\nint *p[3], i;\nfor (i=0; i<3; i++) (or) for (i=0; i<3,i++)\np[i] = &a[i];\np[i] = a+i;"
},
{
"code": null,
"e": 2188,
"s": 2140,
"text": "Indirection operator (*) is used for accessing."
},
{
"code": null,
"e": 2201,
"s": 2188,
"text": "For Example,"
},
{
"code": null,
"e": 2243,
"s": 2201,
"text": "for (i=0, i<3; i++)\nprintf (\"%d\", *p[i]);"
},
{
"code": null,
"e": 2294,
"s": 2243,
"text": "Given below is the program for array of pointers −"
},
{
"code": null,
"e": 2305,
"s": 2294,
"text": " Live Demo"
},
{
"code": null,
"e": 2518,
"s": 2305,
"text": "#include<stdio.h>\nmain ( ){\n int a[3] = {10,20,30};\n int *p[3],i;\n for (i=0; i<3; i++)\n p[i] = &a[i];\n printf (\"elements of the array are \\n\");\n for (i=0; i<3; i++)\n printf (\"%d \\t\", *p[i]);\n}"
},
{
"code": null,
"e": 2589,
"s": 2518,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 2626,
"s": 2589,
"text": "elements at the array are : 10 20 30"
},
{
"code": null,
"e": 2692,
"s": 2626,
"text": "Given below is the program for the array of pointers to strings −"
},
{
"code": null,
"e": 2703,
"s": 2692,
"text": " Live Demo"
},
{
"code": null,
"e": 2940,
"s": 2703,
"text": "#include <stdio.h>\n#include <stdlib.h>\nint main(void){\n char *a[5] = {\"one\", \"two\", \"three\", \"four\", \"five\"};\n int i;\n printf ( \"the strings are at locations:\\n\");\n for (i=0; i<5; i++)\n printf (\"%d\\n\", a[i]);\n return 0;\n}"
},
{
"code": null,
"e": 3011,
"s": 2940,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 3081,
"s": 3011,
"text": "The strings are at locations:\n4210688\n4210692\n4210696\n4210702\n4210707"
}
] |
Tryit Editor v3.7
|
Tryit: A list with ABC
|
[] |
How to replace a character in a MySQL table?
|
To replace only a single character, use REPLACE() in MySQL. Let us first create a table −
mysql> create table DemoTable
-> (
-> Name varchar(20)
-> );
Query OK, 0 rows affected (0.69 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('John Smitk');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values('David Miller');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Adam Smitk');
Query OK, 1 row affected (0.11 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+--------------+
| Name |
+--------------+
| John Smitk |
| David Miller |
| Adam Smitk |
+--------------+
3 rows in set (0.00 sec)
Here is the query to replace a character −
mysql> update DemoTable
-> set Name=replace(Name,'k','h');
Query OK, 2 rows affected (0.13 sec)
Rows matched: 3 Changed: 2 Warnings: 0
Let us check the table records once again −
mysql> select *from DemoTable;
This will produce the following output −
+--------------+
| Name |
+--------------+
| John Smith |
| David Miller |
| Adam Smith |
+--------------+
3 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1152,
"s": 1062,
"text": "To replace only a single character, use REPLACE() in MySQL. Let us first create a table −"
},
{
"code": null,
"e": 1259,
"s": 1152,
"text": "mysql> create table DemoTable\n -> (\n -> Name varchar(20)\n -> );\nQuery OK, 0 rows affected (0.69 sec)"
},
{
"code": null,
"e": 1315,
"s": 1259,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1578,
"s": 1315,
"text": "mysql> insert into DemoTable values('John Smitk');\nQuery OK, 1 row affected (0.09 sec)\nmysql> insert into DemoTable values('David Miller');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable values('Adam Smitk');\nQuery OK, 1 row affected (0.11 sec)"
},
{
"code": null,
"e": 1638,
"s": 1578,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1669,
"s": 1638,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1710,
"s": 1669,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1854,
"s": 1710,
"text": "+--------------+\n| Name |\n+--------------+\n| John Smitk |\n| David Miller |\n| Adam Smitk |\n+--------------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1897,
"s": 1854,
"text": "Here is the query to replace a character −"
},
{
"code": null,
"e": 2035,
"s": 1897,
"text": "mysql> update DemoTable\n -> set Name=replace(Name,'k','h');\nQuery OK, 2 rows affected (0.13 sec)\nRows matched: 3 Changed: 2 Warnings: 0"
},
{
"code": null,
"e": 2079,
"s": 2035,
"text": "Let us check the table records once again −"
},
{
"code": null,
"e": 2110,
"s": 2079,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 2151,
"s": 2110,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2295,
"s": 2151,
"text": "+--------------+\n| Name |\n+--------------+\n| John Smith |\n| David Miller |\n| Adam Smith |\n+--------------+\n3 rows in set (0.00 sec)"
}
] |
How to make flexbox children 100% height of their parent using CSS? - GeeksforGeeks
|
30 Jul, 2021
CSS Flexbox is an awesome tool to create website layouts. Making a flex-box child 100% height of their parent can be done in two ways. It is little tricky because, certainly it will display an error. For example, the child may flow out of the parent boundary or it may not get upto 100% height that you will see in your browser output.Example 1: This example makes a child flex-box of height 100% using CSS.
html
<!DOCTYPE html><html> <head> <title> Make flex-box child height 100% </title> <style> * { padding: 0; margin: 0; } .container { width: 100vw; height: 50vh; background-color: green; display: flex; justify-content: center; align-items: center; } .child-div { height: 100%; background-color: red; margin: 0 20px; } </style> </head> <body> <div class="container"> <div class="child-div"> One </div> <div class="child-div"> Two </div> <div class="child-div"> Three </div> <div class="child-div"> Four </div> <div class="child-div"> Five </div> </div> </body></html>
Output:
Example 2: The second way to achieve this by using align-items property in the parent div to ‘stretch’. It makes every .child-div 100% height of it’s parent height.
html
<!DOCTYPE html><html> <head> <title> Make flex-box child height 100% </title> <style> *{ padding: 0; margin: 0; } .container{ width: 100vw; height: 50vh; background-color: green; display: flex; justify-content: center; } .child-div{ background-color: red; margin: 0 20px; } </style> </head> <body> <div class="container"> <div class="child-div"> One </div> <div class="child-div"> Two </div> <div class="child-div"> Three </div> <div class="child-div"> Four </div> <div class="child-div"> Five </div> </div> </body></html>
Output:
Example 3: This example makes width of child to 100% of there parent.
html
<!DOCTYPE html><html> <head> <title> Make flex-box child width 100% </title> <style> * { padding: 0; margin: 0; } .container { width: 100vw; height: 50vh; background-color: green; display: flex; flex-direction: column; justify-content: center; } .child-div { background-color: red; margin: 20px 0; padding: 5px; } </style> </head> <body> <div class="container"> <div class="child-div"> One </div> <div class="child-div"> Two </div> <div class="child-div"> Three </div> <div class="child-div"> Four </div> <div class="child-div"> Five </div> </div> </body></html>
Output:
Supported Browser:
Google Chrome 29.0
Internet Explorer 11.0
Firefox 22.0
Opera 48
Safari 10
HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.
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.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
surindertarika1234
ysachin2314
CSS-Questions
Picked
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to create footer to stay at the bottom of a Web page?
Types of CSS (Cascading Style Sheet)
Primer CSS Flexbox Flex Direction
HTML Course | First Web Page | Printing Hello World
How to position a div at the bottom of its container using CSS?
How to set input type date in dd-mm-yyyy format using HTML ?
Types of CSS (Cascading Style Sheet)
HTML | <img> align Attribute
Form validation using HTML and JavaScript
How to set the default value for an HTML <select> element ?
|
[
{
"code": null,
"e": 24889,
"s": 24861,
"text": "\n30 Jul, 2021"
},
{
"code": null,
"e": 25298,
"s": 24889,
"text": "CSS Flexbox is an awesome tool to create website layouts. Making a flex-box child 100% height of their parent can be done in two ways. It is little tricky because, certainly it will display an error. For example, the child may flow out of the parent boundary or it may not get upto 100% height that you will see in your browser output.Example 1: This example makes a child flex-box of height 100% using CSS. "
},
{
"code": null,
"e": 25303,
"s": 25298,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Make flex-box child height 100% </title> <style> * { padding: 0; margin: 0; } .container { width: 100vw; height: 50vh; background-color: green; display: flex; justify-content: center; align-items: center; } .child-div { height: 100%; background-color: red; margin: 0 20px; } </style> </head> <body> <div class=\"container\"> <div class=\"child-div\"> One </div> <div class=\"child-div\"> Two </div> <div class=\"child-div\"> Three </div> <div class=\"child-div\"> Four </div> <div class=\"child-div\"> Five </div> </div> </body></html>",
"e": 26239,
"s": 25303,
"text": null
},
{
"code": null,
"e": 26249,
"s": 26239,
"text": "Output: "
},
{
"code": null,
"e": 26416,
"s": 26249,
"text": "Example 2: The second way to achieve this by using align-items property in the parent div to ‘stretch’. It makes every .child-div 100% height of it’s parent height. "
},
{
"code": null,
"e": 26421,
"s": 26416,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Make flex-box child height 100% </title> <style> *{ padding: 0; margin: 0; } .container{ width: 100vw; height: 50vh; background-color: green; display: flex; justify-content: center; } .child-div{ background-color: red; margin: 0 20px; } </style> </head> <body> <div class=\"container\"> <div class=\"child-div\"> One </div> <div class=\"child-div\"> Two </div> <div class=\"child-div\"> Three </div> <div class=\"child-div\"> Four </div> <div class=\"child-div\"> Five </div> </div> </body></html>",
"e": 27295,
"s": 26421,
"text": null
},
{
"code": null,
"e": 27305,
"s": 27295,
"text": "Output: "
},
{
"code": null,
"e": 27377,
"s": 27305,
"text": "Example 3: This example makes width of child to 100% of there parent. "
},
{
"code": null,
"e": 27382,
"s": 27377,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Make flex-box child width 100% </title> <style> * { padding: 0; margin: 0; } .container { width: 100vw; height: 50vh; background-color: green; display: flex; flex-direction: column; justify-content: center; } .child-div { background-color: red; margin: 20px 0; padding: 5px; } </style> </head> <body> <div class=\"container\"> <div class=\"child-div\"> One </div> <div class=\"child-div\"> Two </div> <div class=\"child-div\"> Three </div> <div class=\"child-div\"> Four </div> <div class=\"child-div\"> Five </div> </div> </body></html>",
"e": 28320,
"s": 27382,
"text": null
},
{
"code": null,
"e": 28330,
"s": 28320,
"text": "Output: "
},
{
"code": null,
"e": 28350,
"s": 28330,
"text": " Supported Browser:"
},
{
"code": null,
"e": 28369,
"s": 28350,
"text": "Google Chrome 29.0"
},
{
"code": null,
"e": 28392,
"s": 28369,
"text": "Internet Explorer 11.0"
},
{
"code": null,
"e": 28405,
"s": 28392,
"text": "Firefox 22.0"
},
{
"code": null,
"e": 28414,
"s": 28405,
"text": "Opera 48"
},
{
"code": null,
"e": 28424,
"s": 28414,
"text": "Safari 10"
},
{
"code": null,
"e": 28618,
"s": 28424,
"text": "HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples."
},
{
"code": null,
"e": 28804,
"s": 28618,
"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": 28941,
"s": 28804,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 28960,
"s": 28941,
"text": "surindertarika1234"
},
{
"code": null,
"e": 28972,
"s": 28960,
"text": "ysachin2314"
},
{
"code": null,
"e": 28986,
"s": 28972,
"text": "CSS-Questions"
},
{
"code": null,
"e": 28993,
"s": 28986,
"text": "Picked"
},
{
"code": null,
"e": 28997,
"s": 28993,
"text": "CSS"
},
{
"code": null,
"e": 29002,
"s": 28997,
"text": "HTML"
},
{
"code": null,
"e": 29019,
"s": 29002,
"text": "Web Technologies"
},
{
"code": null,
"e": 29024,
"s": 29019,
"text": "HTML"
},
{
"code": null,
"e": 29122,
"s": 29024,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29131,
"s": 29122,
"text": "Comments"
},
{
"code": null,
"e": 29144,
"s": 29131,
"text": "Old Comments"
},
{
"code": null,
"e": 29202,
"s": 29144,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 29239,
"s": 29202,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 29273,
"s": 29239,
"text": "Primer CSS Flexbox Flex Direction"
},
{
"code": null,
"e": 29325,
"s": 29273,
"text": "HTML Course | First Web Page | Printing Hello World"
},
{
"code": null,
"e": 29389,
"s": 29325,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 29450,
"s": 29389,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 29487,
"s": 29450,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 29516,
"s": 29487,
"text": "HTML | <img> align Attribute"
},
{
"code": null,
"e": 29558,
"s": 29516,
"text": "Form validation using HTML and JavaScript"
}
] |
Lodash _.flatMap() Method - GeeksforGeeks
|
10 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, objects, numbers etc.The _.flatMap() method creates a flattened array of values by running each element in collection through iteratee and flattening the mapped results.
Syntax:
_.flatMap(collection, iteratee)
Parameters: This method accepts two parameters as mentioned above and described below:
collection: This parameter holds the collection to iterate over.
iteratee: This parameter holds the function invoked per iteration.
Return Value: This method returns the new flattened array.
Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file.
javascript
// Requiring the lodash library const _ = require("lodash"); // Original array var user1 = ([35, 47, 58, 69, 94, 13, 72]); // Use of _.flatMap() methodlet gfg1 = _.flatMap(user1, function duplicate(n) { return [n, n];}) // Printing the output console.log(gfg1);
Output:
[
35, 35, 47, 47, 58, 58,
69, 69, 94, 94, 13, 13,
72, 72
]
Example 2:
javascript
// Requiring the lodash library const _ = require("lodash"); // Original array var user1 = ([3.5, 4.7, 5.8, 6.9, 9.4, 1.3, 7.2]);var user2 = ([3, 4, 5, 9, 9, 1, 7]); // Use of _.flatMap() methodlet gfg1 = _.flatMap(user1, function duplicate(n) { return [n, n];}) let gfg2 = _.flatMap(user2, function duplicate(n) { return [n, n];}) // Printing the output console.log(gfg1);console.log(gfg2);
Output:
[
3.5, 3.5, 4.7, 4.7, 5.8, 5.8,
6.9, 6.9, 9.4, 9.4, 1.3, 1.3,
7.2, 7.2
]
[
3, 3, 4, 4, 5, 5,
9, 9, 9, 9, 1, 1,
7, 7
]
Note: This code will not work in normal JavaScript because it requires the library lodash to be installed.
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
File uploading in React.js
Form validation using HTML and JavaScript
Express.js express.Router() Function
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 ?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 37045,
"s": 37017,
"text": "\n10 Sep, 2020"
},
{
"code": null,
"e": 37344,
"s": 37045,
"text": "Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, objects, numbers etc.The _.flatMap() method creates a flattened array of values by running each element in collection through iteratee and flattening the mapped results."
},
{
"code": null,
"e": 37352,
"s": 37344,
"text": "Syntax:"
},
{
"code": null,
"e": 37384,
"s": 37352,
"text": "_.flatMap(collection, iteratee)"
},
{
"code": null,
"e": 37471,
"s": 37384,
"text": "Parameters: This method accepts two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 37536,
"s": 37471,
"text": "collection: This parameter holds the collection to iterate over."
},
{
"code": null,
"e": 37603,
"s": 37536,
"text": "iteratee: This parameter holds the function invoked per iteration."
},
{
"code": null,
"e": 37662,
"s": 37603,
"text": "Return Value: This method returns the new flattened array."
},
{
"code": null,
"e": 37757,
"s": 37662,
"text": "Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file."
},
{
"code": null,
"e": 37768,
"s": 37757,
"text": "javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array var user1 = ([35, 47, 58, 69, 94, 13, 72]); // Use of _.flatMap() methodlet gfg1 = _.flatMap(user1, function duplicate(n) { return [n, n];}) // Printing the output console.log(gfg1);",
"e": 38039,
"s": 37768,
"text": null
},
{
"code": null,
"e": 38047,
"s": 38039,
"text": "Output:"
},
{
"code": null,
"e": 38114,
"s": 38047,
"text": "[\n 35, 35, 47, 47, 58, 58, \n 69, 69, 94, 94, 13, 13,\n 72, 72\n]\n"
},
{
"code": null,
"e": 38125,
"s": 38114,
"text": "Example 2:"
},
{
"code": null,
"e": 38136,
"s": 38125,
"text": "javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array var user1 = ([3.5, 4.7, 5.8, 6.9, 9.4, 1.3, 7.2]);var user2 = ([3, 4, 5, 9, 9, 1, 7]); // Use of _.flatMap() methodlet gfg1 = _.flatMap(user1, function duplicate(n) { return [n, n];}) let gfg2 = _.flatMap(user2, function duplicate(n) { return [n, n];}) // Printing the output console.log(gfg1);console.log(gfg2);",
"e": 38539,
"s": 38136,
"text": null
},
{
"code": null,
"e": 38547,
"s": 38539,
"text": "Output:"
},
{
"code": null,
"e": 38679,
"s": 38547,
"text": "[\n 3.5, 3.5, 4.7, 4.7, 5.8, 5.8, \n 6.9, 6.9, 9.4, 9.4, 1.3, 1.3,\n 7.2, 7.2\n]\n[\n 3, 3, 4, 4, 5, 5,\n 9, 9, 9, 9, 1, 1,\n 7, 7\n]\n"
},
{
"code": null,
"e": 38786,
"s": 38679,
"text": "Note: This code will not work in normal JavaScript because it requires the library lodash to be installed."
},
{
"code": null,
"e": 38804,
"s": 38786,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 38815,
"s": 38804,
"text": "JavaScript"
},
{
"code": null,
"e": 38832,
"s": 38815,
"text": "Web Technologies"
},
{
"code": null,
"e": 38930,
"s": 38832,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38939,
"s": 38930,
"text": "Comments"
},
{
"code": null,
"e": 38952,
"s": 38939,
"text": "Old Comments"
},
{
"code": null,
"e": 39013,
"s": 38952,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 39085,
"s": 39013,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 39154,
"s": 39085,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 39181,
"s": 39154,
"text": "File uploading in React.js"
},
{
"code": null,
"e": 39223,
"s": 39181,
"text": "Form validation using HTML and JavaScript"
},
{
"code": null,
"e": 39260,
"s": 39223,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 39293,
"s": 39260,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 39355,
"s": 39293,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 39398,
"s": 39355,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Python | Ways to check string contain all same characters
|
29 Jun, 2019
Given a list of strings, write a Python program to check whether each string has all the characters same or not. Given below are a few methods to check the same.
Method #1: Using Naive Method [Inefficient]
# Python code to demonstrate # to check whether string contains# all characters same or not # Initialising string listini_list = ["aaaaaaaaaaa", "aaaaaaabaa"] # Printing initial stringprint ("Initial Strings list", ini_list) # Using Naive Method:flag = Truefor i in ini_list: for j in range(0, len(i)-1): if i[j]!= i[j + 1]: print ("String {} don't have all characters same".format(i)) flag = False break if flag == True: print ("String {} don't have all characters same".format(i))
Initial Strings list ['aaaaaaaaaaa', 'aaaaaaabaa']
String aaaaaaaaaaa don't have all characters same
String aaaaaaabaa don't have all characters same
Method #2: Using String Comparisons
# Python code to demonstrate # to check whether string contains# all characters same or not # Initialising string listini_list = ["aaaaaaaaaaa", "aaaaaaabaa"] # Printing initial stringprint ("Initial Strings list", ini_list) # Using String comparisonfor i in ini_list: if i == len(i)*i[0]: print ("String {} have all characters same".format(i)) else: print ("String {} don't have all characters same".format(i))
Initial Strings list ['aaaaaaaaaaa', 'aaaaaaabaa']
String aaaaaaaaaaa have all characters same
String aaaaaaabaa don't have all characters same
Method #3: Using count comparison
# Python code to demonstrate # to check whether string contains# all characters same or not # Initialising string listini_list = ["aaaaaaaaaaa", "aaaaaaabaa"] # Printing initial stringprint ("Initial Strings list", ini_list) # Using String comparisonfor i in ini_list: if i.count(i[0]) == len(i): print ("String {} have all characters same".format(i)) else: print ("String {} don't have all characters same".format(i))
Initial Strings list ['aaaaaaaaaaa', 'aaaaaaabaa']
String aaaaaaaaaaa have all characters same
String aaaaaaabaa don't have all characters same
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Jun, 2019"
},
{
"code": null,
"e": 190,
"s": 28,
"text": "Given a list of strings, write a Python program to check whether each string has all the characters same or not. Given below are a few methods to check the same."
},
{
"code": null,
"e": 234,
"s": 190,
"text": "Method #1: Using Naive Method [Inefficient]"
},
{
"code": "# Python code to demonstrate # to check whether string contains# all characters same or not # Initialising string listini_list = [\"aaaaaaaaaaa\", \"aaaaaaabaa\"] # Printing initial stringprint (\"Initial Strings list\", ini_list) # Using Naive Method:flag = Truefor i in ini_list: for j in range(0, len(i)-1): if i[j]!= i[j + 1]: print (\"String {} don't have all characters same\".format(i)) flag = False break if flag == True: print (\"String {} don't have all characters same\".format(i)) ",
"e": 782,
"s": 234,
"text": null
},
{
"code": null,
"e": 933,
"s": 782,
"text": "Initial Strings list ['aaaaaaaaaaa', 'aaaaaaabaa']\nString aaaaaaaaaaa don't have all characters same\nString aaaaaaabaa don't have all characters same\n"
},
{
"code": null,
"e": 970,
"s": 933,
"text": " Method #2: Using String Comparisons"
},
{
"code": "# Python code to demonstrate # to check whether string contains# all characters same or not # Initialising string listini_list = [\"aaaaaaaaaaa\", \"aaaaaaabaa\"] # Printing initial stringprint (\"Initial Strings list\", ini_list) # Using String comparisonfor i in ini_list: if i == len(i)*i[0]: print (\"String {} have all characters same\".format(i)) else: print (\"String {} don't have all characters same\".format(i)) ",
"e": 1414,
"s": 970,
"text": null
},
{
"code": null,
"e": 1559,
"s": 1414,
"text": "Initial Strings list ['aaaaaaaaaaa', 'aaaaaaabaa']\nString aaaaaaaaaaa have all characters same\nString aaaaaaabaa don't have all characters same\n"
},
{
"code": null,
"e": 1594,
"s": 1559,
"text": " Method #3: Using count comparison"
},
{
"code": "# Python code to demonstrate # to check whether string contains# all characters same or not # Initialising string listini_list = [\"aaaaaaaaaaa\", \"aaaaaaabaa\"] # Printing initial stringprint (\"Initial Strings list\", ini_list) # Using String comparisonfor i in ini_list: if i.count(i[0]) == len(i): print (\"String {} have all characters same\".format(i)) else: print (\"String {} don't have all characters same\".format(i)) ",
"e": 2045,
"s": 1594,
"text": null
},
{
"code": null,
"e": 2190,
"s": 2045,
"text": "Initial Strings list ['aaaaaaaaaaa', 'aaaaaaabaa']\nString aaaaaaaaaaa have all characters same\nString aaaaaaabaa don't have all characters same\n"
},
{
"code": null,
"e": 2213,
"s": 2190,
"text": "Python string-programs"
},
{
"code": null,
"e": 2220,
"s": 2213,
"text": "Python"
},
{
"code": null,
"e": 2236,
"s": 2220,
"text": "Python Programs"
},
{
"code": null,
"e": 2334,
"s": 2236,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2366,
"s": 2334,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2393,
"s": 2366,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2424,
"s": 2393,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2447,
"s": 2424,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2468,
"s": 2447,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2490,
"s": 2468,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2529,
"s": 2490,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2567,
"s": 2529,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2616,
"s": 2567,
"text": "Python | Convert string dictionary to dictionary"
}
] |
How to return multiple values from a function in C or C++?
|
15 Jun, 2022
New programmers are usually in the search of ways to return multiple values from a function. Unfortunately, C and C++ do not allow this directly. But fortunately, with a little bit of clever programming, we can easily achieve this. Below are the methods to return multiple values from a function in C:
By using pointers.By using structures.By using Arrays.
By using pointers.
By using structures.
By using Arrays.
Example: Consider an example where the task is to find the greater and smaller of two distinct numbers. We could write multiple functions. The main problem is the trouble of calling more than one functions since we need to return multiple values and of course, having more number of lines of code to be typed.
Returning multiple values Using pointers: Pass the argument with their address and make changes in their value using pointer. So that the values get changed into the original argument.
Returning multiple values Using pointers: Pass the argument with their address and make changes in their value using pointer. So that the values get changed into the original argument.
C++
C
// Modified program using pointers#include <iostream>using namespace std; // add is the short name for addressvoid compare(int a, int b, int* add_great, int* add_small){ if (a > b) { // a is stored in the address pointed // by the pointer variable *add_great *add_great = a; *add_small = b; } else { *add_great = b; *add_small = a; }} // Driver codeint main(){ int great, small, x, y; cout << "Enter two numbers: \n"; cin >> x >> y; // The last two arguments are passed // by giving addresses of memory locations compare(x, y, &great, &small); cout << "\nThe greater number is " << great << " and the smaller number is " << small; return 0;} // This code is contributed by sarajadhav12052009
// Modified program using pointers#include <stdio.h> // add is the short name for addressvoid compare(int a, int b, int* add_great, int* add_small){ if (a > b) { // a is stored in the address pointed // by the pointer variable *add_great *add_great = a; *add_small = b; } else { *add_great = b; *add_small = a; }} // Driver codeint main(){ int great, small, x, y; printf("Enter two numbers: \n"); scanf("%d%d", &x, &y); // The last two arguments are passed // by giving addresses of memory locations compare(x, y, &great, &small); printf("\nThe greater number is %d and the smaller number is %d", great, small); return 0;}
Enter two numbers:
5 8
The greater number is 8 and the smaller number is 5
Returning multiple values using structures : As the structure is a user-defined datatype. The idea is to define a structure with two integer variables and store the greater and smaller values into those variable, then use the values of that structure.
Returning multiple values using structures : As the structure is a user-defined datatype. The idea is to define a structure with two integer variables and store the greater and smaller values into those variable, then use the values of that structure.
C
// Modified program using structures#include <stdio.h>struct greaterSmaller { int greater, smaller;}; typedef struct greaterSmaller Struct; Struct findGreaterSmaller(int a, int b){ Struct s; if (a > b) { s.greater = a; s.smaller = b; } else { s.greater = b; s.smaller = a; } return s;} // Driver codeint main(){ int x, y; Struct result; printf("Enter two numbers: \n"); scanf("%d%d", &x, &y); // The last two arguments are passed // by giving addresses of memory locations result = findGreaterSmaller(x, y); printf("\nThe greater number is %d and the" "smaller number is %d", result.greater, result.smaller); return 0;}
Enter two numbers:
5 8
The greater number is 8 and the smaller number is 5
Returning multiple values using an array (Works only when returned items are of same types): When an array is passed as an argument then its base address is passed to the function so whatever changes made to the copy of the array, it is changed in the original array. Below is the program to return multiple values using array i.e. store greater value at arr[0] and smaller at arr[1].
Returning multiple values using an array (Works only when returned items are of same types): When an array is passed as an argument then its base address is passed to the function so whatever changes made to the copy of the array, it is changed in the original array. Below is the program to return multiple values using array i.e. store greater value at arr[0] and smaller at arr[1].
C++
C
// Modified program using array#include <iostream>using namespace std; // Store the greater element at 0th indexvoid findGreaterSmaller(int a, int b, int arr[]){ // Store the greater element at // 0th index of the array if (a > b) { arr[0] = a; arr[1] = b; } else { arr[0] = b; arr[1] = a; }} // Driver codeint main(){ int x, y; int arr[2]; cout << "Enter two numbers: \n"; cin >> x >> y; findGreaterSmaller(x, y, arr); cout << "\nThe greater number is " << arr[0] << " and the " "smaller number is " << arr[1]; return 0;} // This code is contributed by sarajadhav12052009
// Modified program using array#include <stdio.h> // Store the greater element at 0th indexvoid findGreaterSmaller(int a, int b, int arr[]){ // Store the greater element at // 0th index of the array if (a > b) { arr[0] = a; arr[1] = b; } else { arr[0] = b; arr[1] = a; }} // Driver codeint main(){ int x, y; int arr[2]; printf("Enter two numbers: \n"); scanf("%d%d", &x, &y); findGreaterSmaller(x, y, arr); printf("\nThe greater number is %d and the " "smaller number is %d", arr[0], arr[1]); return 0;}
Enter two numbers:
5 8
The greater number is 8 and the smaller number is 5
C++ Only Methods
Returning multiple values Using References: We use references in C++ to store returned values.
Returning multiple values Using References: We use references in C++ to store returned values.
CPP
// Modified program using References in C++#include <stdio.h> void compare(int a, int b, int &add_great, int &add_small){ if (a > b) { add_great = a; add_small = b; } else { add_great = b; add_small = a; }} // Driver codeint main(){ int great, small, x, y; printf("Enter two numbers: \n"); scanf("%d%d", &x, &y); // The last two arguments are passed // by giving addresses of memory locations compare(x, y, great, small); printf("\nThe greater number is %d and the" "smaller number is %d", great, small); return 0;}
Enter two numbers:
5 8
The greater number is 8 and the smaller number is 5
Returning multiple values using Class and Object : The idea is similar to structures. We create a class with two integer variables and store the greater and smaller values into those variable, then use the values of that structure.
Returning multiple values using Class and Object : The idea is similar to structures. We create a class with two integer variables and store the greater and smaller values into those variable, then use the values of that structure.
CPP
// Modified program using class#include <stdio.h> class GreaterSmaller {public: int greater, smaller;}; GreaterSmaller findGreaterSmaller(int a, int b){ GreaterSmaller s; if (a > b) { s.greater = a; s.smaller = b; } else { s.greater = b; s.smaller = a; } return s;} // Driver codeint main(){ int x, y; GreaterSmaller result; printf("Enter two numbers: \n"); scanf("%d%d", &x, &y); // The last two arguments are passed // by giving addresses of memory locations result = findGreaterSmaller(x, y); printf("\nThe greater number is %d and the" "smaller number is %d", result.greater, result.smaller); return 0;}
Enter two numbers:
5 8
The greater number is 8 and the smaller number is 5
Returning multiple values using STL tuple : The idea is similar to structures. We create a tuple with two integer variables and return the tuple, and then inside main function we use tie function to assign values to min and max that is returned by the function.
Returning multiple values using STL tuple : The idea is similar to structures. We create a tuple with two integer variables and return the tuple, and then inside main function we use tie function to assign values to min and max that is returned by the function.
CPP
// Modified program using C++ STL tuple#include<iostream>#include<tuple> using namespace std; tuple <int, int> findGreaterSmaller(int a, int b){ if (a < b) { return make_tuple(a, b); } else { return make_tuple(b, a); }} // Driver codeint main(){ int x = 5, y= 8; int max, min; tie(min, max) = findGreaterSmaller(x, y); printf("The greater number is %d and the " "smaller number is %d", max, min); return 0;} // This article is contributed by Blinkii
The greater number is 8 and the smaller number is 5
Blinkii
Akanksha_Rai
sarajadhav12052009
C-Arrays
C-Functions
C-Pointers
C-Structure & Union
CPP-Functions
cpp-pointer
cpp-references
C Language
C Programs
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
std::string class in C++
Strings in C
Arrow operator -> in C/C++ with Examples
Basics of File Handling in C
UDP Server-Client implementation in C
Header files in C/C++ and its uses
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n15 Jun, 2022"
},
{
"code": null,
"e": 354,
"s": 52,
"text": "New programmers are usually in the search of ways to return multiple values from a function. Unfortunately, C and C++ do not allow this directly. But fortunately, with a little bit of clever programming, we can easily achieve this. Below are the methods to return multiple values from a function in C:"
},
{
"code": null,
"e": 409,
"s": 354,
"text": "By using pointers.By using structures.By using Arrays."
},
{
"code": null,
"e": 428,
"s": 409,
"text": "By using pointers."
},
{
"code": null,
"e": 449,
"s": 428,
"text": "By using structures."
},
{
"code": null,
"e": 466,
"s": 449,
"text": "By using Arrays."
},
{
"code": null,
"e": 776,
"s": 466,
"text": "Example: Consider an example where the task is to find the greater and smaller of two distinct numbers. We could write multiple functions. The main problem is the trouble of calling more than one functions since we need to return multiple values and of course, having more number of lines of code to be typed."
},
{
"code": null,
"e": 962,
"s": 776,
"text": "Returning multiple values Using pointers: Pass the argument with their address and make changes in their value using pointer. So that the values get changed into the original argument. "
},
{
"code": null,
"e": 1148,
"s": 962,
"text": "Returning multiple values Using pointers: Pass the argument with their address and make changes in their value using pointer. So that the values get changed into the original argument. "
},
{
"code": null,
"e": 1152,
"s": 1148,
"text": "C++"
},
{
"code": null,
"e": 1154,
"s": 1152,
"text": "C"
},
{
"code": "// Modified program using pointers#include <iostream>using namespace std; // add is the short name for addressvoid compare(int a, int b, int* add_great, int* add_small){ if (a > b) { // a is stored in the address pointed // by the pointer variable *add_great *add_great = a; *add_small = b; } else { *add_great = b; *add_small = a; }} // Driver codeint main(){ int great, small, x, y; cout << \"Enter two numbers: \\n\"; cin >> x >> y; // The last two arguments are passed // by giving addresses of memory locations compare(x, y, &great, &small); cout << \"\\nThe greater number is \" << great << \" and the smaller number is \" << small; return 0;} // This code is contributed by sarajadhav12052009",
"e": 1933,
"s": 1154,
"text": null
},
{
"code": "// Modified program using pointers#include <stdio.h> // add is the short name for addressvoid compare(int a, int b, int* add_great, int* add_small){ if (a > b) { // a is stored in the address pointed // by the pointer variable *add_great *add_great = a; *add_small = b; } else { *add_great = b; *add_small = a; }} // Driver codeint main(){ int great, small, x, y; printf(\"Enter two numbers: \\n\"); scanf(\"%d%d\", &x, &y); // The last two arguments are passed // by giving addresses of memory locations compare(x, y, &great, &small); printf(\"\\nThe greater number is %d and the smaller number is %d\", great, small); return 0;}",
"e": 2648,
"s": 1933,
"text": null
},
{
"code": null,
"e": 2724,
"s": 2648,
"text": "Enter two numbers: \n5 8\nThe greater number is 8 and the smaller number is 5"
},
{
"code": null,
"e": 2977,
"s": 2724,
"text": "Returning multiple values using structures : As the structure is a user-defined datatype. The idea is to define a structure with two integer variables and store the greater and smaller values into those variable, then use the values of that structure. "
},
{
"code": null,
"e": 3230,
"s": 2977,
"text": "Returning multiple values using structures : As the structure is a user-defined datatype. The idea is to define a structure with two integer variables and store the greater and smaller values into those variable, then use the values of that structure. "
},
{
"code": null,
"e": 3232,
"s": 3230,
"text": "C"
},
{
"code": "// Modified program using structures#include <stdio.h>struct greaterSmaller { int greater, smaller;}; typedef struct greaterSmaller Struct; Struct findGreaterSmaller(int a, int b){ Struct s; if (a > b) { s.greater = a; s.smaller = b; } else { s.greater = b; s.smaller = a; } return s;} // Driver codeint main(){ int x, y; Struct result; printf(\"Enter two numbers: \\n\"); scanf(\"%d%d\", &x, &y); // The last two arguments are passed // by giving addresses of memory locations result = findGreaterSmaller(x, y); printf(\"\\nThe greater number is %d and the\" \"smaller number is %d\", result.greater, result.smaller); return 0;}",
"e": 3952,
"s": 3232,
"text": null
},
{
"code": null,
"e": 4028,
"s": 3952,
"text": "Enter two numbers: \n5 8\nThe greater number is 8 and the smaller number is 5"
},
{
"code": null,
"e": 4414,
"s": 4028,
"text": "Returning multiple values using an array (Works only when returned items are of same types): When an array is passed as an argument then its base address is passed to the function so whatever changes made to the copy of the array, it is changed in the original array. Below is the program to return multiple values using array i.e. store greater value at arr[0] and smaller at arr[1]. "
},
{
"code": null,
"e": 4800,
"s": 4414,
"text": "Returning multiple values using an array (Works only when returned items are of same types): When an array is passed as an argument then its base address is passed to the function so whatever changes made to the copy of the array, it is changed in the original array. Below is the program to return multiple values using array i.e. store greater value at arr[0] and smaller at arr[1]. "
},
{
"code": null,
"e": 4804,
"s": 4800,
"text": "C++"
},
{
"code": null,
"e": 4806,
"s": 4804,
"text": "C"
},
{
"code": "// Modified program using array#include <iostream>using namespace std; // Store the greater element at 0th indexvoid findGreaterSmaller(int a, int b, int arr[]){ // Store the greater element at // 0th index of the array if (a > b) { arr[0] = a; arr[1] = b; } else { arr[0] = b; arr[1] = a; }} // Driver codeint main(){ int x, y; int arr[2]; cout << \"Enter two numbers: \\n\"; cin >> x >> y; findGreaterSmaller(x, y, arr); cout << \"\\nThe greater number is \" << arr[0] << \" and the \" \"smaller number is \" << arr[1]; return 0;} // This code is contributed by sarajadhav12052009",
"e": 5462,
"s": 4806,
"text": null
},
{
"code": "// Modified program using array#include <stdio.h> // Store the greater element at 0th indexvoid findGreaterSmaller(int a, int b, int arr[]){ // Store the greater element at // 0th index of the array if (a > b) { arr[0] = a; arr[1] = b; } else { arr[0] = b; arr[1] = a; }} // Driver codeint main(){ int x, y; int arr[2]; printf(\"Enter two numbers: \\n\"); scanf(\"%d%d\", &x, &y); findGreaterSmaller(x, y, arr); printf(\"\\nThe greater number is %d and the \" \"smaller number is %d\", arr[0], arr[1]); return 0;}",
"e": 6058,
"s": 5462,
"text": null
},
{
"code": null,
"e": 6134,
"s": 6058,
"text": "Enter two numbers: \n5 8\nThe greater number is 8 and the smaller number is 5"
},
{
"code": null,
"e": 6151,
"s": 6134,
"text": "C++ Only Methods"
},
{
"code": null,
"e": 6247,
"s": 6151,
"text": "Returning multiple values Using References: We use references in C++ to store returned values. "
},
{
"code": null,
"e": 6343,
"s": 6247,
"text": "Returning multiple values Using References: We use references in C++ to store returned values. "
},
{
"code": null,
"e": 6347,
"s": 6343,
"text": "CPP"
},
{
"code": "// Modified program using References in C++#include <stdio.h> void compare(int a, int b, int &add_great, int &add_small){ if (a > b) { add_great = a; add_small = b; } else { add_great = b; add_small = a; }} // Driver codeint main(){ int great, small, x, y; printf(\"Enter two numbers: \\n\"); scanf(\"%d%d\", &x, &y); // The last two arguments are passed // by giving addresses of memory locations compare(x, y, great, small); printf(\"\\nThe greater number is %d and the\" \"smaller number is %d\", great, small); return 0;}",
"e": 6950,
"s": 6347,
"text": null
},
{
"code": null,
"e": 7026,
"s": 6950,
"text": "Enter two numbers: \n5 8\nThe greater number is 8 and the smaller number is 5"
},
{
"code": null,
"e": 7259,
"s": 7026,
"text": "Returning multiple values using Class and Object : The idea is similar to structures. We create a class with two integer variables and store the greater and smaller values into those variable, then use the values of that structure. "
},
{
"code": null,
"e": 7492,
"s": 7259,
"text": "Returning multiple values using Class and Object : The idea is similar to structures. We create a class with two integer variables and store the greater and smaller values into those variable, then use the values of that structure. "
},
{
"code": null,
"e": 7496,
"s": 7492,
"text": "CPP"
},
{
"code": "// Modified program using class#include <stdio.h> class GreaterSmaller {public: int greater, smaller;}; GreaterSmaller findGreaterSmaller(int a, int b){ GreaterSmaller s; if (a > b) { s.greater = a; s.smaller = b; } else { s.greater = b; s.smaller = a; } return s;} // Driver codeint main(){ int x, y; GreaterSmaller result; printf(\"Enter two numbers: \\n\"); scanf(\"%d%d\", &x, &y); // The last two arguments are passed // by giving addresses of memory locations result = findGreaterSmaller(x, y); printf(\"\\nThe greater number is %d and the\" \"smaller number is %d\", result.greater, result.smaller); return 0;}",
"e": 8204,
"s": 7496,
"text": null
},
{
"code": null,
"e": 8280,
"s": 8204,
"text": "Enter two numbers: \n5 8\nThe greater number is 8 and the smaller number is 5"
},
{
"code": null,
"e": 8543,
"s": 8280,
"text": "Returning multiple values using STL tuple : The idea is similar to structures. We create a tuple with two integer variables and return the tuple, and then inside main function we use tie function to assign values to min and max that is returned by the function. "
},
{
"code": null,
"e": 8806,
"s": 8543,
"text": "Returning multiple values using STL tuple : The idea is similar to structures. We create a tuple with two integer variables and return the tuple, and then inside main function we use tie function to assign values to min and max that is returned by the function. "
},
{
"code": null,
"e": 8810,
"s": 8806,
"text": "CPP"
},
{
"code": "// Modified program using C++ STL tuple#include<iostream>#include<tuple> using namespace std; tuple <int, int> findGreaterSmaller(int a, int b){ if (a < b) { return make_tuple(a, b); } else { return make_tuple(b, a); }} // Driver codeint main(){ int x = 5, y= 8; int max, min; tie(min, max) = findGreaterSmaller(x, y); printf(\"The greater number is %d and the \" \"smaller number is %d\", max, min); return 0;} // This article is contributed by Blinkii",
"e": 9309,
"s": 8810,
"text": null
},
{
"code": null,
"e": 9361,
"s": 9309,
"text": "The greater number is 8 and the smaller number is 5"
},
{
"code": null,
"e": 9369,
"s": 9361,
"text": "Blinkii"
},
{
"code": null,
"e": 9382,
"s": 9369,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 9401,
"s": 9382,
"text": "sarajadhav12052009"
},
{
"code": null,
"e": 9410,
"s": 9401,
"text": "C-Arrays"
},
{
"code": null,
"e": 9422,
"s": 9410,
"text": "C-Functions"
},
{
"code": null,
"e": 9433,
"s": 9422,
"text": "C-Pointers"
},
{
"code": null,
"e": 9453,
"s": 9433,
"text": "C-Structure & Union"
},
{
"code": null,
"e": 9467,
"s": 9453,
"text": "CPP-Functions"
},
{
"code": null,
"e": 9479,
"s": 9467,
"text": "cpp-pointer"
},
{
"code": null,
"e": 9494,
"s": 9479,
"text": "cpp-references"
},
{
"code": null,
"e": 9505,
"s": 9494,
"text": "C Language"
},
{
"code": null,
"e": 9516,
"s": 9505,
"text": "C Programs"
},
{
"code": null,
"e": 9520,
"s": 9516,
"text": "C++"
},
{
"code": null,
"e": 9533,
"s": 9520,
"text": "C++ Programs"
},
{
"code": null,
"e": 9537,
"s": 9533,
"text": "CPP"
},
{
"code": null,
"e": 9635,
"s": 9537,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9652,
"s": 9635,
"text": "Substring in C++"
},
{
"code": null,
"e": 9674,
"s": 9652,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 9720,
"s": 9674,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 9765,
"s": 9720,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 9790,
"s": 9765,
"text": "std::string class in C++"
},
{
"code": null,
"e": 9803,
"s": 9790,
"text": "Strings in C"
},
{
"code": null,
"e": 9844,
"s": 9803,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 9873,
"s": 9844,
"text": "Basics of File Handling in C"
},
{
"code": null,
"e": 9911,
"s": 9873,
"text": "UDP Server-Client implementation in C"
}
] |
What is Data Science?
|
04 Feb, 2022
Data Science is an interdisciplinary field that focuses on extracting knowledge from data sets which are typically huge in amount. The field encompasses analysis, preparing data for analysis, and presenting findings to inform high-level decisions in an organization. As such, it incorporates skills from computer science, mathematics, statics, information visualization, graphic, and business.
Data is everywhere and is one of the most important features of every organization that helps a business to flourish by making decisions based on facts, statistical numbers, and trends. Due to this growing scope of data, data science came into picture which is a multidisciplinary IT field, and data scientist’s jobs are the most demanding in the 21st century. Data analysis/ Data science helps us to ensure we get answers for questions from data. Data science, and in essence, data analysis plays an important role by helping us to discover useful information from the data, answer questions, and even predict the future or the unknown. It uses scientific approaches, procedures, algorithms, the framework to extract the knowledge and insight from a huge amount of data.Data science is a concept to bring together ideas, data examination, Machine Learning, and their related strategies to comprehend and dissect genuine phenomena with data. It is an extension of data analysis fields such as data mining, statistics, predictive analysis. It is a huge field that uses a lot of methods and concepts which belong to other fields like in information science, statistics, mathematics, and computer science. Some of the techniques utilized in Data Science encompasses machine learning, visualization, pattern recognition, probability model, data engineering, signal processing, etc.Few important steps to help you work more successfully with data science projects:
Setting the research goal: Understanding the business or activity that our data science project is part of is key to ensuring its success and the first phase of any sound data analytics project. Defining the what, the why, and the how of our project in a project charter is the foremost task. Now sit down to define a timeline and concrete key performance indicators and this is the essential first step to kick-start our data initiative!
Retrieving data: Finding and getting access to the data needed in our project is the next step. Mixing and merging data from as many data sources as possible is what makes a data project great, so look as far as possible. This data is either found within the company or retrieved from a third party. So, here are a few ways to get ourselves some usable data: connecting to a database, using API’s or looking for open data.
Data preparation: The next data science step is the dreaded data preparation process that typically takes up to 80% of the time dedicated to our data project. Checking and remediating data errors, enriching the data with data from other data sources, and transforming it into a suitable format for your models.
Data exploration: Now that we have clean our data, it’s time to manipulate it to get the most value out of it. Diving deeper into our data using descriptive statistics and visual techniques is how we explore our data. One example of that is to enrich our data by creating time-based features, such as: Extracting date components (month, hour, day of the week, week of the year, etc.), Calculating differences between date columns or Flagging national holidays. Another way of enriching data is by joining datasets — essentially, retrieving columns from one data-set or tab into a reference data-set.
Presentation and automation: Presenting our results to the stakeholders and industrializing our analysis process for repetitive reuse and integration with other tools. When we are dealing with large volumes of data, visualization is the best way to explore and communicate our findings and is the next phase of our data analytics project.
Data modeling: Using machine learning and statistical techniques is the step to further achieve our project goal and predict future trends. By working with clustering algorithms, we can build models to uncover trends in the data that were not distinguishable in graphs and stats. These create groups of similar events (or clusters) and more or less explicitly express what feature is decisive in these results.
Data scientists straddle the world of both business and IT and possess unique skill sets. Their role has assumed significance thanks to how businesses today think of big data. Business wants to make use of the unstructured data which can boost their revenue. Data scientists analyze this information to make sense of it and bring out business insights that will aid in the growth of the business.
Now, let’s get started with the foremost topic i.e., Python Packages for Data Science which will be the stepping stone to start our Data Science journey. A Python library is a collection of functions and methods that allow us to perform lots of actions without writing any code.1. Scientific Computing Libraries:
Pandas — It is a two dimensional size-mutable, potentially heterogeneous tabular data structure with the labeled axis. It offers data structures and tools for effective manipulation and analysis. It provides fast access to structured data.Example:
Python3
import pandas as pd lst = ['I', 'Love', 'Data', 'Science']df = pd.DataFrame(lst) print(df)
Output:
Numpy — It uses arrays for its inputs and outputs. It can be extended to objects for matrices. It allows developers to perform fast array processing with minor coding changes.Example:
Python3
import numpy as np arr = np.array ([[1, 2, 3], [4, 6, 8]]) print("Array is of type: ", type(arr))print("No. of dimensions:", arr.ndim)print("Shape of array: ", arr.shape)
Output:
Array is of type: <class 'numpy.ndarray'>
No. od dimensions: 2
Shape of array: (2, 3)
Scipy — It is an open-source python-based library. It functions for some advanced math problems — integrals, differential equations, optimizations, and data visualizations. It is easy to use and understand as well as fast computational power.Example:
Python3
import numpy as npfrom scipy import miscimport matplotlib.pyplot as plt print ("I like ", np.pi)face = misc.face()plt.imshow(face)plt.show()
Output:
2. Visualization Libraries:
Matplotlib — It provides an object-oriented API for embedding plots into applications. Each pyplot function makes some changes to a figure. It creates a figure or plotting area in a figure, plots some lines in a plotting area.Example:
Python3
import matplotlib.pyplot as plt plt.plot([1, 2, 3, 4])plt.ylabel('some numbers') plt.show()
Output:
Seaborn — It is used for making statistical graphics. It provides a high-level interface for drawing attractive and informative graphics. It is very easy to generate in various plots such as heap maps, team series, violin plots.Example:
Python3
import seaborn as sns sns.set()tips = sns.load_dataset("tips")sns.relplot(x = "total_bill", y = "tip", col = "time", hue = "smoker", style = "smoker", size = "size", data = tips);
Output:
3. Algorithmic Libraries:
Scikit learn — It provides statistical modeling including regression, classification, clustering. It is a free software machine learning library for python programming. It uses NumPy for high-performance linear algebra and array operations.Example:
Python3
from sklearn import datasets iris = datasets.load_iris( )digits = datasets.load_digits( )print(digits)
Output:
{‘data’: array([[ 0., 0., 5., ..., 0., 0., 0.], [ 0., 0., 0., ..., 10., 0., 0.], [ 0., 0., 0., ..., 16., 9., 0.], ..., [ 0., 0., 1., ..., 6., 0., 0.], [ 0., 0., 2., ..., 12., 0., 0.], [ 0., 0., 10., ..., 12., 1., 0.]]), ‘target’: array([0, 1, 2, ..., 8, 9, 8]), ‘target_names’: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), ‘images’: array([[[ 0., 0., 5., ..., 1., 0., 0.], [ 0., 0., 13., ..., 15., 5., 0.], [ 0., 3., 15., ..., 11., 8., 0.], ..., [ 0., 4., 11., ..., 12., 7., 0.], [ 0., 2., 14., ..., 12., 0., 0.], [ 0., 0., 6., ..., 0., 0., 0.]],[[ 0., 0., 0., ..., 5., 0., 0.], [ 0., 0., 0., ..., 9., 0., 0.], [ 0., 0., 3., ..., 6., 0., 0.], ..., [ 0., 0., 1., ..., 6., 0., 0.], [ 0., 0., 1., ..., 6., 0., 0.], [ 0., 0., 0., ..., 10., 0., 0.]],[[ 0., 0., 0., ..., 12., 0., 0.], [ 0., 0., 3., ..., 14., 0., 0.], [ 0., 0., 8., ..., 16., 0., 0.], ..., [ 0., 9., 16., ..., 0., 0., 0.], [ 0., 3., 13., ..., 11., 5., 0.], [ 0., 0., 0., ..., 16., 9., 0.]],...,[[ 0., 0., 1., ..., 1., 0., 0.], [ 0., 0., 13., ..., 2., 1., 0.], [ 0., 0., 16., ..., 16., 5., 0.], ..., [ 0., 0., 16., ..., 15., 0., 0.], [ 0., 0., 15., ..., 16., 0., 0.], [ 0., 0., 2., ..., 6., 0., 0.]],[[ 0., 0., 2., ..., 0., 0., 0.], [ 0., 0., 14., ..., 15., 1., 0.], [ 0., 4., 16., ..., 16., 7., 0.], ..., [ 0., 0., 0., ..., 16., 2., 0.], [ 0., 0., 4., ..., 16., 2., 0.], [ 0., 0., 5., ..., 12., 0., 0.]],[[ 0., 0., 10., ..., 1., 0., 0.], [ 0., 2., 16., ..., 1., 0., 0.], [ 0., 0., 15., ..., 15., 0., 0.], ..., [ 0., 4., 16., ..., 16., 6., 0.], [ 0., 8., 16., ..., 16., 8., 0.], [ 0., 1., 8., ..., 12., 1., 0.]]]), ‘DESCR’: “.. _digits_dataset:\n\nOptical recognition of handwritten digits dataset\n————————————————–\n\n**Data Set Characteristics:**\n\n :Number of Instances: 5620\n :Number of Attributes: 64\n :Attribute Information: 8×8 image of integer pixels in the range 0..16.\n :Missing Attribute Values: None\n :Creator: E. Alpaydin (alpaydin ‘@’ boun.edu.tr)\n :Date: July; 1998\n\nThis is a copy of the test set of the UCI ML hand-written digits datasets\nhttps://archive.ics.uci.edu/ml/datasets/Optical+Recognition+of+Handwritten+Digits\n\nThe data set contains images of hand-written digits: 10 classes where\neach class refers to a digit.\n\nPreprocessing programs made available by NIST were used to extract\nnormalized bitmaps of handwritten digits from a preprinted form. From a\ntotal of 43 people, 30 contributed to the training set and different 13\nto the test set. 32×32 bitmaps are divided into nonoverlapping blocks of\n4x4 and the number of on pixels are counted in each block. This generates\nan input matrix of 8×8 where each element is an integer in the range\n0..16. This reduces dimensionality and gives invariance to small\ndistortions.\n\nFor info on NIST preprocessing routines, see M. D. Garris, J. L. Blue, G.\nT. Candela, D. L. Dimmick, J. Geist, P. J. Grother, S. A. Janet, and C.\nL. Wilson, NIST Form-Based Handprint Recognition System, NISTIR 5469, \n1994.\n\n.. topic:: References\n\n – C. Kaynak (1995) Methods of Combining Multiple Classifiers and Their\n Applications to Handwritten Digit Recognition, MSc Thesis, Institute of\n Graduate Studies in Science and Engineering, Bogazici University.\n – E. Alpaydin, C. Kaynak (1998) Cascading Classifiers, Kybernetika.\n – Ken Tang and Ponnuthurai N. Suganthan and Xi Yao and A. Kai Qin.\n Linear dimensionalityreduction using relevance weighted LDA. School of\n Electrical and Electronic Engineering Nanyang Technological University.\n 2005.\n – Claudio Gentile. A New Approximate Maximal Margin Classification\n Algorithm. NIPS. 2000.”}
Stats model — It is built on NumPy and SciPy. It allows users to explore data, estimate statistical models, and perform tests. It also uses Pandas for data handling and Patsy for the R-like formula interface.Example:
Python3
import numpy as npimport statsmodels.api as smimport statsmodels.formula.api as smf dat = sm.datasets.get_rdataset("Guerry", "HistData").dataresults = smf.ols('Lottery ~ Literacy + np.log(Pop1831)', data = dat).fit() print(results.summary())
Output:
sagar0719kumar
data-science
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n04 Feb, 2022"
},
{
"code": null,
"e": 448,
"s": 53,
"text": "Data Science is an interdisciplinary field that focuses on extracting knowledge from data sets which are typically huge in amount. The field encompasses analysis, preparing data for analysis, and presenting findings to inform high-level decisions in an organization. As such, it incorporates skills from computer science, mathematics, statics, information visualization, graphic, and business. "
},
{
"code": null,
"e": 1908,
"s": 448,
"text": "Data is everywhere and is one of the most important features of every organization that helps a business to flourish by making decisions based on facts, statistical numbers, and trends. Due to this growing scope of data, data science came into picture which is a multidisciplinary IT field, and data scientist’s jobs are the most demanding in the 21st century. Data analysis/ Data science helps us to ensure we get answers for questions from data. Data science, and in essence, data analysis plays an important role by helping us to discover useful information from the data, answer questions, and even predict the future or the unknown. It uses scientific approaches, procedures, algorithms, the framework to extract the knowledge and insight from a huge amount of data.Data science is a concept to bring together ideas, data examination, Machine Learning, and their related strategies to comprehend and dissect genuine phenomena with data. It is an extension of data analysis fields such as data mining, statistics, predictive analysis. It is a huge field that uses a lot of methods and concepts which belong to other fields like in information science, statistics, mathematics, and computer science. Some of the techniques utilized in Data Science encompasses machine learning, visualization, pattern recognition, probability model, data engineering, signal processing, etc.Few important steps to help you work more successfully with data science projects:"
},
{
"code": null,
"e": 2349,
"s": 1908,
"text": "Setting the research goal: Understanding the business or activity that our data science project is part of is key to ensuring its success and the first phase of any sound data analytics project. Defining the what, the why, and the how of our project in a project charter is the foremost task. Now sit down to define a timeline and concrete key performance indicators and this is the essential first step to kick-start our data initiative! "
},
{
"code": null,
"e": 2774,
"s": 2349,
"text": "Retrieving data: Finding and getting access to the data needed in our project is the next step. Mixing and merging data from as many data sources as possible is what makes a data project great, so look as far as possible. This data is either found within the company or retrieved from a third party. So, here are a few ways to get ourselves some usable data: connecting to a database, using API’s or looking for open data. "
},
{
"code": null,
"e": 3087,
"s": 2774,
"text": "Data preparation: The next data science step is the dreaded data preparation process that typically takes up to 80% of the time dedicated to our data project. Checking and remediating data errors, enriching the data with data from other data sources, and transforming it into a suitable format for your models. "
},
{
"code": null,
"e": 3689,
"s": 3087,
"text": "Data exploration: Now that we have clean our data, it’s time to manipulate it to get the most value out of it. Diving deeper into our data using descriptive statistics and visual techniques is how we explore our data. One example of that is to enrich our data by creating time-based features, such as: Extracting date components (month, hour, day of the week, week of the year, etc.), Calculating differences between date columns or Flagging national holidays. Another way of enriching data is by joining datasets — essentially, retrieving columns from one data-set or tab into a reference data-set. "
},
{
"code": null,
"e": 4030,
"s": 3689,
"text": "Presentation and automation: Presenting our results to the stakeholders and industrializing our analysis process for repetitive reuse and integration with other tools. When we are dealing with large volumes of data, visualization is the best way to explore and communicate our findings and is the next phase of our data analytics project. "
},
{
"code": null,
"e": 4443,
"s": 4030,
"text": "Data modeling: Using machine learning and statistical techniques is the step to further achieve our project goal and predict future trends. By working with clustering algorithms, we can build models to uncover trends in the data that were not distinguishable in graphs and stats. These create groups of similar events (or clusters) and more or less explicitly express what feature is decisive in these results. "
},
{
"code": null,
"e": 4843,
"s": 4445,
"text": "Data scientists straddle the world of both business and IT and possess unique skill sets. Their role has assumed significance thanks to how businesses today think of big data. Business wants to make use of the unstructured data which can boost their revenue. Data scientists analyze this information to make sense of it and bring out business insights that will aid in the growth of the business. "
},
{
"code": null,
"e": 5157,
"s": 4843,
"text": "Now, let’s get started with the foremost topic i.e., Python Packages for Data Science which will be the stepping stone to start our Data Science journey. A Python library is a collection of functions and methods that allow us to perform lots of actions without writing any code.1. Scientific Computing Libraries: "
},
{
"code": null,
"e": 5406,
"s": 5157,
"text": "Pandas — It is a two dimensional size-mutable, potentially heterogeneous tabular data structure with the labeled axis. It offers data structures and tools for effective manipulation and analysis. It provides fast access to structured data.Example: "
},
{
"code": null,
"e": 5414,
"s": 5406,
"text": "Python3"
},
{
"code": "import pandas as pd lst = ['I', 'Love', 'Data', 'Science']df = pd.DataFrame(lst) print(df)",
"e": 5506,
"s": 5414,
"text": null
},
{
"code": null,
"e": 5514,
"s": 5506,
"text": "Output:"
},
{
"code": null,
"e": 5698,
"s": 5514,
"text": "Numpy — It uses arrays for its inputs and outputs. It can be extended to objects for matrices. It allows developers to perform fast array processing with minor coding changes.Example:"
},
{
"code": null,
"e": 5706,
"s": 5698,
"text": "Python3"
},
{
"code": "import numpy as np arr = np.array ([[1, 2, 3], [4, 6, 8]]) print(\"Array is of type: \", type(arr))print(\"No. of dimensions:\", arr.ndim)print(\"Shape of array: \", arr.shape)",
"e": 5878,
"s": 5706,
"text": null
},
{
"code": null,
"e": 5886,
"s": 5878,
"text": "Output:"
},
{
"code": null,
"e": 5974,
"s": 5886,
"text": "Array is of type: <class 'numpy.ndarray'>\nNo. od dimensions: 2\nShape of array: (2, 3)"
},
{
"code": null,
"e": 6226,
"s": 5974,
"text": "Scipy — It is an open-source python-based library. It functions for some advanced math problems — integrals, differential equations, optimizations, and data visualizations. It is easy to use and understand as well as fast computational power.Example: "
},
{
"code": null,
"e": 6234,
"s": 6226,
"text": "Python3"
},
{
"code": "import numpy as npfrom scipy import miscimport matplotlib.pyplot as plt print (\"I like \", np.pi)face = misc.face()plt.imshow(face)plt.show()",
"e": 6376,
"s": 6234,
"text": null
},
{
"code": null,
"e": 6384,
"s": 6376,
"text": "Output:"
},
{
"code": null,
"e": 6413,
"s": 6384,
"text": "2. Visualization Libraries: "
},
{
"code": null,
"e": 6649,
"s": 6413,
"text": "Matplotlib — It provides an object-oriented API for embedding plots into applications. Each pyplot function makes some changes to a figure. It creates a figure or plotting area in a figure, plots some lines in a plotting area.Example: "
},
{
"code": null,
"e": 6657,
"s": 6649,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as plt plt.plot([1, 2, 3, 4])plt.ylabel('some numbers') plt.show()",
"e": 6750,
"s": 6657,
"text": null
},
{
"code": null,
"e": 6758,
"s": 6750,
"text": "Output:"
},
{
"code": null,
"e": 6996,
"s": 6758,
"text": "Seaborn — It is used for making statistical graphics. It provides a high-level interface for drawing attractive and informative graphics. It is very easy to generate in various plots such as heap maps, team series, violin plots.Example: "
},
{
"code": null,
"e": 7004,
"s": 6996,
"text": "Python3"
},
{
"code": "import seaborn as sns sns.set()tips = sns.load_dataset(\"tips\")sns.relplot(x = \"total_bill\", y = \"tip\", col = \"time\", hue = \"smoker\", style = \"smoker\", size = \"size\", data = tips);",
"e": 7251,
"s": 7004,
"text": null
},
{
"code": null,
"e": 7259,
"s": 7251,
"text": "Output:"
},
{
"code": null,
"e": 7286,
"s": 7259,
"text": "3. Algorithmic Libraries: "
},
{
"code": null,
"e": 7535,
"s": 7286,
"text": "Scikit learn — It provides statistical modeling including regression, classification, clustering. It is a free software machine learning library for python programming. It uses NumPy for high-performance linear algebra and array operations.Example:"
},
{
"code": null,
"e": 7543,
"s": 7535,
"text": "Python3"
},
{
"code": "from sklearn import datasets iris = datasets.load_iris( )digits = datasets.load_digits( )print(digits)",
"e": 7646,
"s": 7543,
"text": null
},
{
"code": null,
"e": 7654,
"s": 7646,
"text": "Output:"
},
{
"code": null,
"e": 11237,
"s": 7654,
"text": "{‘data’: array([[ 0., 0., 5., ..., 0., 0., 0.], [ 0., 0., 0., ..., 10., 0., 0.], [ 0., 0., 0., ..., 16., 9., 0.], ..., [ 0., 0., 1., ..., 6., 0., 0.], [ 0., 0., 2., ..., 12., 0., 0.], [ 0., 0., 10., ..., 12., 1., 0.]]), ‘target’: array([0, 1, 2, ..., 8, 9, 8]), ‘target_names’: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), ‘images’: array([[[ 0., 0., 5., ..., 1., 0., 0.], [ 0., 0., 13., ..., 15., 5., 0.], [ 0., 3., 15., ..., 11., 8., 0.], ..., [ 0., 4., 11., ..., 12., 7., 0.], [ 0., 2., 14., ..., 12., 0., 0.], [ 0., 0., 6., ..., 0., 0., 0.]],[[ 0., 0., 0., ..., 5., 0., 0.], [ 0., 0., 0., ..., 9., 0., 0.], [ 0., 0., 3., ..., 6., 0., 0.], ..., [ 0., 0., 1., ..., 6., 0., 0.], [ 0., 0., 1., ..., 6., 0., 0.], [ 0., 0., 0., ..., 10., 0., 0.]],[[ 0., 0., 0., ..., 12., 0., 0.], [ 0., 0., 3., ..., 14., 0., 0.], [ 0., 0., 8., ..., 16., 0., 0.], ..., [ 0., 9., 16., ..., 0., 0., 0.], [ 0., 3., 13., ..., 11., 5., 0.], [ 0., 0., 0., ..., 16., 9., 0.]],...,[[ 0., 0., 1., ..., 1., 0., 0.], [ 0., 0., 13., ..., 2., 1., 0.], [ 0., 0., 16., ..., 16., 5., 0.], ..., [ 0., 0., 16., ..., 15., 0., 0.], [ 0., 0., 15., ..., 16., 0., 0.], [ 0., 0., 2., ..., 6., 0., 0.]],[[ 0., 0., 2., ..., 0., 0., 0.], [ 0., 0., 14., ..., 15., 1., 0.], [ 0., 4., 16., ..., 16., 7., 0.], ..., [ 0., 0., 0., ..., 16., 2., 0.], [ 0., 0., 4., ..., 16., 2., 0.], [ 0., 0., 5., ..., 12., 0., 0.]],[[ 0., 0., 10., ..., 1., 0., 0.], [ 0., 2., 16., ..., 1., 0., 0.], [ 0., 0., 15., ..., 15., 0., 0.], ..., [ 0., 4., 16., ..., 16., 6., 0.], [ 0., 8., 16., ..., 16., 8., 0.], [ 0., 1., 8., ..., 12., 1., 0.]]]), ‘DESCR’: “.. _digits_dataset:\\n\\nOptical recognition of handwritten digits dataset\\n————————————————–\\n\\n**Data Set Characteristics:**\\n\\n :Number of Instances: 5620\\n :Number of Attributes: 64\\n :Attribute Information: 8×8 image of integer pixels in the range 0..16.\\n :Missing Attribute Values: None\\n :Creator: E. Alpaydin (alpaydin ‘@’ boun.edu.tr)\\n :Date: July; 1998\\n\\nThis is a copy of the test set of the UCI ML hand-written digits datasets\\nhttps://archive.ics.uci.edu/ml/datasets/Optical+Recognition+of+Handwritten+Digits\\n\\nThe data set contains images of hand-written digits: 10 classes where\\neach class refers to a digit.\\n\\nPreprocessing programs made available by NIST were used to extract\\nnormalized bitmaps of handwritten digits from a preprinted form. From a\\ntotal of 43 people, 30 contributed to the training set and different 13\\nto the test set. 32×32 bitmaps are divided into nonoverlapping blocks of\\n4x4 and the number of on pixels are counted in each block. This generates\\nan input matrix of 8×8 where each element is an integer in the range\\n0..16. This reduces dimensionality and gives invariance to small\\ndistortions.\\n\\nFor info on NIST preprocessing routines, see M. D. Garris, J. L. Blue, G.\\nT. Candela, D. L. Dimmick, J. Geist, P. J. Grother, S. A. Janet, and C.\\nL. Wilson, NIST Form-Based Handprint Recognition System, NISTIR 5469, \\n1994.\\n\\n.. topic:: References\\n\\n – C. Kaynak (1995) Methods of Combining Multiple Classifiers and Their\\n Applications to Handwritten Digit Recognition, MSc Thesis, Institute of\\n Graduate Studies in Science and Engineering, Bogazici University.\\n – E. Alpaydin, C. Kaynak (1998) Cascading Classifiers, Kybernetika.\\n – Ken Tang and Ponnuthurai N. Suganthan and Xi Yao and A. Kai Qin.\\n Linear dimensionalityreduction using relevance weighted LDA. School of\\n Electrical and Electronic Engineering Nanyang Technological University.\\n 2005.\\n – Claudio Gentile. A New Approximate Maximal Margin Classification\\n Algorithm. NIPS. 2000.”} "
},
{
"code": null,
"e": 11455,
"s": 11237,
"text": "Stats model — It is built on NumPy and SciPy. It allows users to explore data, estimate statistical models, and perform tests. It also uses Pandas for data handling and Patsy for the R-like formula interface.Example: "
},
{
"code": null,
"e": 11463,
"s": 11455,
"text": "Python3"
},
{
"code": "import numpy as npimport statsmodels.api as smimport statsmodels.formula.api as smf dat = sm.datasets.get_rdataset(\"Guerry\", \"HistData\").dataresults = smf.ols('Lottery ~ Literacy + np.log(Pop1831)', data = dat).fit() print(results.summary())",
"e": 11722,
"s": 11463,
"text": null
},
{
"code": null,
"e": 11730,
"s": 11722,
"text": "Output:"
},
{
"code": null,
"e": 11745,
"s": 11730,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 11758,
"s": 11745,
"text": "data-science"
},
{
"code": null,
"e": 11765,
"s": 11758,
"text": "Python"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.